POPULARITY
We got our WLED-friend PCBs today, and we only made one mistake: the wrong resistor on the 3.3V feedback line. Now that it's fixed, the board seems to work great with the latest version of WLED (https://kno.wled.ge/basics/tutorials/)! we are checking all 4 signal outputs with this handy 256-LED grid that sits on our desk. Next, we will test the onboard IR receiver, USB PD, I2S microphone, extra I/O pins, and I2C. We'll also do an Arduino IDE board definition in case folks want to use it as a generic ESP32-to-LED-driver board. We're calling the board "Sparkle Motion" for now, but if you have other naming ideas, let us know - if we pick your name, you get a free board (https://www.adafruit.com/product/6100). Sign up, coming soon. Visit the Adafruit shop online - http://www.adafruit.com ----------------------------------------- LIVE CHAT IS HERE! http://adafru.it/discord Subscribe to Adafruit on YouTube: http://adafru.it/subscribe New tutorials on the Adafruit Learning System: http://learn.adafruit.com/ ----------------------------------------- #wled #ledscreen #electronics
This week's EYE ON NPI is Perfect and Looking Cool - We're checking out the Arduino Opta line of programmable PLCs (https://www.digikey.com/en/product-highlight/a/arduino/opta-expansions). PLC stands for "programmable logic controller" (https://en.wikipedia.org/wiki/Programmable_logic_controller) and these devices are used in manufacturing and robotics to automate sensor inputs and robotic control outputs in factories. Because of dependable PLC performance, your food, clothing, medicine and water are affordable and high quality, with repeatable results. Manufacturing engineers have used PLCs since the 80's, and they've been essential for the 3rd Industrial Revolution (https://en.wikipedia.org/wiki/Information_Age). If in the second industrial revolution moved us from individually-manufactured handmade goods (https://en.wikipedia.org/wiki/Handicraft) to assembly-line repeatability (https://en.wikipedia.org/wiki/Assembly_line), then the information age and PLCs took us from the back-breaking work of doing the same task day-in-day-out to robots (https://www.youtube.com/watch?v=CjL_dQ5HAAg). Tasks like: measuring out the exact weight or count of product, applying labels, heating to temperature and holding it there for 45 minutes. While designing the machines that do this automatically is also time-consuming expensive, it's something you only have to do once. The Opta was designed in collaboration with Finder, (https://opta.findernet.com/en/) an Italian company like Arduino, which specializes in PLC design. This is a great team-up because Finder already had a family automation products and tools, so it has the industrial experience whereas Arduino has the IDE, cloud and PCB-design skills to bring in the user experience. The Opta family looks like a classic PLC, with screw terminal inputs and outputs. There are LEDs embedded to the case that can be controlled, as well as analog inputs, digital IO and built in power relays. All of the IO ports have wide voltage ranges like 0-10V and are well protected from under/over-volting, short-circuiting or ESD. Inside is an STM32H747XI (https://www.digikey.com/short/hzr2rnv2), a ultra-powerful Cortex M7 @ 480MHz + Cortex M4 @ 240MHz chip with a ton of SRAM and Flash. It can easily run an entire factory! Some versions have WiFi, Ethernet, or RS-485 for connectivity - however they are all designed to run standalone. Traditional PLCs are completely opaque, to the point where you have to use only the proprietary software that the vendor provides. What's nice about the Opta (https://www.digikey.com/short/jbb74j41) is you get to use the Arduino IDE, which has integrated support with a couple different programming systems. (https://docs.arduino.cc/software/plc-ide/tutorials/plc-programming-introduction/) You can of course use the classic Arduino sketch system (https://opta.findernet.com/en/tutorial/getting-started) and use digitalWrite(), analogRead() and all the other C++ capabilities of the classic IDE. But you can also use the classic "IEC 61131-3 programming languages" (https://en.wikipedia.org/wiki/IEC_61131-3), Structured Text ST, Instruction List IL, Ladder Diagram LD, Sequential Function Chart SFC, and Function Block Diagram FBD. These are somewhat archaic languages, but many mechanical engineers are trained in their use, so the Opta is a nice transitionary device. There's also expansion options so if you want more digital input pins and relays, you can plug a port on (https://www.digikey.com/en/product-highlight/a/arduino/opta-expansions) which will give you 16 more inputs and 8 more SSR or electromechanial relay outputs. If you've ever been curious about how PLCs work, or if you want to maintain, upgrade or repair factory equiptment, the Arduino + Finder Opta (https://www.digikey.com/short/jbb74j41) is an great product which will let you replicate the microcontroller experience to industrial automation. And best of all, it's in stock right now at DigiKey! Order today and DigiKey will ship your Opta immediately so that you can be manufacturing the future by tomorrow afternoon.
GB2RS News Sunday the 25th of August 2024 The news headlines: The RSGB 2024 Convention will feature a microcontroller programming workshop You can take the RSGB Morse competency test at National Hamfest this year RSGB Board Director Peter Bowyer, G4MJS to take on Board Liaison roles for contesting and trophies At this year's RSGB Convention, there will be a workshop to introduce attendees to microcontroller programming through a short presentation followed by practical exercises. The Society aims to widen the programming skills in the amateur radio community and introduce individuals to radio-related usage of Micro Controller Units, or MCUs. If you attend the workshop, you will receive a genuine Arduino board, a set of DuPont wires, a breadboard and two specific devices which you will be able to take away with you at the end of the workshop. The exercises will take you through using the Arduino IDE, basic programming and interfacing to the provided devices. You need to pre-register as spaces are limited to just 20 people. The workshop and hardware are free, but in return for the £10 booking fee, you will receive a copy of the book “Microcontroller Know How” by Mark Jones, G0MGX. You must be a ticket holder for the Convention to be able to take part. To find out more and to book your place, go to the RSGB website at rsgb.org/convention and choose the workshops and forums tab on the right-hand menu. If you're going to the National Hamfest on the 27th and 28th of September, why not try the RSGB Morse competency test? You don't have to book in advance, just visit the RSGB village area. You can be tested at 10, 12, 15, 20, 25 or 30 words per minute so you don't have to be a CW expert. If you pass the test, you'll either receive a certificate on the day or it will be sent to you electronically shortly after. Eric Arkinstall, M0KZB is the RSGB Morse Competency Project Lead and he will guide you through the test process. If you don't want to do the test you can still drop in to try Morse for the first time or pick up some hints and tips. It will be a busy event so whilst there will be headphones available, you're welcome to bring your own if you prefer. Eric looks forward to seeing you at the event! If you have any questions, please contact Eric via morse.tests@rsgb.org.uk The RSGB Board Chair has announced that new Director Peter Bowyer, G4MJS will take on the Board Liaison roles for contesting and trophies. If you would like to contact Peter, his email address is g4mjs@rsgb.org.uk This year's Youngsters on the Air camp in the Czech Republic finished on Friday the 23rd of August after an action-packed week. The RSGB representative Rhys Williams, M0WGY took part in a range of amateur radio activities that included kit building, ARDF and surface-mount technology as well as a day trip into Prague. Rhys also made the most of the great station setup and enjoyed plenty of airtime. This included making over 100 QSOs on the 40m band whilst operating special callsign OL24YOTA, which he has said was good to practise his pile-up management. You can read more from Rhys by going to rsgb.org/yota-camp and reading his daily blog. This year's camp was organised by the IARU Region 1 Youth Working Group together with the Czech Radio Club. The next event in the popular 145 Alive series takes place on Sunday the 29th of September 2024. The event will run from 1 pm to 4 pm and there will be nets operating in most Maidenhead Squares across England, Scotland, Wales and Ireland. To take part in the event, which is designed to promote FM activity on the 2m band, all you need to do is call in and make contact with others. The organisers are looking for more net controllers. If you would like to run a net, contact Mark Savage, M0XIC via the 145 Alive Facebook page. The date has been confirmed for the Twelfth Scottish Microwave Round Table GMRT. The event will take place on Saturday the 9th of November 2024 at the Museum of Communication, Burntisland, Fife. Lunch will be provided and an optional dinner will be held in the evening at a local hotel. The programme is now confirmed and online booking is available via the GMRT website at gmroundtable.org.uk or by emailing Colin, GM4HWO at gm4hwo@gmail.com National Hamfest is only a few weeks away. Early-bird advance tickets are currently available but this offer finishes on Saturday the 31st of August. Visit nationalhamfest.org.uk for more details and booking information. And finally, don't forget to listen out for all the stations that are on the air for the British Inland Waterways on the Air event this weekend. To read more about the event visit Nunsfield House Amateur Radio Group's website at nharg.org.uk and follow the ‘BIWOTA 2024' link. And now for details of rallies and events Milton Keynes Amateur Radio Society Rally is taking place today, the 25th. The venue is Heron's Lodge Guide Activity Centre, Bradwell Road, Loughton Lodge, Milton Keynes, MK8 9AA. The doors open to the public from 9 am. The entrance fee is £3 and free parking is available. For trader and exhibitor enquiries please email rally@mkars.org.uk Outdoor pitches and indoor tables are available. For more information visit mkars.org.uk Torbay Annual Communications Fair is also taking place today, the 25th, at Newton Abbot Racecourse, TQ12 3AF from 10 am. This is an indoor event with free parking, a bring-and-buy area, an RSGB bookstall and on-site catering. For more information email rally@tars.org.uk Huntingdonshire Amateur Radio Society Annual Rally is taking place tomorrow, Monday the 26th, at Ernulf Academy, St Neots, PE19 2SH. The gates open for traders at 7 am and for the public at 9 am. The entrance fee is £3. Free car parking, an RSGB bookstall, a bring-and-buy area, catering, and indoor and outdoor stalls will be available. For more information email henry_hirst@hotmail.com or phone 01480 214282. Saffron Walden Radio Ham and CB Club Rally will run from Friday the 30th of August to Sunday the 1st of September in the CM22 6BH area. For more information about fees, and directions, visit the event's Facebook page or email swrc73@gmail.com Telford Hamfest is set to take place on Sunday the 1st of September at Harper Adams University near Newport, Shropshire. The doors open at 10.15 am and admission is £5. Children up to age 16 will be admitted free of charge. Free parking, catering, an RSGB bookstall, and a bring-and-buy area will be available on site. For more details visit tdars.org.uk or email John, M0JZH at hamfest@tdars.org.uk September marks the golden anniversary of the G-QRP Club, which was started by the Reverend George Dobbs, G3RJV in 1974. The Club will be marking its 50th anniversary at its annual Convention over the weekend of the 31st of August to the 1st of September. The event takes place in parallel with the Telford Hamfest at the Harper Adams University Campus near Newport, Shropshire. Following a buildathon and social supper on the Saturday, there are a number of speakers lined up on Sunday, including Hans Summers, G0UPL talking about his QRP kits. Non-members are welcome to come along on the Sunday and enjoy the Hamfest and the G-QRP Club talks. Full details are on the G-QRP Club website at gqrp.com Following the Convention, the Club is running an activity period called ‘Low and Clear' throughout September. A number of QRP stations are being activated across the UK and in other countries, with ‘LOW' or ‘QRP' in their special callsigns. Stations working a number of them will receive a certificate, and the ‘best' logs will be awarded prizes which have been donated by traders who advertise in the Club's journal Sprat. Again, details can be found on the Club's website. You can find details of a new RSGB book celebrating 50 years of the G-QRP Club in the September issue of RadCom. Now the Special Event news Special callsign YQ60YODXC is active until the 31st of August to celebrate the 60th anniversary of the YO DX Club. For details of certificates that are available, see QRZ.com Marking the 25th anniversary since Poland joined the North Atlantic Treaty Organisation, special callsign HF25NATO will be active until the 31st of August. QSL via Logbook of the World or Club Log's OQRS. A certificate will be available for download via tinyurl.com/hf25nato Now the DX news Today, the 25th, a team from Guernsey Amateur Radio Society is operating a Parks on the Air station on Lihou Island, just off the coast of Guernsey. The park reference for the location is GG-0005 and activity is planned from 6 am to 3 pm. Operators will be using SSB and data modes on the HF bands but will also be available on the 2m band for local calls. Alex, SQ9UM is active as D4UM from Sal Island, AF-086, in Cape Verde until tomorrow, the 26th. He is operating CW, SSB, FT8 and FT4 on the 80 to 6m bands. QSL via Alex's home call. QSOs will be uploaded to ClubLog. Holger, DG3FEH is active as S79/DG3FEH from Mahe [MA-HAY], AF-024, in the Seychelles until the 27th of August. He is operating using SSB on the 40, 20 and 15m bands and also via the QO-100 satellite. QSL via the Bureau to Holger's home call. Now the contest news The World-Wide Digi DX Contest started at 1200UTC on Saturday the 24th of August and runs until 1200UTC today, Sunday the 25th of August. Using FT4 and FT8 on the 160 to 10m bands, where contests are permitted, the exchange is your four-character locator. Today, the 25th, the UK Microwave Group 5.7 and 10GHz Contest runs from 0600 to 1800UTC. Using all modes on 5.7 and 10GHz frequencies, the exchange is signal report, serial number and locator. On Tuesday the 27th, the SHF UK Activity Contest runs from 1830 to 2130UTC. Using all modes on 2.3 to 10GHz frequencies, the exchange is signal report, serial number and locator. The UK and Ireland Contest Club DX SSB Contest starts at 1200UTC on Saturday the 31st of August and runs until 1200UTC on Sunday the 1st of September. Using SSB on the 80 to 10m bands, where contests are permitted, the exchange is signal report and serial number. UK and Ireland stations also send their district code. The Worked All Britain DX Contest starts at 1200UTC on Saturday the 31st of August and runs until 1200UTC on Sunday the 1st of September. The exchange is a report, serial number and Worked All Britain square, where applicable. Entries need to be with the contest manager by the 11th of September. Visit the Worked All Britain website for more information and to read more on the rules for the contest. Now the radio propagation report, compiled by G0KYA, G3YLA, and G4BAO on Thursday the 22nd of August 2024 We had yet another week with a high solar flux and relatively calm geomagnetic conditions. The solar flux index ended up at 239 on Thursday the 22nd, while the Kp index has been below 4 since Sunday the 18th. There are currently 11 active sunspot regions on the Sun's surface and there is a 20% chance of a major X-class solar flare according to the NOAA Space Weather Prediction Center. There are signs that HF propagation may be improving, but it will probably be another month or so before we see any large change. This is due to the summer doldrums that see the ionosphere harder to ionise due to a change in its chemical composition. By mid to late September, we will start to see a change to autumnal conditions and DX will start to open up again on the higher bands. Having said that, there is still DX to be had. The N5J DXpedition to Jarvis Island in the Pacific Ocean proved that the DX is workable, but the path was mainly open to well-equipped stations with beams and linear amplifiers. 15m remains the best DX band and there are occasional openings on the 12m band. The 10m band may come into its own as we head into September and October. According to the NOAA Space Weather Prediction Center, solar cycle 25 likely reached its highest sunspot number yet of at least 299 on the 8th of August. This may increase further, but we may be close to solar maximum. Next week, NOAA predicts that the solar flux index will remain around 200 to 210. Geomagnetic conditions will depend almost entirely on the occurrence of coronal mass ejections, or CMEs. And, as we are at a particularly active part of the solar cycle, flares and CMEs are very prevalent. And now the VHF and up propagation news from G3YLA and G4BAO The overview for the coming week is that, although some fronts will affect the north and west at times, there are only a few that reach down to the southeast of Britain. This means that rain scatter is more likely in northern areas. There will be weak high pressure over southern areas for much of the coming week and, although not enough for a full-blown Tropo event, conditions should be a little ‘up', especially for paths into the near continent or across the North Sea. Meteor scatter is back to a more random approach since the broad peak of the August Perseids comes to an end. The solar conditions mean that auroras can be a possible element of operating excitement in the coming week. Remember to look out for a disturbed Kp index value of 6 or greater. The last part of the sporadic-E season is playing out this week taking us to the end of the month. These 'last hurrahs' are usually characterised by QSOs of very limited duration on the 10m band, or perhaps up to 6m, and mainly over the southern half of Europe. This usually favours southern UK stations but, notwithstanding the previous comments, some years have seen isolated Sporadic-E events in the first part of September. But they are certainly not reliable. Moon declination is positive but still rising, reaching maximum on Wednesday, so long Moon visibility windows and high peak elevations continue. We are past perigee now, so path losses are increasing again. 144MHz sky noise is low but increasing to a moderate 500 Kelvin on Wednesday before falling back to low at the end of the week. And that's all from the propagation team this week.
This week's Electromaker Show is now available on YouTube and everywhere you get your podcasts! Welcome to the Electromaker Show episode 135! This week we investigate how a Raspberry Pi survived a multi year bath, how Arduino are bringing their IDE to the cloud, and look at one of the most powerful and fully featured MCU dev boards yet! Tune in for the latest maker, tech, DIY, IoT, embedded, and crowdfunding news stories from the week. Watch the show! We publish a new show every week. Subscribe here: https://www.youtube.com/channel/UCiMO2NHYWNiVTzyGsPYn4DA?sub_confirmation=1 We stock the latest products from Adafruit, Seeed Studio, Pimoroni, Sparkfun, and many more! Browse our shop: https://www.electromaker.io/shop Join us on Discord! https://discord.com/invite/w8d7mkCkxj Follow us on Twitter: https://twitter.com/ElectromakerIO Like us on Facebook: https://www.facebook.com/electromaker.io/ Follow us on Instagram: https://www.instagram.com/electromaker_io/ Featured in this show: Arduino IDE in the cloud Arduino Open Source Report Raspberry Pi Running Underwater NEXTPCB Sponsored Section: New Online Gerber Viewer NEXTPCB Sponsored Section: What is DFA NEXTPCB Sponsored Section: Free PCBA Manufacture for Businesses Aventen Formosa Sync Kaching Karaoke: Repurposing a Cash Register Printer
Want to learn more? Check out our Membership! https://bit.ly/PEAPOD_Membership We designed this circuit board for beginners! Kit-On-A-Shield: https://amzn.to/3lfWClU PEA Customer Projects Page: https://www.programmingelectronics.com/customer-project-gallery/ FOLLOW US ELSEWHERE --------------------------------------------------- Facebook:https://www.facebook.com/ProgrammingElectronicsAcademy/ Twitter: https://twitter.com/ProgElecAcademy Website: https://www.programmingelectronics.com/
we're trying to revive the old EZ-Link Bluefruit design from many years ago - originally done with a CSR chipset that became very hard for us to get. ESP32 is a lot easier and the original chip has BT classic support - required for BT SPP which is what we're using. This test uses the Arduino IDE, we are uploading code from the IDE 'transparently' to the COM port which the operating system makes when you pair to a BT SPP profile device. Since we pass the baud rate and control lines, we're able to auto-reset and transmit data as if it were connected with a USB cable! here, we're uploading a NeoPixel test sketch and it seems to be working Visit the Adafruit shop online - http://www.adafruit.com ----------------------------------------- LIVE CHAT IS HERE! http://adafru.it/discord Adafruit on Instagram: https://www.instagram.com/adafruit Subscribe to Adafruit on YouTube: http://adafru.it/subscribe New tutorials on the Adafruit Learning System: http://learn.adafruit.com/ -----------------------------------------
Mental models are metaphors that help us understand complex problems we work on. They can be a simplified roadmap over an infinite area of complexity. How does one come up with mental models? How are they useful? Are they primarily a solo thing, or can they be used to communicate with the team? What happens when your model is inaccurate? Today, Joël is joined by Eebs Kobeissi, a Developer and Dev Manager at You Need a Budget, to discuss. This episode is brought to you by Airbrake (https://airbrake.io/?utm_campaign=Q3_2022%3A%20Bike%20Shed%20Podcast%20Ad&utm_source=Bike%20Shed&utm_medium=website). Visit Frictionless error monitoring and performance insight for your app stack. Eebs on Twitter (https://twitter.com/EebsKobeissi) You Need a Budget (https://www.youneedabudget.com/) Skill floors and skill ceilings (https://thoughtbot.com/blog/who-is-empowered-by-your-design) Transcript: JOËL: Hello and welcome to another episode of The Bike Shed, a weekly podcast from your friends at thoughtbot about developing great software. I'm Joël Quenneville. And today, I'm joined by Eebs Kobeissi, a Developer and Dev Manager at You Need a Budget. EEBS: Hi, Joël. It's really good to be here. JOËL: And together, we're here to share a little bit about what we've learned along the way. So, Eebs, what's new in your world? EEBS: Oh, a whole lot. I'm a new dad, so I'm getting to experience all those things. But in the developer world, I've recently picked up programming on an ESP32, which controls LED lights. And so I'm having fun lighting up my office. JOËL: Is that like one of those little microboards, kind of like a Raspberry Pi? EEBS: Yeah, exactly. It's a little board that's compatible with the Arduino IDE. And I literally only played with it last weekend, so it's still very new to me. JOËL: Nice. Have you done any Arduino development or Raspberry Pi or anything like that before? EEBS: No, I have a Raspberry Pi that I run like a DNS server on, but I haven't done any actual programming. I did make an LED blink, which is pretty cool. JOËL: What kind of programming is required for a board like that? EEBS: From my understanding, it's either in Python or C. Those are, I think, the two languages that you can program on it. I definitely do not know C. And so I'm just going through a bunch of tutorials and reading some sample code. But I think if I ever end up trying to implement something more complex, I'll probably switch over to Python because that's a little more familiar. JOËL: So the coding feels fairly high level even though you're writing controller code for LEDs. EEBS: I hope so. I'd love to be able to take advantage of whatever abstractions I can. JOËL: Do you have any fun goals you're trying to do with this? Or is this just for the fun of trying a completely different environment than web development? EEBS: No, it's actually rooted in something visual. So I have these shelves behind me that are in my webcam when I'm in meetings or whatever. And so I want to be able to put a light strip across these shelves and have some sort of visual thing in the background. JOËL: Like LED mood ring? EEBS: Yeah, kind of. My eventual goal would be that as I'm talking, a little equalizer display pops up behind me. I thought that would be pretty neat. JOËL: That is amazing. That will give you all of the cred in the meetings. EEBS: Right? I thought that'd be pretty cool. What have you been thinking about recently, Joël? JOËL: I've been submitting to the RubyConf call for proposals which, as of the recording of this episode, has just closed this week. And like many people, I submitted on the last day. EEBS: [laughs] JOËL: And it was really fun trying to take some ideas that I'm excited about and then turn them into a proposal that is accessible to other people. EEBS: Nice. Do you want to share a little bit about what the talk is, or is it under wraps for now? JOËL: I don't know if anyone on the committee will listen to this before the review goes out. This might break the anonymity of the proposal. EEBS: Oh, right, right. JOËL: One thing I will share that's interesting is that there are topics that I'm excited about. It's like, oh, here are a bunch of cool things about something, some technical topic. But talks that are just ten cool things about X are not that great. And so I needed to find some sort of unifying idea that I could use to share that. And that generally is in the form of trying to find a story that I can tell. What unifies all of these things together? What tells a compelling story? Is there some metaphor I can lean into? EEBS: Nice. I think that's a really powerful way of communicating something deeper is through telling something that people can relate to. JOËL: One way that thinking about metaphors has been really impactful for me recently is the idea of mental models and how those can help us in development. I'm curious; we've thrown around the phrase a little bit you and I in past conversations; what does a mental model mean to you? EEBS: I tend to be a visual thinker. And from talking to others, I've heard similar statements. So for me, a mental model is how I think about a particular domain or how I think about code flow or structure. And for me, it's usually either as two-dimensional objects or occasionally three-dimensional objects that I have floating in my visual space. So, for example, if we had two classes that are collaborators in some way, I often think of them maybe as two rectangles that are side by side. And when they interact, there's some little amorphous blob from one of those rectangles that reaches out into the other one or passes a message from one to the other. And I sort of have this idea of how many connections are there between these two physical things. Or, if I'm thinking about code flow and the path of execution that code might take, sometimes I visualize it as maybe a tree or potentially loops if there are such cases. JOËL: So when you think of these concepts, just in general, you're seeing in your mind's eye squares and rectangles floating in the air. EEBS: Yeah, pretty often. Sometimes it takes those shapes, and as I build up a mental model of some code, I'm usually adding new shapes into that picture I have in my mind. I tend to view things sort of top-down. So like, the start of code or the start of execution is usually at the top or maybe the far left or far right. And as execution happens, I usually view that as moving in towards the middle and potentially going back out when a response is returned. If it's a web request, something like that, I view it as this sort of outside in. And there's a bunch of pieces in there that are all talking to each other. JOËL: That's really cool. So not only is there a geometric aspect to it, but there's a spatial aspect to it as well. EEBS: Yeah. And it's interesting, like, I haven't actually thought about it [laughs] in this level of detail before. But yeah, there certainly is a spatial aspect to it. And I have this idea in my mind of like things and domain objects kind of belong at the bottom, and they should have well-defined boundaries. But the pieces that are a little bit towards the outer edges may be a little more fuzzy and may have less definition around them. JOËL: That's really interesting because I also have this sort of in my mind's eye see these things when I'm thinking about concepts like that. But I've talked to other people, and some people don't even have much of a mind's eye at all. They don't tend to visualize things in their mind in that way. EEBS: Yeah, it's really interesting how different people approach this thinking about code. A lot of people write things down. And I write things down, too, and draw little arrows that don't really make any sense. But it helps me do something physically sometimes as well as just thinking about it. JOËL: Have you ever tried to convert these pictures you see in your mind and actually draw them on paper? EEBS: Occasionally. And for the most part, that usually takes the form of some kind of domain modeling, whether it's based on database tables or just domain objects. And sometimes I will try and draw them out and then specify the relationships between them like, oh, you know, this one model talks to this other model in this particular way. And I'll define a relationship between them, which helps me think about them and how they interact. JOËL: I've found that even though for some things I can see it very vividly in my mind's eye, I struggle to then concretely translate that onto paper or digital paper if you will. It's almost like trying to, say, translate an emotion into words and that even though I feel like I see a visual picture, I can't reproduce it by drawing necessarily. EEBS: It's interesting you brought up feeling because a lot of the times, I have this gut feeling about a mental model, like whether I think it is correct or not. And sometimes I have this uneasy feeling of, like, that doesn't feel right to me, but it's hard to articulate why. And I think sometimes that's when I have to pull out something physical, start making those relations, start connecting things. And that's when I might uncover, like, oh, this feels odd because I have a circle here or a cycle or something. Or I've sort of represented the truth of something in two different places. Do you have any techniques for getting it out of your head and into something physical that you could share with someone else, maybe it's text or a picture? JOËL: I think I do struggle with that conversion sometimes. Practice definitely helps. I think maybe there is a metaphor here between converting these, let's call them, pictures that I see in my mind's eye and then drawing diagrams with trying to take feelings and expressing them in words. In the same way that, maybe I might have some feelings, and then I want to journal how I feel, and I struggle to express that. But finding a way to express that gives me a certain amount of precision and a more concrete thing. In the same way, these things that flash in front of my mind's eye, if I can take the time to put them on paper, they're now more real. They're more concrete. I think you can probe the edges, the ways that it kind of falls apart more easily. EEBS: Yeah, that makes a lot of sense. There's a lot of value in writing that down and going through those details in a methodical way because oftentimes, you'll catch inconsistencies, or you'll find better ways to describe it. And being able to share your mental model with someone else is often...well, it can be really tricky. And I think that's why it's important to go through and maybe find a common medium that you can share because I can't see into your brain. You can't see into mine. But if we can share our mental models, then hopefully, we have a better chance of agreeing on the solution or finding inconsistencies. JOËL: Exactly. I think, in many ways, there are almost multiple layers of mental models and that you might have an abstraction or a metaphor for a concept that you're working with separate from the diagram. And then the diagram is yet another metaphor, but now we're going geometric to represent a broader idea. EEBS: Yeah. Are there any other ways that you take that picture from your mind's eye besides written documents or conversations? Do you use any diagramming tools that specifically help with that? Or is it just kind of free-form? JOËL: I do a mix. I am a big fan of draw.io, which allows you to just free-hand or pull shapes together, things like that. There are some more structured tools that I will use. I'll use Mermaid.js. EEBS: Yeah, I've been using that a lot too. JOËL: Yeah, that's great. I've been digging into more structured diagrams recently, particularly the idea of graphs, directed graphs. And those have interesting properties. EEBS: Can you share a little more detail about what you mean? JOËL: So a graph in the computer science sense is a bunch of nodes. They are typically represented as circles and then edges which are the connections between them. A directed graph is now there's an arrow pointing in a particular direction. A really interesting property that you can have with directed graphs is whether or not they include cycles. So can you only by following the arrows effectively create a loop? Or will the arrows always lead you to some kind of terminal node? EEBS: Gotcha. Is that a directed acyclic graph? JOËL: If there are no cycles, yes, it is a directed acyclic graph or DAG, as you'll often see it abbreviated. EEBS: [laughs] How do you relate that graph to code? And what benefits do you get from expressing it that way? JOËL: So this shows up in a lot of places. And I'd even say that thinking of certain aspects of my code as a graph and a potentially directed acyclic graph is itself a mental model or a metaphor that helps bring clarity to the way I think about things. So, for example, code, you know, you invoke some main function at some point to call the code, and then that's going to call out some other functions, which call out some other functions, and so on. You may have heard that referred to as a call graph. But that is a graph of calls. There might be cycles in there for co-recursive functions and things like that. But that is one way you can then sift through and analyze how control flow or how logic flows through your application is through a function graph. You mentioned earlier the idea of objects and how they're connected to each other. That's an object graph. EEBS: Right. Recently, I had to work through a state transition problem where a customer has some billing, and they can go through many different states, whether it's active, or canceled, or past due, those sorts of things. And so actually, I reached for Mermaid.js and built a graph of, okay, they start here in this empty state. And then they subscribe, which then they become active. They might cancel their subscription, which moves them to a different state. And by listing out all the states and the transitions between them, it helped me to understand what methods I might need to define on which objects in order to allow those transitions to happen and what checks I might need to make before allowing those transitions depending on the state of the system. JOËL: I'm hearing the keywords states and transitions. And that's making me think of finite-state machines. Are you drawing a finite-state machine graph or something a bit more free-handed? EEBS: It's a bit more of free-handed. I don't think I've actually drawn out a state machine since college but just representing the different states as different boxes and the transitions that are possible from those states. I mean, I guess that kind of is a state machine in some way. So graphs are great visual approaches. Are there any non-visual approaches that you take? JOËL: That's a great question because not all mental models have to be visual. I think the power of a mental model exists in a metaphor. And one that's kind of broad but that I've applied to a lot of different areas is the general idea of something being parallel or in series. I think I first came across this concept talking about electric circuits. And are we talking about two little light bulbs that are in parallel, and if the electricity to one is cut, the other one still lights up? Or are they chained together in series? EEBS: Yeah, like my LEDs. JOËL: Exactly, going back to Arduino, but it can also be applied to a bunch of other things. We can talk about code being in parallel or in series. We can talk about work being in parallel or in series. Interestingly, I took that mental model as a sort of quick shortcut when I was digging into some functional programming ideas. Monads and applicatives are the fancy terms here. EEBS: Oh boy, I'm ready. JOËL: In general, and there's a hefty asterisk here, I think of monads as being serial, so you're chaining something; one thing happens, then another. So you can think of, for example, chaining promises in JavaScript, promise one, then promise two, as opposed to applicatives which are parallel. So you might think of maybe zipping two lists or two arrays in Ruby. The two arrays, there are no dependencies between the two of them. They get processed side by side as you're traversing both of them together. EEBS: Interesting. I've heard the term monad a lot, but I haven't heard the term applicative. Are there any other details you can share about them and what makes them different or how they might be seen in our code? JOËL: I think that the key difference is that distinction in how they're processed. Applicatives are a way of combining two independent, let's call them data sources, and then you find a way to combine them together. So it could be two independent arrays, and you're zipping through them. It might be two independent HTTP requests, and they can both fire in parallel. But then you want to combine their outputs. So you say wait until both are successful and then combine their output. EEBS: Oh, okay, gotcha. JOËL: It could even be nullable values. So you say do this thing if both values are present. But you're not...the value of one or the fact that one is null or not is not dependent on whether the other one is null or not. They're independently null or not as opposed to something...Monads are, again, a different way of combining. You might call them data sources or operations. But in this case, there is a clear dependency one, and then its output influences the next one. You might say check the value is null or present or not. And then, if it is present, take that value and then put it as the input of my next operation. And then, if it is null or not, do another thing. See, now you have a sort of chain. EEBS: Where do you see these chains happening in code? Or is it everywhere? JOËL: Once you know that pattern which, again, could be thought of as another mental model, you start seeing it everywhere. So promises in JavaScript chaining together that's effectively monads. Don't @ me, all the functional programming people. EEBS: [laughs] JOËL: I know that's not quite true. Anything dealing with multiple operations that could succeed or fail depending on, again, whether you're treating them as dependent or independent, that's probably going to look very similar to either monad or applicative. EEBS: So the first thing that actually comes to mind here is things like background jobs. Using Sidekiq or Resque or other job processors, you can have a queue of jobs that need to be executed, and they might need to run in serial, or potentially you have multiple workers pulling from a single queue, and thus the work is happening in parallel. Is that a reasonable analogy? JOËL: I think it's good for the serial versus parallel, but it's not necessarily a good analogy for understanding monads and applicatives. EEBS: Gotcha. JOËL: So with two workers, you can process a queue in parallel, and a bunch of things happen. EEBS: But there's not necessarily anything that is bringing those two workers together to produce a single output. JOËL: Yes. And there's no dependency between the tasks in the queue. EEBS: Right, right, gotcha. JOËL: So if you have a task that says execute this task and then only if this task succeeds, then do the second task, now you've created a dependency. And you couldn't process that in parallel because if task one, which has to be executed first, is executed by worker one, task two should not get processed unless task one is successful. You can't just say, oh, I've got another worker free. I haven't processed task two because it's waiting to know does task one succeed. EEBS: Right. So an example in code would be a user creates a new order. And when they create a new order, we send them a confirmation email. That would be an example of that happening in serial or a monad-like thing. [chuckle] JOËL: Yes, I found that thinking of things as serial or parallel is a good shortcut for thinking about monads and applicatives. I don't know that the reverse is necessarily true. They don't necessarily transfer one-to-one with each other. And maybe that's a danger of mental models, right? You find a mental model that describes a situation, and then you try to reverse it, and then you make false assumptions about the world. MID-ROLL AD: Debugging errors can be a developer's worst nightmare...but it doesn't have to be. Airbrake is an award-winning error monitoring, performance, and deployment tracking tool created by developers for developers that can actually help cut your debugging time in half. So why do developers love Airbrake? It has all of the information that web developers need to monitor their application - including error management, performance insights, and deploy tracking! Airbrake's debugging tool catches all of your project errors, intelligently groups them, and points you to the issue in the code so you can quickly fix the bug before customers are impacted. In addition to stellar error monitoring, Airbrake's lightweight APM helps developers to track the performance and availability of their application through metrics like HTTP requests, response times, error occurrences, and user satisfaction. Finally, Airbrake Deploy Tracking helps developers track trends, fix bad deploys, and improve code quality. Since 2008, Airbrake has been a staple in the Ruby community and has grown to cover all major programming languages. Airbrake seamlessly integrates with your favorite apps to include modern features like single sign-on and SDK-based installation. From testing to production, Airbrake notifiers have your back. Your time is valuable, so why waste it combing through logs, waiting for user reports, or retrofitting other tools to monitor your application? You literally have nothing to lose. Head on over to airbrake.io/try/bikeshed to create your FREE developer account today! JOËL: Another mental model that is not necessarily visual that I like actually comes from the video game community, and that's thinking of skill ceilings and skill floors. So in, I think, particularly the MOBA Community, that's a Multiplayer Online Battle Arena, they'll talk about characters as having a high skill floor or a low skill ceiling. And generally, what that means, and again, the meaning varies a little bit by community, is that a character with a low-skill floor is an easily accessible character. They might not have a lot of skill shots, like, you press a button, and things happen around your character. You don't need to aim, things like that. A high skill ceiling means that there's a lot of room for you to grow, and as you get more skilled, you can get significantly better with that character. EEBS: Gotcha. So the opportunity is greater with a higher skill ceiling. JOËL: Correct. And depending on how the character is set up, you might have a very narrow range that could be in the low range where it has a low skill floor and a low skill ceiling, which means that the character is easy to learn. But once you've learned it, there's not really a lot you can do with it. It's a fairly basic character. So getting better at the game is not necessarily going to make you that much more impactful. And then you could have one that's the opposite that is high both skill floor and skill ceiling where a character is very hard to learn. But once you learn it, that's kind of all there is to it. And then you might have one that has a large range somewhere; maybe it's easy to learn, but it's hard to master, or there's a lot of room for growth. And so, taking this framework for analyzing characters and video games, I think we can apply that to technology in general. This could be language design. This could be just API design. And you might say, well, I want this to be very accessible. People can jump in very easily. You might say I want this to be very powerful and have a lot of high-end features that make your power users very happy and very productive. EEBS: That's interesting. When you first were talking about it, I was actually less thinking about it from a user's perspective of what maybe they could do in the application but potentially from the standpoint of a developer writing the system itself. One of the pieces I always come back to in software development is that change is inevitable. And so, making something easy to change often pays great benefits down the road. And so I wonder how that fits into this idea of a low skill ceiling or a high skill ceiling in terms of perhaps flexibility or being decoupled such that you can take one idea and easily extend it or easily get more from it than you originally set out to build. JOËL: There's often a trade-off. So you make something easy to change. It's highly decoupled. But you maybe introduce more indirection to the system. So while it's easier to change one single piece, it's harder to understand the system as a whole. EEBS: Yeah, that's true. And sometimes, you bake in assumptions that you make about the future, which turn out not to be true. JOËL: [laughs] Yes, that is definitely something I'm guilty of. EEBS: I think we all are. JOËL: One thing that I find interesting is as you evolve the design of an architecture pattern, a system, a whole language, you might want to move one of those if I think of them like two independent sliders on a one-dimensional scale. So maybe you want to move the upper boundary a little bit and say I want a higher skill ceiling for this, but they don't actually move completely independently. So introducing some advanced features might inadvertently also raise the skill floor. And conversely, making the language super accessible so that it has a low-skill floor, you might have to decide I will not introduce certain features. EEBS: One thing I wanted to ask you about is, do you view different languages as having different skill floors and ceilings? And, you know, I love Ruby. I know you love Element. I've played with Element. It's been a great learning tool for me. How do you view those two languages in terms of skill ceilings and skill floors in terms of, I guess, what you can do with them? JOËL: That's a great question. And I think you can definitely apply that to languages. Admittedly, I think you could probably start a lot of flame wars with that. EEBS: [chuckles] Let's not do that. JOËL: I wrote an article a while back where I applied that mental model to look at the F# programming language. And there was a debate in that community about certain features to add and whether they would allow advanced programming but potentially at the cost of accessibility to newer members of the community and how to balance those. And so I thought, hey, let's throw this video game metaphor at the problem and talk about it through that lens. EEBS: That's really cool. Did you draw any conclusions, or was it as a way to start a conversation? JOËL: It is a way to start a conversation. I don't think there is a single correct or best distribution of your skill, ceiling, and floor. It has to match the goals you set out for your project. Just like in games, people love to rank which characters are best and not. And sometimes you can show that, in general, this character is better. But oftentimes, in a balanced game, you can talk about this character being easier to get started with or this character working very well if you're a pro. But the fact that you have a higher or lower skill ceiling or floor doesn't necessarily make the character better or worse. EEBS: So, this conversation about differing mental models, I think I hadn't realized that there can be so many different types of mental models. And some things that I do in my thinking I haven't classified as a mental model. But now that you bring it up, I think one that I think about fairly often is this idea of two objects that are collaborators and reaching into the internals of one of those objects from the other object. So A and B are two separate things. And if A reaches into B's bucket and messes with the state of B, I view that as sort of a bad practice. You're not really adhering to maybe the public API that that object is exposing. You're kind of reaching in and going around behind its back and changing some stuff that it may not expect. JOËL: Would you refer to that maybe as tight coupling? EEBS: Yeah, it's definitely tight coupling. It's not just tightly coupled; it's almost worse than that. It's almost like going behind somebody's back and making a change without them knowing. And so when I see that in code or when I write code that does that, I have this really intense desire to separate that and to say, no, no, you can't go in and update this record directly in the database. You have to send it a message and say, "Hey, I would like you to be aware of something," and then it goes and changes its own internal state as a response to that. And so I have this very vivid sort of mental feeling of it being wrong, of it being like, I'm being sneaky, or I'm not being gracious to the person I'm interacting with as though I were one of these objects. JOËL: That's fascinating. You've practically anthropomorphized these objects. EEBS: I do. I view them as little people. JOËL: You describe this interaction as going behind someone's back. That is the thing that I, a person, do to someone else. It's not a function making a direct call. And yet, it's such a strong...we use a social mental model to talk about objects and interactions. EEBS: Yeah, I almost want them to be friends. And I think that applies to real-life relationships, right? If you have a nice dialogue back and forth, there's an understanding. There's commonality that you can find. But if I were to go do something behind your back without chatting with you about it first, you might not be so happy with me. JOËL: I'd feel betrayed. EEBS: Right. JOËL: I feel like there's probably a really fun conference talk to be done about that. We often use that metaphor; I think when talking about objects sort of subconsciously but making it explicit and just being, hey, let's talk about these objects as if they were people. Why don't we want to do this? Because this one here is betraying the other object there. This one here is being impolite. EEBS: We could have two people get on stage and talk to each other. And I might then go and reach in your pocket and pull out some change without you knowing, and you might be upset with me. JOËL: That would be great. Get a little skit going up on stage. Or even if you're artistically inclined, you could probably draw some really fun little characters to illustrate this. EEBS: That would be really cool. I, unfortunately, don't have the artistic talent to do that. JOËL: Well, free conference talk idea to all listeners of the podcast. I expect to see this for RailsConf 2023, maybe. EEBS: I'll be looking for it. So I've shared a mental model that I didn't really know was a mental model. Are there other mental models that you want to share that I may not be thinking of? JOËL: Here's one that I've just come to realize recently that I'm actually quite excited about: when you think about the word refactoring, how would you describe that idea? EEBS: Well, refactoring to me is changing the implementation without changing the behavior. JOËL: Yes, I think that is the classical definition. You should be able to change the implementation of a method, and the tests without changing are still green after you've done that. EEBS: I guess, mentally, I think about that as perhaps drawing a box around some of the objects that are floating in my mind's eye, rearranging how they exist within that box, and then the box dissolves. And the tests still pass, but the structure of the objects or the code has changed in my mind. JOËL: I love that you immediately went to a visual approach there. And I think I have something similar, but I'm coming at it from a slightly more domain modeling perspective. So thinking maybe less from an individual method approach but looking at maybe a larger system, what you're trying to do is use code to describe some version of reality. So it might be a business process that you have. It might be trying to describe some aspect of your customer's life that you're trying to automate for them. Oftentimes, this thing you're trying to describe in code terms is going to be a simplification because life has a ton of edge cases, and many of them we don't care about. So if we go with a visual metaphor here, you're trying to draw some kind of shape using only straight lines to approximate some weird curve. And so, let's say you draw something with only four lines. It's really simple, how you have a diamond. That's the shape you're trying to create. And then you're going to fill it in with little other shapes that approximate a diamond. And those are your different models and functions and all the other components that we use to build software. At some point, your understanding of the underlying reality might change. Maybe you need more precision, or maybe the actual feature requirements have changed. The thing you're trying to approximate with your code is not a diamond. Maybe you've added a few more sides to it. It's a pentagon. So we've gone from four sides to five. And the little components, and modules, and things that you have there approximate that diamond work. They still mostly approximate your pentagon, but it's really clunky because the initial design was to approximate something else. They were really good for fitting in really tightly and being very loosely coupled to each other when we were trying to do a diamond, but then they don't work as well in the pentagon. EEBS: So maybe some of the internal shapes need to change or adjust to fill the space that the pentagon has now created. JOËL: To fill the space or maybe even just to fill it in a way that's less clunky. And so the idea here in this metaphor is that the reality we're targeting in software is always changing. And so the underlying reality changes, and so we're changing that shape that we're creating all the time. But also, we're getting more precision as we decide; oh, we care about this edge case now. We didn't in version one, and so as part of that, we're constantly having to take the modules that maybe were very well designed initially but then restructure them to fit the new requirements because now there's a fourth object coming in, and it's kind of clunky with our current configuration. EEBS: That's interesting. One of the first things that jumps to mind is that maybe there are better ways or worse ways to do that refactoring to fit that new shape. Do you think there's any truth to that in the sense that you might initially design a system that perfectly fits that diamond or very closely fits that diamond but then as it changes to a pentagon, do you need to simply add a new piece to fill in that empty space? Or do you need to restructure everything within the diamond now to fit the shape of the pentagon? JOËL: Oftentimes, you do need to restructure. And I think there's this wonderful little phrase from; I believe it's Kent Beck that says, "Make the change easy, and then make the easy change." EEBS: Yep. JOËL: And so, to me, that makes the change easy is that initial restructuring that you need to do of those first shapes so that you can finally bring in the new one. EEBS: Oh, that's a cool visual. I immediately can imagine the pieces in the pentagon moving around to make space for a new piece that you need to now bring in. And that movement of all those pieces can be really difficult. Have you ever played that game where it's a square, and you're trying to get a ship out of a port, but there's a whole bunch of other ships, and you can only move them left and right and up and down? And you can do that. And that's what I'm picturing right now is moving shapes within that pentagon to then make space for either a new shape or to allow a shape to escape that is no longer relevant. JOËL: I played a version of that that had cars, cars, and trucks. EEBS: Gotcha. Yeah, I think I played that too. JOËL: That would also be a fun conference talk, right? Like, start with that game as your initial metaphor. And then you use that as a way to talk about refactoring. EEBS: That would be really cool. JOËL: I would watch that talk. To anybody listening who wants to give that talk, I want to see you at RailsConf 2023. EEBS: [laughs] Are we just a talk factory now? [laughter] JOËL: I love talk ideas. Maybe this should become a segment. Just have Eebs come in for five minutes once a month and give us a talk idea. It could even be fun to see a talk idea that multiple people implemented differently. EEBS: That would be really cool, actually. I always get nervous about giving talks or being on podcasts like this one. I would love to be the person that gets to sit there and throw out random ideas and have other people fulfill my dreams. JOËL: Well, thank you so much, Eebs, for joining us to talk about mental models. And to all of our listeners, I'd love to hear about what mental models you find are helpful, and so please share them with us. On Twitter, you can reach us at @_bikeshed. EEBS: Thanks for having me, JOËL. This has been super fun. JOËL: And on that note, let's wrap up. The show notes for this episode can be found at bikeshed.fm. This show is produced and edited by Mandy Moore. If you enjoyed listening, one really easy way to support the show is to leave us a quick rating or even a review in iTunes. It really helps other folks find the show. If you have any feedback, you can reach us at @_bikeshed or reach me at @joelquen on Twitter or at hosts@bikeshed.fm via email. Thank you so much for listening to The Bike Shed, and we'll see you next week. Byeeeeeee!!!!!! ANNOUNCER: This podcast was brought to you by thoughtbot. thoughtbot is your expert design and development partner. Let's make your product and team a success.
This week's EYE ON NPI will pique your curiosity... it's Microchip's AVR-IoT Cellular Mini Development Board featuring the Sequans Monarch 2 GM02S cellular module (https://www.digikey.com/en/product-highlight/m/microchip-technology/avr-iot-cellular-mini-development-board) This dev board really knows how to get us interested with an AVR128DB48 128KB-flash AVR chip (https://www.digikey.com/short/4pq3d2q3), Sequans GM02S compact LTE cell module (https://www.digikey.com/short/4qbfcn17), Feather format (https://learn.adafruit.com/adafruit-feather), Stemma QT / Qwiic connector (https://learn.adafruit.com/introducing-adafruit-stemma-qt/what-is-stemma-qt) and Arduino library support (https://github.com/microchip-pic-avr-solutions/avr-iot-cellular-arduino-library) This is an excellent dev board to use if you want to take advantage of the huge ecosystem afforded by Arduino, Feather, Qwiic/QT - you should be able to use the many thousands of libraries and hardware accessories for quick prototyping. As mentioned, this dev board is Feather shaped, with a USB Type C connector, Li-poly battery charger, and built in programmer/debugger/serial interface for the AVR chip. The individual microcontroller is a AVR128DB48 AVR (https://www.digikey.com/short/4pq3d2q3) which comes with 128KB flash and 16KB RAM. Think of it as a super-beefy ATmega328P! A SAMD21E 'curiosity' chip is used as the programming interface and also serial interface. When plugged in, the board shows up as a disk drive, with a getting started guide bookmark and some other specification files. While following the getting started guide we found that you can also drag hex files over to program it, very handy for quick-start! To program it, MCP suggests using the DxCore from SpenceKonde (https://github.com/SpenceKonde/DxCore) in Arduino so you'll want to get that installed while you follow the rest of the guide. Next up, time to activate the included SIM card from Truphone (https://activate.truphone.com/) that comes with the dev kit. This SIM is free to activate and is good for up to 150 MB of data transfer and 90 days, which is plenty of time to explore the board before needing to renew. Activating the SIM only took us 5 minutes - don't forget to power cycle after activation to make sure the module and SIM re-authorize. One of the surprises we had while trying this eval board is the really good documentation and learning system that is over at https://iot.microchip.com/avr-iot-cellular-mini - we're kinda used to verbose text-based documentation or using specialized software that only runs on Windows. This is the first time we've seen a really nice documentation system with simple step-by-steps, lots of photos, links and a clear navigation system. There are also two interesting in-browser compilation and serial monitor widgets that we spotted, which is a good sign that folks are starting to move towards browser-and-filesystem replacements for tool-chains. The Arduino library code is available over at https://github.com/microchip-pic-avr-solutions/avr-iot-cellular-arduino-library which looks like it's got platform.io support and you can download a release for installation into the Arduino IDE. (We do recommend someone at MCP try to add a proper release to the Arduino library manager to save one extra step if possible!) Once installed, there are a few helpful examples to get you going. The first one is just connecting to an HTTP endpoint and parsing out the result and it worked...really well! We were able to connect to the AT&T cellular network and fetch the data within a minute. We'd request an HTTPS example since most folks will want a TLS method of connection! Since the board is Arduino and Stemma QT compatible, we were able to connect an OLED and extend the example to display the HTTP-gotten data to the OLED - it only took us 10 minutes to install everything for Arduino library support and extend the code which is amazingly fast! You know what else is really fast? Digi-Key shipping for the AVR-IoT Cellular Mini Development Board, cause it's in stock right now! (https://www.digikey.com/short/bn7mp80w) Order today and you'll be connecting to the LTE cellular network by tomorrow afternoon.
In this video we're taking a look at the new Adafruit Feather ESP32 V2. This is a big upgrade over the original. The V2 has 8MB of flash - that's twice as much storage! It also has additional 2MB of PSRAM, Mini NeoPixel, Stemma QT and a USB-C port. Get ESP32 V2 Feather Huzzah https://www.adafruit.com/product/5400 Learn Guide for ESP32 V2 Feather Huzzah https://learn.adafruit.com/adafruit-esp32-feather-v2 It's designed for Low power usage so you can use a lipoly battery in deep sleep. It features the ESP32 Pico module, so you get extra space for pin labels and mounting holes! With STEMMA QT, you can just plug in your favorite sensor breakouts and start plotting data. It's a great way to quickly get your IOT projects up and running. You can use it with Arduino IDE just like other ESP32 boards - with the extra flash and RAM, even big complex projects are a breeze. With WipperSnapper you can easily make IOT projects without having to write any code! Just install the firmware with a chrome based browser, now your Feather will appear in Adafruit.IO automatically. ESP32 V2 also has MicroPython support so you can write python code and libraries to create your IOT Projects. Follow along with the Adafruit Learn Guide to install and set up your Feather ESP32 V2. Visit the Adafruit shop online - http://www.adafruit.com ----------------------------------------- LIVE CHAT IS HERE! http://adafru.it/discord Adafruit on Instagram: https://www.instagram.com/adafruit Subscribe to Adafruit on YouTube: http://adafru.it/subscribe New tutorials on the Adafruit Learning System: http://learn.adafruit.com/ -----------------------------------------
Hackaday Editor-in-Chief Elliot Williams and Managing Editor Tom Nardi are back again to talk about all the weird and wonderful stores from our corner of the tech world. Canon having to temporarily give up on chipping their toner cartridges due to part shortages is just too perfect to ignore, and there's some good news for the International Space Station as the White House signals they're ready to support the orbiting outpost until 2030. We'll also look at an extremely promising project looking to deliver haptic feedback for VR, programming retrocomputers with the Arduino IDE, and the incredible reverse engineering involved in adding a DIY autonomous driving system to a 2010 Volkswagen Golf. Finally we'll find out why most of the human life on this planet depends on a process many people have never heard of, and learn about the long history of making cars heavier than they need to be. Check out all the links over on Hackaday!
Es gibt Software, die man nur deswegen nicht benutzt, weil einem noch niemand davon erzählt hat. Deswegen hat sich das Uplink-Team Tools aus den Kurztests in c't geschnappt und bespricht, warum die kreativen Helferlein Canva, ClipDrop und Procreate für MacOS schneller zur Einladungskarte verhelfen, das Freistellen von Screenshots beschleunigen und auf dem iPad das Zeichnen erleichtern. Ob das MacBook dabei noch Ressourcen frei hat, zeigt der Performance-Monitor Sensei mit hübschen Diagrammen. Wer lieber kreativ programmiert, sollte Microsofts kostenlose Entwicklungsumgebung Visual Studio Code kennen, einem gänzlich anderen Programm als „Visual Studio“ (ohne „Code“). Über den Plug-in-Manager der IDE lässt sich nämlich nicht nur Syntax-Highlighting und Refactoring-Unterstützung für jede erdenkliche Programmiersprache nachinstallieren, sondern auch PlatformIO. PlatformIO erlaubt Mikrocontroller wie den Arduino oder den ESP8266 zu programmieren. Dank Visual Studio Code als mächtigen Editor im Hintergrund macht die C-Programmierung mit PlatformIO viel mehr Spaß als mit der umständlichen Arduino IDE. Ebenfalls auf allen Desktop-Betriebssystemen läuft Discord, ein Tool, um Menschen virtuell zusammen zu bringen. Egal ob Text-Chat, Telefonat, Videokonferenz oder multiple Livestreams: Mit Discord können Menschen sich mitteilen, ohne vom Schreibtischstuhl aufstehen zu müssen. Es gibt sogar einen Heise-Kanal in Discord, wo Sie direkt mit uns diskutieren können. Discord ist feingliedrig konfigurierbar und trotzdem dank zentraler Server und einem einheitlichen Client relativ leicht bedienbar. Die zentrale Struktur nutzt Discord aber auch, um Werbetreibende mitlesen zu lassen. Ob erzwungene Offenheit gegenüber der Werbeindustrie eine gute Idee ist, wo die Tools glänzen und wo sie zu teuer sind, diskutieren Kim Sartorius, Pina Merkert und Michael Wieczorek. === Anzeige / Sponsorenhinweis === Diese Ausgabe des c't uplink ist gesponsert von Dell Technologies. Besuchen Sie uns online unter: Dell.de/KMU-Beratung === Anzeige / Sponsorenhinweis Ende ===
Es gibt Software, die man nur deswegen nicht benutzt, weil einem noch niemand davon erzählt hat. Deswegen hat sich das Uplink-Team Tools aus den Kurztests in c't geschnappt und bespricht, warum die kreativen Helferlein Canva, ClipDrop und Procreate für MacOS schneller zur Einladungskarte verhelfen, das Freistellen von Screenshots beschleunigen und auf dem iPad das Zeichnen erleichtern. Ob das MacBook dabei noch Ressourcen frei hat, zeigt der Performance-Monitor Sensei mit hübschen Diagrammen. Wer lieber kreativ programmiert, sollte Microsofts kostenlose Entwicklungsumgebung Visual Studio Code kennen, einem gänzlich anderen Programm als „Visual Studio“ (ohne „Code“). Über den Plug-in-Manager der IDE lässt sich nämlich nicht nur Syntax-Highlighting und Refactoring-Unterstützung für jede erdenkliche Programmiersprache nachinstallieren, sondern auch PlatformIO. PlatformIO erlaubt Mikrocontroller wie den Arduino oder den ESP8266 zu programmieren. Dank Visual Studio Code als mächtigen Editor im Hintergrund macht die C-Programmierung mit PlatformIO viel mehr Spaß als mit der umständlichen Arduino IDE. Ebenfalls auf allen Desktop-Betriebssystemen läuft Discord, ein Tool, um Menschen virtuell zusammen zu bringen. Egal ob Text-Chat, Telefonat, Videokonferenz oder multiple Livestreams: Mit Discord können Menschen sich mitteilen, ohne vom Schreibtischstuhl aufstehen zu müssen. Es gibt sogar einen Heise-Kanal in Discord, wo Sie direkt mit uns diskutieren können. Discord ist feingliedrig konfigurierbar und trotzdem dank zentraler Server und einem einheitlichen Client relativ leicht bedienbar. Die zentrale Struktur nutzt Discord aber auch, um Werbetreibende mitlesen zu lassen. Ob erzwungene Offenheit gegenüber der Werbeindustrie eine gute Idee ist, wo die Tools glänzen und wo sie zu teuer sind, diskutieren Kim Sartorius, Pina Merkert und Michael Wieczorek. === Anzeige / Sponsorenhinweis === Diese Ausgabe des c't uplink ist gesponsert von Dell Technologies. Besuchen Sie uns online unter: Dell.de/KMU-Beratung === Anzeige / Sponsorenhinweis Ende ===
Adafruit seesaw is a near-universal converter framework which allows you to add add and extend hardware support to any I2C-capable microcontroller or microcomputer. Instead of getting separate I2C GPIO expanders, ADCs, PWM drivers, etc, seesaw can be configured to give a wide range of capabilities. And now we've got our seesaw peripheral library ported to Arduino IDE & humming along nicely - here's a demo where we have an I2C controller read a trim potentiometer over I2C, then turn that into NeoPixel brightness settings and pipe out a rainbow demo to a NeoPixel strip over I2C. #adafruit #seesaw #arduino Visit the Adafruit shop online - http://www.adafruit.com ----------------------------------------- LIVE CHAT IS HERE! http://adafru.it/discord Adafruit on Instagram: https://www.instagram.com/adafruit Subscribe to Adafruit on YouTube: http://adafru.it/subscribe New tutorials on the Adafruit Learning System: http://learn.adafruit.com/ -----------------------------------------
En esta nueva entrega del podcast hablamos de:- Arduino IDE 2.0- Novedades TinyGS- Proyecto monitorización de vehículoMás información en https://programarfacil.com/podcast/arduino-ide-2-0/
Welcome to the Electromaker Show, episode 40! This week’s DIY tech news highlights include a Raspberry Pi smart chess board, Arduino-controlled Nintendo Switch, Raspberry Pi Zero RF video modulator HAT, RP2040 board Arduino IDE support, and more! Tune in for the latest maker, tech, DIY, IoT, embedded, and crowdfunding news stories from the week! We publish a new show every week. Subscribe here! Don't have time to watch the show? Listen to the Electromaker Show in podcast format! Big Clive reverse engineers a generic 433 MHz receiver How to drill a hole with Butluni Raspberry Pi Smart Chess Board Arduino helps control the world's largest Nintendo Switch Raspberry Pi Easter fun! Incredible Commodore 64 Organ Pi Zero RF Video Modulator HAT RP2040 boards get Unofficial Arduino IDE support CNX software roundup of the most powerful ARM SBCs and DevKits in 2021 Electromaker roundup of x86 boards
Welcome to the Electromaker Show, episode 36! This week saw the Arduino IDE 2.0 beta released, DietPi added Docker and Steam support, the ESP32-M1 seeks crowdfunding, and there’s an early hands-on look at the ESP32-S3! Check out these top maker, tech, DIY, IoT, embedded, and crowdfunding news stories from the week! We publish a new show every week. Subscribe here. Read the article! Don't have time to watch the show? Listen to the Electromaker Show in podcast format! Super Early hands-on look at ESP32-S3 with Unexpected Maker Using Raspberry Pi GPIO pins as radio transmitters "The Thresher" A personal grooming device from JoelCreates you'd never want to use Bitluni 3d Printed Holographic Displays Zack Freedman talks about "Disgusting Secrets of Real Hardware" ESP32-M1 Reach Out - long-range Wi-Fi board Binary Decoder SMD soldering kit Simple Calculator Through Hole Kit Arduino IDE 2.0 hits Beta Arduino Day 2021 Free RISC-V training classes from Linux Foundation and RISC-V International Embedded World Closing Report DietPi 7.0 now has Docker and Steam support
KidsLab - a podcast for parents and educators passionate about STEAM education
I am talking to Bridget Hegarty about the SpinWheel. The SpinWheel is a small, colorful, programmable, wearable kit to facilitate student exploration of physics, engineering, and computer science.Bridget is part of the SpinWheel Team, a group of volunteers with a passion for teaching science and building beautiful things. She is a postdoc researcher in Environmental Engineering at the University of Michigan. As a kid, Bridget was always asking “why?” Luckily, her parents put up with her incessant questioning and taught her to love the process of discovering new information. Bridget continues to pursue answers to her questions as a researcher, studying the microbes that survive in buildings. Outside of the lab, she shares her love of science and engineering by designing and leading activities that help participants, particularly girls, envision themselves as engineers. Through SpinWearables, she is excited to develop educational kits to inspire the next generation of engineers.The SpinWheel is a colorful wearable programming kit. It can be “just” a stylish, cool, accessoire, but can also be programmed to be way more via the popular Arduino IDE. For example you can turn it into a step counter, a compass or an exploration tool for color and vision. No prior knowledge is required to program the spinwheel and it also comes with an educational guide that introduces you to the basics.
Brittany KF8IJZ received an Arduino kit with many sensors and addons for Christmas and is starting to get familiar with the microcontroller and its capabilities. Mark KR6ZY joins us to answer the fundamental question of “What is Arduino?” We talk through some fundamentals and some practical examples of projects one can complete with an Arduino compatible microcontroller. PERMALINK - https://www.hamradioworkbench.com/podcast/what-is-arduino Our Website - http://www.hamradioworkbench.com/ Follow us on Twitter - https://twitter.com/hamworkbench Contact us for feedback and ideas - http://hamradioworkbench.com/contact Connect with us on Facebook - https://www.facebook.com/groups/hamradioworkbench/ BrandMeister Talkgroup 31075 - https://hose.brandmeister.network/group/31075/ Save $100 on the Digilent Analog Discovery 2 Package by using code “HamRadioWorkbench2019” in your cart prior to checkout - https://store.digilentinc.com/ham-radio-workbench-bundle/ Smitty’s Headphone Amp - http://diyaudioprojects.com/Solid/12AU7-IRF510-LM317-Headamp/ Active Antenna Loop Antenna - https://active-antenna.eu/ Using Filters to smooth Pulse Width Modulation Output - https://hackaday.com/2011/06/16/beginner-concepts-using-a-low-pass-filter-to-smooth-pwm-output/ Arduino analogWrite - https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/ Arduino Wire - https://www.arduino.cc/en/reference/wire What is Arduino - https://www.arduino.cc/en/guide/introduction Arduino IDE - https://www.arduino.cc/en/Main/Software Microsoft Visual Code Arduino - https://medium.com/home-wireless/use-visual-studio-code-for-arduino-2d0cf4c1760b Arduino Software Tools - https://playground.arduino.cc/Main/DevelopmentTools Arduino Official Language Reference - https://www.arduino.cc/reference/en/ Core Arduino Libraries - https://www.arduino.cc/en/Reference/Libraries Arduino Libraries - https://playground.arduino.cc/Main/LibraryList K3NG Arduino Based CW Keyer - https://blog.radioartisan.com/arduino-cw-keyer/ Debouncing a Button in Software - https://www.youtube.com/watch?v=jYOYgU2vlSE KR6ZY’s 4 part series on TWiT’s Coding 101 on building an Analog Panel Meter clock https://www.youtube.com/watch?v=ZwoGkRf5WnM https://www.youtube.com/watch?v=FSd-jip59PI https://www.youtube.com/watch?v=IWnmMRls1os https://www.youtube.com/watch?v=R-WKsIuVrIw Arduino Controlled Fox Hunt Transmitter - http://www.wt4y.com/arduino-fox-controller Arduino MIDI Controller Tutorial - https://www.arduino.cc/en/tutorial/midi
Have you ever wanted to change the font color in the Arduino IDE? Maybe it is hard for you to read the light grey comments in the Arduino IDE, or maybe you prefer something a little bolder. Whatever your reason, in this short video, I demonstrate a relatively easy way to change the font color of comments.
In many cases while using an Arduino, you will want to see the data being generated by the Arduino. One common method of doing this is using the Serial.print() function from the Serial library to display information to your computer’s monitor. In this week’s episode, we will talk about the intricacies of the Serial.print() function. This is the first part, of a two part series on the Serial.print() function. Here are the specific topics we will cover in this lesson: Why would you want to use the Serial.print() function? A brief overview of the Serial library The basic use of the Serial.print() function Like this video? Sign up for our FREE Arduino Crash Course to get more videos that don't assume you have a PhD. Why Would You Want to Use the Serial.print() Function? You may know that a function is a programming tool - it performs a specific task for you. The Serial.print() function’s task is to send information from your Arduino to your computer, so you can see the value displayed on your computer’s monitor. There are an endless number of reasons you may want to send information from the Arduino to a computer display, but two reasons really stand out to me: The first reason is being able to see information that you are generating with your Arduino. For example, if you have a temperature sensor hooked up to your Arduino and you want to see the value that the temperature sensor is recording, then you can use the Serial.print() function to send the data to a computer monitor via the USB cable. If you open up the serial monitor window (Tools > Serial Monitor), you will see the values streaming in from the Arduino. The other big reason to send information to a computer display using the Serial.print() function is for developing and debugging Arduino sketches. Very often, when you are developing an Arduino sketch, what you end up coding does something differently than what you expected it to do. Maybe you have a variable that gets incremented every so often and blinks an LED when it reaches a threshold. When you upload the code to the Arduino, you notice that the LED is blinking more often than it should. You can look at the code until your eyes bleed, but actually visualizing the variable being incremented [via the Serial.print() function], to see its values every time through the loop() can help explain what is happening very quickly. A Brief Overview of the Serial Library We can’t talk about the Serial.print() function, without briefly talking about the Serial library. Generally speaking, a library is simply a collection of functions that all have something in common. The print() function is part of a library called the Serial library. Now, it's not cereal like Cheerios or Captain Crunch we're talking about - it's serial as in “one after another”. The serial library allows us to interface the Arduino with other hardware, like a computer. In order for us to use the functions of the Serial library, we have to initiate serial communication - to do this we use the Serial.begin() function. Serial.begin() needs to go in the setup(). void setup() { //Initiate Serial communication. Serial.begin(9600); } Now for reasons beyond the scope of this discussion, it is convenient to use the number 9600 in the Serial.begin() function. The value 9600 specifies the baud rate. The baud rate is the rate at which information will pass from the Arduino to the computer, or in the other direction. The Basic Use of the Serial.print() Function Let's talk about how to use the Serial.print() function. Say we have a sketch. This sketch has a variable called coolFactor. I want to be able to monitor the value of the coolFactor variable – that is, I want it displayed on my computer screen. A perfect use for the Serial.print() function! The first thing we must do in the Arduino sketch is begin serial communications. Like we just said, we use the Serial.begin() function and place it within the setup() of the sketch. //A variable to hold the level of coolness int coolFactor = 3; void setup() { Serial.begin(9600); } void loop() { //Send the value of coolFactor to the the Serial port. //So we can see it in the serial monitor window Serial.print(coolFactor); } Now in the loop(), if I want to display coolFactor’s value with print(), I simply type Serial.print() and in the parenthesis I type the variable name. If we upload this sketch to the Arduino, the value of coolFactor will be sent to the serial port every time through the loop(). In the Arduino IDE, if you open up the serial monitor window [Tools > Serial Monitor], you will see the values streaming down. In next week’s episode, we’ll talk about some more intricacies of the Serial.print() function. If you enjoyed this lesson, I welcome you to join 1000's of students who have enjoyed our free Arduino Crash Course - it's a 19 part video training series on using Arduino (You can sign up below).
In this video we demonstrate how to create pseudo random numbers with Arduino - with a useful twist. This lesson was inspired by the following viewer question: How do I create Random Non-Consecutive numbers with Arduino? P.S. These are the best tutorials that a complete idiot like you could ever make, thanks. -Chris Let's overview exactly what we will talk about in today's episode: Talk about pseudo random numbers. Identify the problem - using an Arduino sketch to demonstrate. Discuss how we might solve the problem. Write an Arduino sketch that solves the problem. Review what we talked about. Before we answer the viewer’s question it is important to talk about what a pseudo random number is. A purely random number in the mathematical sense can't be predicted. The microcontroller that the Arduino uses (and for that case, most computers in general) can't really create pure random numbers. What they create instead are called pseudo random numbers. These are numbers that appear to be randomly generated, but if studied over time a predictable pattern emerges. The bottom line is that the random numbers we create with Arduino can be predicted. Now there are clever ways to create pseudo random numbers that act like the real deal – you can learn about one method in our video tutorial talking all about random numbers – but for this discussion, let’s return to our viewers inquiry. Identify the Viewer’s Problem - use an Arduino sketch to demonstrate. Ok, so let's go back to the viewers question, he wants to generate random numbers, but he never wants the same number generated two times in a row. Let's write an Arduino Sketch to make this clear. //This sketch outputs pseudo random integers. //A variable to hold pseudo random integers. int randomInt = 0; void setup() { //Initiate serial communication. Serial.begin(9600); }//Close setup function void loop() { //Create a random number and assign it to the randomInt variable. randomInt = random(0, 10); //Send randomInt to the serial port for displaying on the serial monitor window. Serial.print(randomInt); }//Close loop function. In the first block of code a variable that will hold the pseudo random integers is declared and initialized. //A variable to hold pseudo random integers. int randomInt = 0; In the setup() function we begin serial communication in order to display the numbers we generate on a computer display. void setup() { //Initiate serial communication. Serial.begin(9600); }//Close setup function In the loop() we create the random number with the Arduino random() function and assign the output to the variable we had just created. The random() function can take two arguments 1) the minimum value of the number we want generated 2) the maximum value we want generated. //Create a random number and assign it to the randomInt variable. randomInt = random(0, 10); I will use 0 for the minimum, and 10 for the maximum. Every time through the loop, a new random number will be assigned the randomInt variable. Finally, the value of randomInt is sent over the serial port to be displayed in the serial monitor window. //Send randomInt to the serial port for displaying on the serial monitor window. Serial.print(randomInt); If you upload this code and open the serial monitor you will see in some cases where the same number shows up two times in a row. This is the problem. The viewer doesn't ever want the same number two times in a row. Discuss how we might solve the problem. So let's talk about how we might solve this problem. We know we need to generate a random number. What if we create a variable to track the previous random number? Then we could use a condition that says something like "If the previous random number is equal to the random number that was just generated, toss that number out the window, and create a different one.” The final thing we would need to do is set the previous random number equal to the new random number, that way we keep updating our previous random number every time through the loop(). Let’s Implement our solution in an Arduino Sketch. Copy and paste this code into your Arduino IDE. All you need is an Arduino board attached to your computer to make it work. //This sketch outputs pseudo random non-consecutive integers. //A variable to hold pseudo random non-consecutive integers. int randomInt = 0; //A variable to hold the previously assigned pseudo random non-consecutive integers. int previousRandomInt = 0; void setup() { //Initiate serial communication. Serial.begin(9600); }//Close setup function void loop() { //Create a random number and assign it to the randomInt variable. randomInt = random(0, 10); /*Check if the random number is the same as the previous random number. If it is, then reassign a new random number until it is different from the previously set one.*/ while (randomInt == previousRandomInt) { //Create a random number and assign it to the randomInt variable. randomInt = random(0, 10); //When a consecutive random number has been identified, indicate it. Serial.println(); }//close while statement //Set previousRandomInt equal to the current randomInt. previousRandomInt = randomInt; //Send randomInt to the serial port for displaying on the serial monitor window. Serial.print(randomInt); }//Close loop function. If you upload this code to your Arduino and open the serial monitor window you will see the numbers scrolling across the serial monitor window, but now you will not witness any duplicates side-by-side. You may notice some X’s intermittently between the numbers, this is where the Arduino sketch identified a duplicate random number and generated a replacement. If you look through the code, you will see this is accomplished with a While Statement. I hope you can find some application for this simple process of creating a pseudo random non-consecutive number with Arduino. Let me know what you think the comments!
Understanding how the Arduino IDE sets up its file directory system can spare you some confusion when it comes to saving, organizing and opening your Arduino sketches (or sketches you have downloaded from the internet). This week’s episode covers the following: The Arduino Sketchbook folder How to change the default location where your Arduino sketches get saved What happens when an Arduino file does not have an enclosing sketch folder of the same name Where and how multiple tabs get saved in an Arduino sketch Why the pancreas of a woodchuck is better suited than our own Want to fast-track your Arduino skills? Click here to join our 12-part HD Video Course. You are probably familiar with a file directory system on a computer. It's usually represented as a hierarchy of folders and files. An example would be your C Drive - inside the C drive, you may have a folder for Applications, Users, and Systems files. Inside the Users folder, you might have subfolders for Documents, Downloads, Music, etc. All the files on the computer get organized in this fashion, and Arduino sketches are no exception. The Arduino Sketchbook Folder and Changing the Default Save Location The default location where Arduino sketches you write will be saved is called the Sketchbook. The Sketchbook is simply a folder on your computer like any other. It acts as a handy repository for sketches and is also where add-on code libraries get saved. You can see the sketches in the Sketchbook folder by going to File > Sketchbook. The default name of the Sketchbook folder is “Arduino” and the default location of the Sketchbook folder is in the “My Documents” folder (or just “Documents” for Mac users). If your Sketchbook does not appear to be in this default location, you can see exactly where it is by opening the Arduino IDE and going to Arduino > Preferences. The default file path for your sketches is listed at the top of Arduino Preferences window. Mine is: /Users/michaelJames/Documents/Arduino When I save a file in the Arduino IDE, this “Arduino” folder is the default location where the sketch will be saved, unless I choose to change that location by selecting a different folder on my computer's directory. If you want to change this default location, you click the Browse button next to the file directory path and choose a different place. Pretty simple. Sketch Folders If you go into your file directory system and open up the Sketchbook folder (again, named “Arduino” by default), you may see a bunch of folders that you didn’t make. This is because every Arduino file must be inside a folder that has the same name as the file (there are some exceptions to this that we'll talk about in a moment). Let me say that one more time because it is really important to understand. Every Arduino file must be inside a folder that has the same name as the file When I write a new sketch and save it, the Arduino IDE automatically creates a new folder that has the exact same name as the sketch itself. The Arduino file (which has the extension .ino) is placed inside this enclosing folder, which is called a sketch folder. If you go into the Sketchbook folder and change the name of the enclosing folder, it will create some issues. The first issue is that when you go to File > Sketchbook, the sketch will no longer show up! If you want to open this sketch you need to go to the .ino file in your directory and open it from there. If you open a .ino file that is not inside an enclosing sketch folder of the exact same name, then you will get a pop-up from the Arduino IDE that says: “The file “sketch_name.ino” needs to be inside a sketch folder named “sketch_name”. Create this folder, move the file, and continue?” If you choose Cancel, the sketch will not open. If you choose OK, then a folder gets created (it will have the same name as the sketch) and the .ino file is placed inside it. This sketch folder will be created in whatever directory the .ino file was that you tried to open. For example, if you tried to open a .ino file that was in your My Downloads folder, then the enclosing sketch folder also will be created inside the My Downloads folder. Saving Tabs in Arduino The exception to the rule about the sketch folder having the same name as the .ino file is when you create multiple tabs in an Arduino sketch. The additional tabs do NOT need to bear the same name as the enclosing sketch folder. Once you get a handle on some of these intricacies of the Arduino IDE file system, it can really help to clear things up. Please take a moment to leave a comment if you have any insights or thoughts about this tutorial. I would love to hear them!
If you have been learning about Arduino for any amount of time, than you have probably come across the term Breakout Board. Now, you might think, as I did when I first heard about breakout boards, that they were some fixture for practicing your Kung Fu fighting. In this lesson, we will discuss what breakout boards are, how they can accelerate your Arduino prototyping and some things to look out for when you buy them. Want to step-up your Arduino skills? Click here to join our 12-part HD Video Course. Basic Concept of a Breakout Board The basic concept of a breakout board is that is takes a single electrical component and makes it easy to use. Usually the electrical component is an integrated circuit (IC). Integrated circuits, as you may know, have pins on them. The pins on an IC can do a multitude of things, but you usually have pins for supply power, pins for providing a ground, pins for receiving an input and pins for sending an output. A breakout board "breaks out" these pins onto a printed circuit board that has its own pins that are spaced perfectly for a solderless breadboard, giving you easy access to use the integrated circuit. There are all type of breakout boards - but most of them are for different types of sensors, for example: accelerometers, ultrasonic distance sensors, RFID tag sensors, temperature sensors, pressure sensors, and they even have seismic breakout boards for sensing dinosaurs' footsteps! Breakout Board vs Arduino Shield: What's the difference? You might be wondering what the difference is between a breakout board and an Arduino shield, and that is a good question. Breakout boards usually have a smaller form factor - they don't need the entire space of an Arduino shield to accomplish their mission. And while the market for most breakout boards is being driven because of their use with Arduino, since the pin-out of a breakout board is not designed specific to the Arduino headers, it means you could use a breakout board with any other microcontroller development board you want - which gives them a bit more scope than Arduino shields. Also, since breakout boards generally have fewer components than a shield does, you may find the cost is lower than a comparable Arduino shield. As you may have guessed by now, you can find a breakout board that does essentially the same thing as a shield. You might be wondering, if breakout boards are only a few components, why not just buy the integrated circuit the breakout board uses, put it on a solderless breadboard yourself, and then hook them up to your Arduino? That is great question, and there is nothing saying you can't – plenty of people do - especially since the components by themselves are often far cheaper to buy alone from an electronics distributor, like digikey or mouser. So, why the heck are people buying all these breakout boards? It essentially comes down to convenience. Let me list the ways a breakout board can help you out, and then you make the call: Breakout boards can save you space We have already said that breakout boards use integrated circuits. Integrated circuits are kind of like t-shirts - you can get them in all different sizes. Usually breakout boards utilize a tiny version of an integrated circuit called an SMD (surface mounted device). The pins on SMD parts are really small - not something you can easily pop into a breadboard. The larger form factor of an integrated circuit, called a DIP (dual inline package) has bigger pins, which fit easily into a breadboard. The DIP package of an IC will be bigger than the SMD form factor. The point, I am getting to here, is that Breakout boards can sometimes save you space which may or may not be important for your project. Breakout Boards are designed for reuse Another thing about using DIP packages is that while the pins are bigger, they are not necessarily sturdy. If you plan to use a DIP component over and over, the usable life of the pins is only so long - the pins on a breakout board however, are heavy duty and designed for reuse. The DIP version on a component may not be available One other issue you may find is that the DIP version of an integrated circuit is not available - as electronics get smaller over time, the demand for larger components is drying up and manufacturers are moving away from even bothering with the DIP package, which ultimately brings you back to a breakout board. Pin labeling on a Breakout board One great feature of breakout boards is that they usually have the pin names of the integrated circuit labeled on the PCB. This makes hooking up the breakout board to your Arduino a cinch, especially when there are a ton of pins. Otherwise, you are looking at the black box of an IC and referencing the datasheet of the integrated circuit to try to figure out which pin is for what. So now that you know some of the benefits of a breakout board, let's talk about a couple things you might want to consider when you are buying them. Good documentation I said this about Arduino Shields in the last lesson, but I will say it again - good documentation is like water in the desert. The more you can get your hands on, the better. Let's face it - a lot of this electronics and programming stuff is not self evident - you need good instructions and reference material to make it work right. The test I usually use before buying a breakout board is to see what reference material I can find online for it. If nothing tangible exists, you might be spending way more time trying to get it up and running than you would prefer. Breakout boards are not necessarily interchangeable As you search for particular breakout boards, you may find that there is a super cheap version available. If you plan on using pre-existing code for a breakout board that references the more expensive version of the breakout board – i.e. maybe in the sketch comments it says, "use XYZ breakout board", one thing you will want to check is that the breakout boards use the same integrated circuit. If they don't use the same integrated circuit, and you don't know how to adjust the code for these differences, then you may find that the cheap version will cost you more time in trying to figure out how to use it. Soldering and header pins may be required Many breakout boards are sold as kits. Usually, the only things you have to solder are the header pins that allow the breakout board PCB to plug into a breadboard - this is really easy to do. It may also be the case that a kit maker just sells the breakout board with the SMD components, and you have to buy the pin headers separately. So those are a few things to keep in mind when buying a breakout boards. Using the correct supply voltage Finally, once you actually have your breakout board, make sure that you know what voltage supply pin it needs hooked up to. The Arduino has two voltage out pins, one at 3.3 volts and one at 5 volts. Many breakout boards use a supply voltage around 3.3 volts. Sometimes the supply voltage will be printed right on the PCB by the associated pin, but other times it will just say Vcc, so you will want to check the specs on the breakout board. If you are just getting started with breakout boards, a great place to look is in the Arduino IDE examples. Some pre-written sketches get you up and running quick with some common breakout boards. If you like the style of this lesson, I welcome you to join the free Arduino Crash Course - you can sign up below.
So you just opened up your fancy new gadget - maybe an awesome DSLR camera, or the newest gaming system, or maybe a new Blu-ray player. As you gladly tear away the packaging - you notice a small book that feels like it was printed on 4th generation recycled newspaper - it’s the instruction manual. As you skim the pages you realize it was first written in Japanese, translated to Chinese by an Australian ventriloquist and then an intern in California used Google Translate to finish the job for your native tongue. So you toss the instruction manual and just plug the gadget in. Good for you - especially since it appears as everything is working just fine. Until.. ...something isn’t working just fine. Maybe you can’t navigate the menu options to find a setting that was advertised on the box, or maybe the functionality you thought your gadget has does not appear to be working no matter how correctly it seems you are pressing the buttons. This tutorial is going to focus on the Arduino instruction manual, known more commonly as the “Arduino Reference” or the “Arduino Documentation”. It is an important and useful aspect of learning to use Arduino - it will be your best friend in times of bewilderment, brain lapses and fits of rage. I know that instruction manuals get a bad wrap - but don't fret - the Arduino Reference is awesome! To be honest what really keeps us away from the documentation is our fears. That’s right - the reference pages can be a bit intimidating when you are just starting out. They use a lot of technical jargon, are loaded with funky acronyms and filled with rabbit holes. Nobody uses the stuff anyway...right? ( Not right - that was a joke! ) This Tutorial Will Cover: What is the Arduino Reference? The Anatomy of an Arduino Reference Page. Why You Should Be Using the Arduino Reference More. How to use brain waves to trick your cat into eating less. Have you ever read a book and come upon a word you didn’t understand? Sometimes you can infer the meaning from it’s context, but what about when no such context exists? Likely, you used a search engine to find the definition. The definition told you what the word meant, whether is was a verb or adjective (or both), it gave some examples of how to use the word, and maybe even the etymology. The Arduino Reference is the same thing. It is the “dictionary” for all the structures, variables and functions that you can use when programming a sketch. It tells you the description, the parameters it uses, the syntax (how it is written), and even gives a bunch of examples on how to use it. So let’s jump into an Arduino Reference page and dig into what we can learn. The Anatomy of an Arduino Reference Page So let’s navigate to a reference page to start our journey. You can find the index of all the Arduino Reference pages on the Arduino Website: http://arduino.cc/en/Reference/HomePage Or - if you are offline - don’t worry, your Arduino IDE comes with an html copy of all the pages. You can get to it through the Arduino IDE: Help > Reference You will note at the top of the Reference Index page, there are three columns; Structure, Variables, Functions. This is the first level of organization in the reference. So if you are looking for a variable, you know which column to start looking in. Each of the hyperlinked items on this index page will take you to the individual entries reference page. What’s great about the individual reference pages is that they are organized in a similiar manner from one to the next, so you should know what to expect. They are also terse, so don’t think you are going to have to scour through someones dissertation. Each page has some major headings. We will walk through each of the main ones, and then talk about some less common ones. Description: All entries will have a description. Pretty straightforward - this is going to be a simple explanation of what the item does. It usually uses language that is basic. Syntax: Most all entries have a “syntax” heading, but they are more prevalent for functions. The syntax shows how the function (or other code) should be written when you use it in your sketch. Basically - it is what the function needs to know to do it’s job. Let's take an example from the digitalWrite() reference page. The words in the parentheses are telling you what type of value should be passed to the function. If we want to use this function than it will need to know 2 things - the pin number and the value to write to the pin. You don’t type in the word “pin” when you use the function, you would replace that with the actual pin number, or a variable that represents that pin number. Same is true for the word “value”, you would replace this with one of the acceptable parameters (see below). So when you actually wrote the function, it might look like this: digitalWrite( 13 , HIGH ) Where 13 is the “pin” and HIGH is the “value”. Parameters: Only structures and functions will have the “Parameters” heading. These describe exactly what can go in the parentheses in the syntax above. This is good to know, because you might be trying to pass a floating point number when the function calls for an integer. Returns: This tells you what value to expect a function to give you back. For example, when you use the square root function, you expect to get back the square root. But what data type will the square root be - an integer, a float or a double? The “Return” heading will tell you. Sometimes, a function will return nothing. Take the pinMode() function for example, you give it the pin number and the mode that you want the pin to be and it simply sets the mode - there is no data it needs to give you back. Example: This is your best bet at understanding how the structure, function or variable is intended to be implemented in code. It is usually a very short code snippet, though sometimes they can be lengthy. The example below is taken from the map() reference page. A nice feature of the example description is the “get code” option on the right of the reference page next to the example code. When you click this, it will take your browser to a plain text web page where you can copy and then paste the code into your Arduino IDE. See Also: This is a bulleted list of similar or related entries to the reference page you are looking at. They will link to other reference pages inside the reference directory. If I end on a reference page that isn’t quite what I was looking for, I will usually check out the options they provide here. Sometimes, they will also link to tutorials on the Arduino website (and who doesn’t like tutorials?) Keep in mind if you are using the reference in the offline mode through the Arduino IDE and you do not have an internet connection that any links outside the reference directory will not work. That includes the most common headings, what follow are some less common, but none-the-less useful headings you will run into. Programming Tips / Coding Tip / Tip: These are going to little bits of knowledge provided by people who know their stuff. I always like to read these, because they add to the depth of my understanding. Warning: These point out common errors that occur when people like me and you try to use the code. Caveat: If there is an exception to the rule, they will be described here. Note: In many cases, the notes are the “miscellaneous” heading, capturing information that doesn’t particularly fall under other headings. Why You Should Be Using the Arduino Reference More Here is a scenario I have played out myself about 7,000 times. I am writing a program and some function does not seem to be working right. I spend 30 minutes making changes to the program, but keep getting errors. Every time I think I have it fixed, I find I am wrong. Then I decide to check out the reference at which point I quickly realize I simply didn’t understand how a function was supposed to work. So the habit I have developed when I don’t completely understand a function it to check out the associated Arduino Reference page. It saves me times, teaches me something I didn’t know or re-teaches me something I forgot - and it will do the same for you. Let’s sum all this up. The Arduino Reference page is: The Bee’s Knee’s. The Lions Mouth. My favorite page on the Arduino website. Your favorite page on the Arduino website? Challenge(s): Go the Arduino Reference Index Page and start perusing some functions. See if you can find entries with the following headings: Caveat / Warning / Tip Further Reading: Warning - this gets deep! - AVR Libc (This is the reference for what the Arduino language is based on) - User Manual for the AVR Libc P.S. Ok - as much as I love the Arduino Reference page, sometimes it has errors. So if you find any, mention it on the Arduino Forum.
In the last couple of episodes we have talked about Arduino shields and breakout boards. In this video, we will review a specific Arduino shield that makes developing projects and debugging sketches on the Arduino extremely easy - it's called Dr. Duino.Arduino Shield for Arduino Shields The Dr. Duino is an Arduino Shield. As would expect, it fits snuggly on top of the Arduino headers and has pin headers of it's own, which can easily accept a shield on top. The first thing you notice about Dr. Duino is that it's built like a doughnut - it's got a giant hole in the middle! (FYI - It does not taste like said pastry…) There are a couple reasons for this form factor, but foremost is that even after you stack another shield on top of Dr. Duino, you still have easy physical access to all its resources. Dr. Duino Hardware Resources What resources are we talking about? Dr. Duino has 4 momentary pushbuttons, 5 LEDs, 6 potentiometers, an RS232 connector, and a bunch of access points for 5 volts, 3.3 volts and ground, oh yeah, and a siren (piezo buzzer). So how do you access these resources and why would you even care to? Both great questions! The core feature that allows us to use all the hardware I just talked about are groups of three “jumper” pins that surround the board. Almost every pin on the Arduino is associated with a set of these jumper pins. The middle pin is connected directly to the Arduino pin. The pin on the left is connected to the pin header on top of the Dr. Duino. The pin on the right is connected to the one of the hardware resources on the Dr. Duino board. With each set of these three jumper pins we get a plastic encased "jumper" - it fits snug on top 2 pins, and electrically connects them together. For every Arduino pin that has associated Dr. Duino jumper pins we have 2 decisions: 1) We can route the Arduino pin to the shield above by connecting the center pin to the jumper pin on the left. This passes the Arduino pin directly up to the shield if you have one attached, bypassing the Dr. Duino. 2) Or, we can route the Arduino pin to the resource on the Dr. Duino shield, bypassing the shield above. Each pin has a different "resource" or piece of hardware that you can use. Here is a quick mnemonic for remembering how to place the “jumper” on the “jumper pins” – Left goes Up (to the shield above), Right goes to Down (to the Dr. Duino). Digital pins 5, 6, 10, 11, and 13 have LEDs attached. Digital Pins 7, 8, 9 and 12 have momentary pushbuttons attached. Analog pins A0 - A5 have potentiometers attached and digital pin 3 is attached to the piezo buzzer. All these asset are extremely helpful. For example, let's say I am prototyping with a motor shield. What I want is for every time I press a button, then a servo moves 180 degrees. Instead of having to bust out a breadboard and jumper wires, I simply move a jumper on the Dr. Duino and I now have a preinstalled button. As long as the shield is not using that pin for anything, it's fair game to route that pin to the Dr. Duino. Or, maybe I want to turn a potentiometer to get the servo to move. Once again - scrap the breadboard - just move a jumper on one of the analog pins and you have a built in potentiometer - in fact, every analog pin has its own dedicated potentiometer! Trying to put 6 potentiometers on a breadboard and run jumpers is a major pain - having these built right in and so compact is great. Potentiometers are great for simulating sensor inputs too. Say you are developing a project that lights up LEDs based on inputs from a pressure sensor - but you don't have the sensor yet. No worries - just use the potentiometer built in to the Dr. Duino to simulate the input from the pressure sensor. Another great resource is the piezo buzzer. Most of us get used to using the serial window to debug our sketches. For example - we use the Serial .print() function to send a value to the serial monitor window when some threshold is met. What this ends up doing is dividing our visual attention from the Arduino to the computer monitor. With the piezo buzzer, you can get the same information, but be able to look at your Arduino - it allows you to incorporate more of your senses into the debugging process. All of these features add up to a great little development package - it's like a breadboard full of components all connected on a handy shield. So if I am traveling I don’t have to pack away a bunch of pieces-parts, I can just throw the Dr. Duino in with my Arduino and go for it. A Tool for Learning Arduino Code Another great use of these resources is when you are learning to use Arduino. If you are really trying to jump right into the code, then setting up the circuit can sometimes be a hassle, even if its just a button and an LED. (Yes - I am that lazy!) With Dr. Duino you can work through practically every sketch in the examples section of the Arduino IDE with only some minor code changes (mostly pin designations changes), without having to add a single piece of hardware. That’s a time saver (especially when it’s hard enough to carve out time to learn). Especially if having to place the components just feels like another barrier to practicing your Arduino coding. A Debugging Tool So far, most of my love for the Dr. Duino has come from this development aspect, but the Dr. Duino has actually been designed to help you debug your sketches when using shields. Microcontrollers (like the Arduino uses) are truly at the threshold of hardware and software. The more you know about both the physical and virtual, the better off you will be. Here in also lies a challenge – you can screw up both the hardware and the software. A big part of debugging your work is tracking down where the issue exists – is it the copper or code? (Or both !@#$) The Dr. Duino’s key feature of being able to direct an Arduino pin to or away from a shield you are using enables you to more quickly establish the starting point of debugging. Once you master how the rerouting works, the Dr. Duino will be a go-to shield for developing and debugging. With such a diverse set of applications it’s no wonder Arduino continues to grow wildly popular. Shields like the Dr. Duino make it that much more fun to use Arduino as a rapid prototyping tool. Special Bonus If you are interested in getting your hands on a Dr Duino, you can buy them directly from the Dr. Duino website. The creator of Dr. Duino (Guido Bonelli) has been kind enough to offer Open Source Hardware Group readers a free shipping code. Free Shipping Code: OSHWG_RULES (So true…)
This lesson covers three easy ways to implement some form of acceleration in your Arduino sketches. It will cover the following: Linear Acceleration Exponential Acceleration Messing Around with the Square Root function What is Acceleration? Acceleration is the rate of change of something over time. Acceleration would help describe things like: Have fast can a stopped car get to 88mph? If I do a wing-suit jump from the top of Mount Everest, how fast will I be when I am gliding over base camp? How can I gently slow down the movement of a mechanical servo before it comes to rest? We can implement acceleration when programming Arduino quite easily with just a couple lines of code. The basic concept is that a variable will need to change - how it changes over the course of the sketch is what we are interested in. Below are three examples of how we can code change in variables so they display acceleration. Linear acceleration Linear acceleration is a constant rate of change. It can be represented by a sloped line on an x-y axis. A simple way to use it is to increment or decrement a variable every time through a loop like below... for (int i = 0; i < 10; i++) { //accel gets increasingly smaller as for loop continues accel = accel - 100; }//close for You can see in the code above, that each time through the 'for loop', the accel variable is decreasing by 100. If accel started at 1000, this is what accel would look like with respect to the number of iterations of the for loop. You can see that the accel variable decreases at a set rate over time in a linear fashion. Exponential Acceleration Exponential acceleration changes over time too, but it does so more dramatically (It's basically a drama queen). At first the rate of change in the variable is small, but once it begins to increase it really takes off! You can use the power function built into the Arduino IDE to make a variable change exponentially. The power function syntax is quite easy. pow( base, exponent ) The parameter base is the number that get raised to the power of the exponent. Like 2 to the 5th power. Below is an example of how you might code it to change a variable exponentially over the course of a 'for loop'. for (int i = 0; i < 10; i++) { //accel grows exponentially as the for loop continues accel = pow(2, i); }//close for Looking at a chart of accel over the course of the 'for loop', we can see that the way it changes is much different than linear acceleration: The theme for exponential growth is that is starts out slow, but once it starts going it really get's going! Using the Square Root Function for Acceleration The square root function can also provide some flavor to the output from your Arduino. It's syntax is simple: sqrt( x ) It returns the square root of the number or variable that you put in the parenthesis. Below is an easy way to use it in a 'for loop': for (int i = 0; i < 6; i++) { //accel quickly decreases through the loop accel = sqrt(accel); }//close for Let's look at how accel changes over the course of the for loop(let's say it started at 10,000): You can see the a rapid deceleration in the value of the accel variable of the 'for loop'. Practice With Acceleration: If you want to take a look at what these types of acceleration will do in "real" life, then set up the circuit below. You Will Need: (10) LEDs (10) 220 Ohm Resistors (1) Jumper Wire Arduino Board Bread Board Black Marker Set Up The Circuit: Start by by placing one resistor at pin 2 on your Arduino. Connect the other end of the resistor to the breadboard and then connect the long leg of the LED to the resistor. Place the short leg of the LED in the outer ground rail of the bread board. Then add 9 more resistors and LEDs across - you should stop at Pin 11 on the Arduino. Then add a jumper wire from GND on the Arduino to the shared ground on the breadboard. (All LEDs not pictured). That is pretty much it for the circuit. Below are the code examples for the different ways to program acceleration that we talked about: Here is the code for the linear acceleration: /* Linaer ( Constant ) Acceleration The circuit: * LEDs from pins 2 through 11 to ground created 2006 by David A. Mellis modified 30 Aug 2011 by Tom Igoe Modifeid 21 Jul 2014 by Michael James This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Array */ //Declare and initialize variables // The higher the number, the slower the timing. int timer = 1000; // an array of pin numbers to which LEDs are attached int ledPins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // the number of pins (i.e. the length of the array) int pinCount = 10; void setup() { // the array elements are numbered from 0 to (pinCount - 1). // use a for loop to initialize each pin as an output: for (int thisPin = 0; thisPin < pinCount; thisPin++) { pinMode(ledPins[thisPin], OUTPUT); } //Start Serial Communication Serial.begin(9600); }//close setup void loop() { // loop from the lowest pin to the highest: for (int thisPin = 0; thisPin < pinCount; thisPin++) { // turn the pin on: digitalWrite(ledPins[thisPin], HIGH); delay(timer); // turn the pin off: digitalWrite(ledPins[thisPin], LOW); //decrement timer (EASY WAY) timer = timer - 100; //let's take a look at the numbers via the serial monitor window (Tools > Serial Monitor) Serial.print("Back ... LED #"); Serial.print(thisPin); Serial.print(" = "); Serial.println(timer); }//close for //reset timer for next for loop timer = 1000; // loop from the highest pin to the lowest: for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) { // turn the pin on: digitalWrite(ledPins[thisPin], HIGH); delay(timer); // turn the pin off: digitalWrite(ledPins[thisPin], LOW); //decrement timer timer = timer - 100; //let's take a look at the numbers via the serial monitor window (Tools > Serial Monitor) Serial.print("Forth ... LED #"); Serial.print(thisPin); Serial.print(" = "); Serial.println(timer); }//close for //reset timer for next for loop timer = 1000; }//close loop Here is the code for the exponential acceleration: /* Exponential Acceleration The circuit: * LEDs from pins 2 through 11 to ground created 2006 by David A. Mellis modified 30 Aug 2011 by Tom Igoe Modifeid 21 Jul 2014 by Michael James This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Array */ //Declare and initialize variables // The higher the number, the slower the timing. float timer = 1000; // an array of pin numbers to which LEDs are attached int ledPins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // the number of pins (i.e. the length of the array) int pinCount = 10; void setup() { // the array elements are numbered from 0 to (pinCount - 1). // use a for loop to initialize each pin as an output: for (int thisPin = 0; thisPin < pinCount; thisPin++) { pinMode(ledPins[thisPin], OUTPUT); } //Start Serial Communication Serial.begin(9600); }//close setup void loop() { // loop from the lowest pin to the highest: for (int thisPin = 0; thisPin < pinCount; thisPin++) { // turn the pin on: digitalWrite(ledPins[thisPin], HIGH); delay(timer); // turn the pin off: digitalWrite(ledPins[thisPin], LOW); //decrement timer timer = pow(2, thisPin); //let's take a look at the numbers via the serial monitor window (Tools > Serial Monitor) Serial.print("Back ... LED #"); Serial.print(thisPin); Serial.print(" = "); Serial.println(timer); }//close for //reset timer for next for loop // loop from the highest pin to the lowest: for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) { // turn the pin on: digitalWrite(ledPins[thisPin], HIGH); delay(timer); // turn the pin off: digitalWrite(ledPins[thisPin], LOW); //decrement timer timer = pow(2, thisPin); //let's take a look at the numbers via the serial monitor window (Tools > Serial Monitor) Serial.print("Forth ... LED #"); Serial.print(thisPin); Serial.print(" = "); Serial.println(timer); }//close for //reset timer for next for loop timer = 1000; }//close loop Here is the code for messing around with the square root: /* square root The circuit: * LEDs from pins 2 through 11 to ground created 2006 by David A. Mellis modified 30 Aug 2011 by Tom Igoe Modifeid 21 Jul 2014 by Michael James This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Array */ //Declare and initialize variables // The higher the number, the slower the timing. float timer = 1000; // an array of pin numbers to which LEDs are attached int ledPins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // the number of pins (i.e. the length of the array) int pinCount = 10; void setup() { // the array elements are numbered from 0 to (pinCount - 1). // use a for loop to initialize each pin as an output: for (int thisPin = 0; thisPin < pinCount; thisPin++) { pinMode(ledPins[thisPin], OUTPUT); } //Start Serial Communication Serial.begin(9600); }//close setup void loop() { // loop from the lowest pin to the highest: for (int thisPin = 0; thisPin < pinCount; thisPin++) { // turn the pin on: digitalWrite(ledPins[thisPin], HIGH); delay(timer); // turn the pin off: digitalWrite(ledPins[thisPin], LOW); //decrement timer timer = sqrt(timer); //let's take a look at the numbers via the serial monitor window (Tools > Serial Monitor) Serial.print("Back ... LED #"); Serial.print(thisPin); Serial.print(" = "); Serial.println(timer); }//close for //reset timer for next for loop timer = 1000; // loop from the highest pin to the lowest: for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) { // turn the pin on: digitalWrite(ledPins[thisPin], HIGH); delay(timer); // turn the pin off: digitalWrite(ledPins[thisPin], LOW); //decrement timer timer = sqrt(timer); //let's take a look at the numbers via the serial monitor window (Tools > Serial Monitor) Serial.print("Forth ... LED #"); Serial.print(thisPin); Serial.print(" = "); Serial.println(timer); }//close for //reset timer for next for loop timer = 1000; }//close loop I hope the lesson was helpful. The idea of adding acceleration to a sketch can seem a bit intimidating at first, but as you can see, it turns out to be a rather simple addition of code. Try on Your Own Challenge: Can you make the fade amount of an LED accelerate/deccelerate? Can you add a potentiometer to the circuit above and find a way to control the amount of acceleration - either linear, exponential or otherwise.
Discussion: In this lesson, we're going to discuss two very special functions that you will use in every single Arduino sketch that you write. They're called Setup and Loop. Specifically, we’ll cover: How Setup Operates and the type of code that it executes How Loop Operates and the type of code that it executes Loop Function’s Responsive Outputs How to get those little ships inside the glass bottles I want you to pretend for a moment that you own a specialty Italian sub shop. Business is great, and you have wonderful customers. However, you have one major problem. Employee turnover is very high. This is mostly because the majority of your employees are teenagers who, by nature, tend to move on to different things. It feels like as soon as you get an employee trained, they move on to Harvard Business School or get a scholarship to MIT - or they just decide that bungee jumping all day long is better than making subs. In order to help train new employees, you create two binders of procedure lists. One binder is called “The Morning Setup Binder”, and it lists all the stuff that you have to do when you open the store. This binder contains things like unlock the front and back doors, turn on the “Open” sign, put the delivered sausage in the fridge, and get the broccoli out of the fridge. It's stuff that only has to be done once. Once all of that stuff has been done, a new employee can take that binder and stick it on the shelf. Then, they can pull out “The Sub Making Binder”. This is the binder that lists step-by-step everything an employee has to do to make a sub and deliver quality customer service. It might go something like this: When a customer walks in, welcome them with a warm, "Hello!" Ask them what type of sub they want. Ask them what type of bread they want. Ask them what type of condiments they want. Ask them if it will be for here or to go. See if they want to add one of Mama's homemade cookies to their order. I think you get the gist. The binder lists these steps in detail and talks about the quantities of toppings for different subs. “The Sub Making Binder” is really the procedure list that drives the task of the employee and will be the binder that the new employee will keep open all day long when they're starting out. They're going to go back to it over and over again for every sub. So, what does this have to do with programming? Well, a program in Arduino has to do similar things like the sub shop. The Setup Function There are certain tasks that need to be done just once when the program first starts. These are things like: setting up a serial communication to talk with the computer over a USB port, setting the modes of microcontroller pins as either inputs or outputs, displaying a welcome message on an attached LCD screen, or possibly turning a servo to a default location. All of these things might only need to happen once when the sketch first starts and never need to be bothered with again until the program is restarted or the Arduino is reset. These are the type of tasks that are put into a special function called Setup. Let's take a look at Setup. First, notice that the color of Setup is different. Unfortunately, the color is reminiscent of baby poop. This automatic coloring, though, is letting you know that the Arduino IDE recognizes the function Setup as a special type of function that's used for controlling the structure of the code. You'll also notice that right after the word Setup there is an opening and closing parenthesis. The Setup function doesn't need any arguments to operate, but you still have to include the opening and closing parentheses just as you would in any other function. To the left is the word void. Void means that the Setup function will not return any data. So this is a function that doesn't need any arguments from us in order to operate and doesn't return any values to us, but it does do something. Its job is to execute all the code inside its opening and closing curly braces precisely one time. Let me say this again - and with a dramatic pause - because it’s that important! Setup only runs once. When the program starts up, Setup will run just once. All of the code inside the curly brackets will get executed one time. If you pretend the program is like the high schooler at the sub shop, the first thing she does when she comes to work is open “The Setup Binder” and go line-by-line until everything is done. Once everything in Setup is finished, she closes the binder, and then she goes on to the next binder. The Loop Function For the Arduino sketch, the next binder is the Loop function. The Loop function looks just like the Setup function. It doesn't take any arguments. It has the opening and closing parentheses. It doesn't return any values, so it has that void to the left. Then, it has the opening and closing curly brackets. Just like Setup, when Loop gets executed, the program will work line-by-line down the sketch. However, here’s how Loop is different. When the code between the curly brackets has been executed, the program starts back at the top of the loop and does it all over again. Back to our sub shop example, imagine the teenage employee during the lunch hour rush. He has customer after customer lined up, and he's going through each line in the procedure guide step-by-step. He asks what kind of sub they want. He asks what kind of bread they want. He asks if they want it for here or to go, and so on and so forth. He keeps working down that list until he gets to the end of the procedure list. Then, he starts back at the top of the list with the next customer. He does this over and over and over, all through the lunch rush and all day long. This is how the Loop works. It executes all of the code inside the curly brackets, step-by-step. When it gets to the closing curly bracket, it starts all over at the top, working through all of the code again, line-by-line. It does this over and over and over. How fast can it go through the loop? How fast can it actually execute this code? Well, that's a really good question. The answer is that it depends, but the microcontroller that the Arduino uses can run at 20 megahertz. Each line of code you write might end up being multiple instructions when it actually gets translated into machine code, but needless to say, even a sketch with several thousand instructions will be looping pretty fast. Even though I really do like this sub shop analogy, there's one key place that it breaks down. I want to point it out so that you're not misled. In the sub shop example, the teenager waits to start the instructions again when a new customer shows up. In reality, the code in the Loop automatically starts over. Once it gets to the bottom, it jumps back to the top. It doesn't wait for any outside input to do so. Responsive Outputs for Loop Functions You might be wondering how the same code running over and over again can produce any coherent result. How does it add any variation? Well, think about that teenage sub maker. Do you remember the steps that she had to follow? Many of the steps could have different results depending on the response of the customer. So she may have had one procedure guide, but she could make a giant variety of tasty subs as a result. It's the same way with the programming code. You're going to write instructions that will do different things based on different new inputs. For example, if the water level is above some threshold, then beep an alarm. Otherwise, don't do anything. As the code loops over and over again, it's probably doing nothing until it sees that the threshold was too high. Then it executes what you've asked it to do. Or maybe something like... while the light is shining, keep the servo arm at 60 degrees. There's all types of amazing things that you can do and all types of possibilities of how you can control things. There’s one last thing to keep in mind. The Setup and Loop functions are required in your sketches. Your sketches will not compile without them being present. In fact, these two functions are so integral that when you open up a new sketch in the Arduino IDE, you'll find them already there for you pre-populated. Review This was a lot of information, so let's review. Setup and Loop are special functions that help define the structure of the program. Setup is written before the loop and only executes once. All of the code in the Setup function only runs once. The code in the Setup function does things like set pin modes, start serial communication with the computer, display default messages to an LCD screen, or just about anything that needs to happen only once at the beginning of a program. The Loop function comes after the Setup function. All of the code in the Loop function runs over and over forever really fast. Both the Loop and the Setup function are required in your sketch. The program will not compile without them. If you ever forget what the Loop and the Setup do, just say their names. Setup sets up the sketch. Loop loops over and over again. I hope you have a wonderful day, and I can't wait to see you in the next video lesson.
Discussion: We're going to explore some of the specific data types you'll encounter as you begin to program with Arduino. We’ll tackle data types in more detail, to include: Integer and Integer Qualifier Long Float Byte Boolean Character Data Types Recap Let's review what we’ve learned in previous units. We know that when we create a variable, we need to declare its data type. We also know that a data type is simply a way to classify the types of information that you're going to put in a variable. Data type determines several things: what range of values can be stored in the variable how much space and memory that variable needs what types of operations can be performed on that variable Integer We'll begin our discussion of data types with the most common one that you'll see in this course - the integer. This is abbreviated “int” when you type it into the Arduino IDE. The integer is really the go-to data type if you need to store a number. It can hold a value from -32,768 all the way up to 32,767. Keep in mind that it only holds a whole number. You can't store a decimal, such as 3.14, in a variable whose data type is integer. Also, an integer is a 16-bit value. In other words, it takes 16 bits (or two bytes) of memory to store an integer. It doesn't matter if you put a small number in that integer variable like 10, or a big number like 30,000. The compiler will always set aside two bytes for any integer, regardless of number size. In the grand scheme of things, that's pretty small and is why integers are our friends. They don't take up that much space, even if you need to hold a very large value. Now, what happens if you try to put a number bigger than 32,767 inside an integer variable? Well, it actually rolls over. I’m sure most of you are familiar with Pac-Man. You know how if he goes off the screen, he comes right back on the other side? The same thing happens with variables. Let’s say we had an integer variable storing 32,767. Then, we add one to it. The result will actually be -32,768, which is called rolling over. Likewise, if you subtract one from -32,768, the result will be 32,767. This leads us to a really important point. When you create a variable, you should have some idea about how big you expect the stored value will be. That expected value will help you determine what data type you should use for a given variable. Remember, the key aspect of variables is that they change - they can vary. At some point, you'll probably do calculations with those variables and change what is stored there based on your results. You can only put so much water in a bucket before it spills over. Therefore, if the value in that variable at any time exceeds the size allow by its data type, it's going to roll over. You can imagine that might return some really weird results. With this in mind, what happens if you need to store a number bigger than 32,767? Well, you have a couple of options. However, before we abandon the integer for a data type that takes up more of our precious memory storage, let's talk about what signed and unsigned means. Integer Qualifier By default, an integer is signed. This means that it accepts both positive and negative signs. So when we say signed, we're talking about the fact that the value could be negative or positive. What if we know we won’t be working with negative numbers? Our variable will never need to store negative values. For example, if I'm using a variable to store the number of days that have passed, there's never going to be a negative number of days. The number is only going to increase from its starting point - unless, for all of you 80’s kids out there, I jump in a Delorean or something like that. If this is the case, we can use what is called a qualifier to make an unsigned integer. This gets rid of all the negative values and shifts them into the positive range. To use the unsigned qualifier, all you have to do is write unsigned before the “int” data type and voila... now you can store a value in the range from zero to 65,535 AND you’re still only using two bytes of storage. Totally awesome! Rolling over still works the same way, though. If you add one to 65,535, you will roll back to zero. Long That’s great, but what if you need a number bigger than 65,535? This brings us to a long. Long is a data type that stores four bytes of data and can hold a value from -2,147,483,648 to 2,147,483,647. You can think of a long as a really big integer. It acts the same way in that it can only hold whole numbers and can be made to qualify as unsigned if needed. This reaps you a whopping range of zero all the way up to four million and some change. Float We still keep running into this whole number wall, though. What if I want to store a decimal value? In programming, a number with a decimal point is called a floating point number. The point can float around the number. The data type for a floating point number is simply the float, and it can hold a value in the range from 340 undecillion 282 decillion, 315 nonillion (or 3.4028235E38 for you math whizzes). That's pretty big, so you might be thinking, “Geez, how much memory does it take to store a floating point number?” It's actually only a cool four bytes. That's right. It's no bigger than the long. How is this possible? It comes down to precision. In reality, a floating point number is only good up to six or seven actual numbers that mean anything. That's the total number - not just how many numbers after the decimal point. A number like 4,056.897 would be within the precision of a floating point number. You can see we only have seven digits there. The same would go for something like 40.1234. The less significant numbers after that, though, are going to be rounded off, chopped off, and battered. You really don't know exactly how the compiler's going to handle them. Large floating point numbers can be made using a capital “E” following the number. This means the same as it did in math class. For example, 42E2 means 42 times 10 to the second, or 4,200. You can think of the number that follows the E as the number of zeroes you want to add to the number before the E. To be honest, I hardly ever use the E. I just want to throw it out there just in case you run into it. Byte Another data type is the byte. A byte can store a number from zero to 255. As the name implies, it only takes up one byte of storage. That’s extremely small. You could also run into a number like B10010 being set equal to a byte. This is a number represented in the binary numeral system. B is the binary formatter. It lets the computer know to interpret the number following the B as a binary number. We aren’t going to delve into the binary numeral system because we really don't need to right now. You can check out the further reading section if you want to learn more about that, though. Boolean There is a data type that goes even smaller than a byte. The Boolean data type only takes up one bit of data. It can only hold one of two values: either true or false. Boolean is quite interesting. What happens if you try to put the number 2 in a Boolean data type? Does it roll over? No, it doesn't. With Boolean, any value other than zero is true. Numbers like 2, 5, -2, and 47 put in as a Boolean variable would be represented as true. False can be represented by several things. It can be represented by the keyword FALSE, the number zero, or the keyword LOW. We'll talk more about LOW later on. The true state can be represented by the keyword TRUE, any non-zero number as illustrated previously, and the keyword HIGH. If a variable only needs to represent two states, then a Boolean data type is a good option. Character This brings us to the final data type, the character. A character data type takes one byte of storage, and it holds a character symbol, such as a letter. The letter is actually stored as a number, and that number represents a specific text character in a system called ASCII. ASCII stands for the American Standard Code for Information Interchange. It's the way text is encoded numerically in programming. You can assign values to the character data type two different ways. It can be set equal to the actual character you want, as in an actual a, n, asterisk, or dollar sign, but you have to put single quotes around that character. The other way is to assign it as a number value since characters can be represented by numbers. For example, the following two lines of code would be equivalent because 97 is a lowercase a in ASCII code. This also means that you can perform math on characters. We won’t get into that now, but it's kind of neat. Review Let's review what we've covered in this lesson. We talked a little bit more about data types and what they do for us. We talked about integers and the fact that they only hold whole numbers. Roll over and integer qualifiers were also explained, with special attention given to unsigned qualifiers. Long data types were next and how it's a really big number. Then, we moved on to the float for floating point numbers and the byte for simple numbers from zero to 255. The last two data types were Boolean, which is either true or false, and character. I hope you don’t feel overwhelmed with all of this information. You don't have to memorize everything. I just wanted at the very least to give you a feel for what they represent because I guarantee you're going to see them as you open up different programs. Take a deep breath, soak it all in, and I’ll see you in the next lesson.
Discussion: This lesson covers one of the most fundamental of all programming concepts: Variables. This is a really exciting topic because once you have a handle on how variables work, you have one of the biggest keys to understanding how programming works. Specifically, we'll be discussing: Memory Data Types Declaring a Variable Naming Conventions Initializing a Variable What is a variable? Variables are a programming tool that help us store and recall information in our programs. Memory A microcontroller, like the one the Arduino uses, as well as computers in general, have something called memory. Memory is really handy because it allows us to store information for use at a later time. Let's say I'm working on a project that will monitor temperature during the day. I have a temperature sensor that reads the current temperature every 60 minutes from 1 am until midnight. I want the program to record the highest temperature and then display it at the end of the day on an LCD screen. In order for the program to accomplish this, it needs to store two key pieces of information. It needs to store the value of the current temperature, and then it also needs to store the value of the highest temperature that it has encountered thus far. But how do we actually save this information in a sketch? Furthermore, how do we recall it when we need to remember it? In order to do this, we need to use the memory. For now, think of memory as a big wall of lockers, and you can use the lockers to store something. When you need that something again, you just go back to locker and grab it. But how do you remember what locker you put it in? In order for us to do that, we first have to give the locker a name. That name you gave to the “locker”, the place where you’re storing your stuff, is called a variable. Now technically speaking, a variable is the named address of a specific location of memory. However, I don't want to get caught up in all of the technical stuff. I want to dive into the practical use of variables. Therefore, let's go back to this temperature project. As previously stated, we want to record the highest temperature during a 24 hour period. For our program, I need to store those two key pieces of information: the current temperature and the highest temperature. That means I’ll have to name two lockers. I’ll call one locker "Current Temperature", and I'll name another locker "Highest Temperature". Let's say my Arduino begins taking the first reading of the day. Maybe the temperature is 50 degrees. So I'll open the “Current Temperature” locker, and I'll put in the number 50. At the same time, I'll also open up the “Highest Temperature” locker. Right now there's nothing in it, but 50 is larger than nothing. Therefore, I'll put the number 50 in the “Highest Temperature” locker, as well. So now both of our lockers have the number 50 in them. After 60 minutes pass, I read the temperature again. Let's say it has raised two degrees to read 52 degrees Fahrenheit outside. I open up my “Current Temperature” locker, and I put in 52. This means that 52 overwrites the number 50 so that now the “Current Temperature” locker has the number 52 in it. I also peek inside the “Highest Temperature” locker. I see that 52 is hotter than 50. I go ahead and replace that also. I'm just going to repeat that process every hour. I open up the “Current Temperature” locker, replace the old value with the new value, and then check to see if I need to replace the temperature in the “Highest Temperature” locker. This reveals the first really important thing about variables and the most powerful thing about variables. The contents of a variable change. The name of the variable stays the same because the variable is just the container for the information. We don't want to confuse it with the actual information itself. The variable is the locker. It's not the actual stuff inside the locker. Let's recap what we’ve learned thus far. We need to store information, and we use memory to store it. We can think of memory like a wall of lockers. To use one of these lockers, we have to name it, and the name of the locker is called a variable. Once we have it named, we can put stuff in it and refer back to that stuff at a later time whenever we need it again. Again, the name refers to the location of the locker, not the actual content of the locker. Data Types There is another thing we have to do when we make a variable. We also have to say what type of thing we're going to put in it. This is called the Data Type. A good analogy here is to imagine that you have to build a zoo. You have to figure out where each animal is going to go in your zoo, and you have to make sure that each animal is given enough space so it can do its thing. For example, you'll need a bigger cage for a tiger than you will for an African frog display. If you're going to have an aquatic display, you'll need a bigger tank for a shark than you will for a goldfish. Where am I going with this zoo analogy? Here's the deal. You can't take a monkey and put him in a cage designed for fish. Likewise, you can't take a fish and put it in a cage designed for a tiger. It just won’t work. Variables are similar to this because you have to specify a data type for the variable. Maybe an example will clarify what I mean. Let's assume I have a variable, and I say, "This variable can only hold whole numbers." I can put whole numbers in that variable all day long. However, if I try to put a number like a fraction into that variable, I'm going to get an error. The reason is that I specified the data type for that variable to be whole numbers. I can't put a fraction into a variable that I've designated as a whole number variable. Declaring a Variable Creating a variable is called "declaring" it. To declare a variable, you need two things: a name and a data type. The data type comes first, followed by its name. One example of a common data type is an integer. An integer is a data type that can store a whole number from -32,768 to 32,766. Of course, you don’t need to memorize that. Just understand that a whole number is like 1, -5, or 18. It doesn't have a decimal point after it, such as the number 1.0567. In order to specify a variable as an integer data type, we use the abbreviation "int". The Arduino IDE recognizes all possible data types. Therefore, when you type “int”, it will conveniently change the color of the text for you automatically. Following the data type, we need to key in the name. There has to be a space between the data type and the name. You can name a variable almost anything you want, but there are some basic rules to follow. A variable name cannot contain any spaces or special characters, such as a pound sign, dollar sign, or percent. You may use numbers in a variable name, as long as the name doesn’t start with a number. Also, you can't use a keyword as the name of a variable. Keywords are special words that you will learn about later in the course. They're words that the Arduino IDE restricts for certain uses. Just like data types, the Arduino IDE will change the color of the text when you type a keyword. Thankfully, this means you don't have to know all the keywords right now. If you happen to type one, it’ll change color and will help you realize that you can't use that as a variable name. Naming Conventions Using these rules, how should we name variables? Even though you can name them whatever you want, there are still some naming conventions that are best to follow. The bottom line is that your variable names should be descriptive of what information they will hold. For example, if we wanted to save the current temperature in a variable called "mom", we could. However, it really wouldn't make that much sense. It'd be more logical to name that variable "currentTemperature". That way, if somebody else reads our sketch, they will have a basic idea of what information is actually in that variable. Notice how I wrote the word "currentTemperature". I capitalized the T in the second word temperature. This is called camelCase. It's simply a way to help distinguish the words in a variable name. You could also type "current_temperature" with an underscore between the two words. How you write the name of the variable is up to you. The important concept here is that this is called the "naming convention". It is a way to keep things standardized to make the code easier to read and easier to understand. Throughout the course you'll see me use a mix of camelCase and underscoring, depending on the context of the variable I create. Again, you're free to use whatever name you want, as long as you follow the rules we discussed. Initializing a Variable As mentioned before, when we are declaring a variable, we need the data type followed by the name. Then, at the end of that statement, we want a semicolon. Once we've declared a variable, it can now hold information. To put a value inside a variable, we use what is called the "assignment operator", which is simply just an equals sign. The first (or initial) time we assign a value to a variable, it's called "initializing the variable". We can actually declare and initialize a variable on the same line of code. Here’s an example: We have "int" for the data type and "currentTemperature"as the name of the variable. Next, there is the assignment operator, the equals sign. After that is the value to which we are initializing that variable. In this case, the initial value we are putting in the variable is 40. Lastly, we finish the statement with the all-important semicolon. If we want to change that value at some point later in the program, we just use the assignment operator again. In other words, we would type the variable name "currentTemperature", use the equals sign as our assignment operator, type the new value, and then end it with a semicolon. Review Let's recap this lesson. A variable is simply the name of a memory location. It's how we're able to store and recall information in our sketch. In order to use a variable, we have to give it both a data type and a name. The data type determines what we can put in a variable. Although you can use almost anything for a variable name, we did go over a few helpful rules and naming conventions. When we want to assign a value to a variable, we use an equals sign called the assignment operator. The first time we do this, it's called initializing that variable. Throughout the program, if we want to change the value of a variable, we simply type its name, assignment operator, and new value. That concludes this lesson. I know it's all kind of abstract right now, but these concepts will become more concrete as we move forward in the course. I look forward to next time where we'll dive more into data types and the like.
You Will Need: The Arduino IDE installed and an Arduino connected to your computer. Discussion: In this lesson, we're going to be talking about programming syntax. We'll be introducing some of the basic programming syntax that you'll be using every time you write a sketch. Specifically, we'll be talking about: what programming syntax is comments the semicolon keywords function syntax layout & indentation Programming Syntax What is programming syntax? I like to use this analogy. You can think of programming syntax like the punctuation and grammar of computer programming. If you've ever read a book, then you're probably really familiar with written punctuation and grammar. For example, in the written word, we use things such as periods, commas, dashes, or semicolons. Languages also have verbs, nouns, diphthongs, and all types of crazy grammar that goes with them. The punctuation and grammar that you're familiar with are tools that help us communicate effectively with one another in the written word. Commas convey a pause. Periods let us know a sentence has ended. Italics and bold text let us know if a word is emphasized. When we're communicating to another person, these are tools that help us do so. Just as written sentences require correct grammar and punctuation to be correct, the same is true for programming languages. However, with programming, in most cases we're communicating with the compiler - the compiler being the program that looks at our code and creates machine language for us. The programming syntax that we use is meant to communicate our intent to the compiler program. For this reason, the programming syntax MUST be correct. You can get away with messing up some grammar and punctuation when you're writing to a friend or an audience. They'll probably understand what your intent is. On the other hand, if you make an error in your programming syntax, there's almost assuredly going to be an issue. You’ll have either a compiler error when you go to compile the code or a subtle and hard to find bug in the actual operation of your sketch. When you start out, you'll likely find that getting all the program syntax correct is a major hassle. It just doesn't feel natural, and the compiler is far more exacting than most “red pen crazy” elementary school teachers. The good news is that as you get more comfortable in the programming language, the syntax will come more naturally to you. It will become second nature as you write your code. Comments Let's start with one of the most important tools in programming - the comment. Comments are descriptive statements that a programmer writes to help explain the code. They are syntax and punctuation that really have nothing to do with the compiler. In fact, the whole purpose of a comment is so that you can hide these words from the compiler. There are two ways to create a comment. The first is the single line comment, which uses a double forward slash. It looks like this: Notice that all the text after the double forward slash is grayed out. If you have a lot to say, then you can use a multi-line comment. To start a multi-line comment, you type a forward slash followed by an asterisk. Now you can type multiple lines of comments. You'll notice that they're all grayed out. Also, when you press the enter key after that first line, the Arduino IDE actually auto closes the comment for you. It is closed with an asterisk and another forward slash. These additional asterisks on the lines in between are not required, but they are added by the Arduino IDE. These help the multi-line comment stand out from the rest of the code. As I said, comments are hidden from the compiler. They are words specifically for any other person reading your code - not the computer. I won't go into the substance of comments right now. You'll learn more about what comments should say as you work through the course, but I will say that comments should be descriptive statements explaining what that part of the code will do. Semicolons The next thing I want to talk about is the semicolon. The semicolon is to the C++ programming language as the period is to the English language. A semicolon lets the compiler know that a specific statement of computer code is complete. Let's take this line of code: . I know right now this code means nothing to you, but what I want you to see is the semicolon at the end. This semicolon lets the compiler know that your next line of code is independent from the previous one. If you wanted, you could move the semicolon to the next line of code or even insert spaces. It wouldn't make a difference. However, this is horrible form. You really should keep your semicolon on the same line of code that it ends. I just wanted to point this out to demonstrate that the compiler will ignore the spaces before and after a semicolon. If you forget to type a semicolon and then compile your sketch, you may get several different types of errors. I took out the semicolon from the previous line of code and compiled the code using the verify button. I then get an error. The message bar says, “expected unqualified id before numeric constant”. What does that mean? Well, let's look down into the error and see what it actually says. If we look through these error messages, we can see that it's referring to the name of the program and the line of code - line 12. Then it says, “expected comma or semicolon before void”. If we look back up to line 12, it says, “void”. It's saying that it expected a comma or a semicolon. Now we can trace back our steps to that particular line of code and put in a semicolon. If I compile it now, it will be successful. In many cases, error codes are not very informative. Luckily, these are pretty descriptive. They tell you what line of code to look at, and they even tell you what you forgot. So it's pretty handy. Keywords You may have noticed that some of the words typed into the Arduino IDE automatically change color. These are called keywords. Keywords are specially designated terms in a programming language. They perform specific functions for us and are reserved to be used only for those functions. You'll get very familiar with different keywords as you work through the course. Therefore, we won't give an in-depth description of every keyword in this module. Remember, you'll know when you've typed a keyword because it will automatically change color. Function Syntax The next thing I want to talk about are functions. Keep in mind that this is a very cursory overview of functions. I want to give you just the gist of what a function does. Functions are programming tools that package up frequently used pieces of code to make them easy to use. Let's say, for example, that you had some code that did a calculation to convert degrees Celsius to degrees Fahrenheit. Maybe it was just a couple lines of code, but you found yourself using that code pretty frequently. Instead of having to type that code into the program every time you wanted to do the calculation, you could turn it into a function. To use a function, all you have to do is write the name of the function. Then, give it some pieces of information so that it can do the job. For example, if it was a Celsius to Fahrenheit converter, you'd have to give it the temperature in Celsius, and it would give you back the value in Fahrenheit. The Arduino language has tons of built-in functions, and, just like keywords, they also change color automatically when you type them. Functions are kind of like the verbs of a programming language. They make things happen, and they do stuff for us. The real reason I brought up functions isn't because I want to explain how they work. We'll be learning, in detail, about all different types of functions throughout the course. What I really want to talk about is function syntax. All functions are followed by an opening and closing parenthesis. Inside these parentheses is where you give the function what it needs to perform its task. If the function needs multiple pieces of information, those items are separated by commas. Some functions don't take any data, but they still must have a pair of parentheses. Also, every open parenthesis MUST have a closing parenthesis. Notice when I put my cursor on an opening parenthesis that the closing parenthesis is highlighted. Likewise, if I put my cursor by the closing parenthesis, the opening parenthesis is highlighted. This can be a handy tool to determine if you've actually closed the parenthesis after you opened it, or vice versa. Some functions, called control structures, have opening and closing curly brackets following the parentheses. The code that goes between these opening and closing curly brackets will get executed under different circumstances. Just as with parentheses, every open curly bracket must have a closing curly bracket. Furthermore, just like parentheses, if you put your cursor by one of the curly brackets, it will highlight the partner of that curly bracket. Layout & Indentation You may have also noticed that there is indentation in these lines of code. Indentation doesn't communicate anything at all to the compiler, but it helps the author of the code - as well as anyone else reading it- navigate through what’s been written. As a general rule of thumb, when you're writing code inside opening and closing curly brackets of a control structure, the code is indented two spaces from the rest of that code. Then, that indentation continues if a new set of curly brackets is opened up. Another tool for indenting is the “Auto Format” tool in the Arduino IDE. Simply go up to “Tools” at the top of the screen, and then choose “Auto Format”. You could also just press command T. This will automatically create the correct layout for you. It’s much easier to use than manually indenting, and it keeps your code from looking sloppy. Review We talked about what programming syntax is. It’s like punctuation and grammar for computer programming languages. We talked about comments, both single line and multi-line. We also talked about the semicolon and how it's like the period of a sentence for the C++ programming language. Next, we discussed the automatic coloring of keywords and about function syntax. Finally, we talked about layout indenting. That's it for this lesson. Again, this was just a cursory overview. Don't worry about memorizing every little thing and about whether or not you understood the coding shown. That's not the expectation right now. Really we just want to get our eyes inside the Arduino IDE and start understanding some of the basics - symbols being used and what some of the coloring and layout mean. I look forward to seeing you in the next lesson. Try On Your Own Challenge: Type the following code (exactly how it is typed), into the Arduino IDE. Remember - the compiler program will not accept errors - so don't get angry if you see a couple spur up the first time around - it is just part of the learning experience. When you are done, Verify the code by pressing "Control + r", you should not get any errors. //Type this into your Arduino IDE *EXACTLY* how it is typed here. //Don't worry about what the program does - this is about practicing the syntax. //This is a single line commment - What color is the text here? //Will the complier *see* these comments? /* This is a mutli-line comment. Will the compiler see these words? Are these multi-line comments colored different than single line comments? */ String dog; //Which of these words is a keyword? How do you know? //Setup only runs once. void setup() { //notice that setup() has a different color. // Comments are meant to explain your code to you and other people. //Set up Serial Communication. Serial.begin(9600); //This is the color of a library function }//This curly bracket "closes" the setup function. // Put your main code here, to run repeatedly: void loop() { //This curly bracket opens the loop() function. //Assign a bark to the dog. dog = "bark"; //Send the dog bark to the computer. Serial.println(dog); //Upload this code to the Arduino (CONTROL + U) and open the Serial Monitor Window (SHIFT + CONTROL + M) } //This curly bracket closes the loop() function. Further Reading: ; Semicolon {} Curly Braces Comments
Discussion: In this lesson, we're going to do an overview of the Arduino toolchain. The toolchain includes all of the software tools that are between us pressing the Verify/Upload buttons and that code actually getting loaded onto the integrated circuit on the Arduino board. I definitely want to stress the keyword overview because there is a lot going on behind the scenes that actually makes it happen. In practice for us, though, the entire process is just a matter of pressing a button. As we start to dig in, it's tempting to want to know every detail. However, remember that our goal in this course is to learn programming and electronics. If we're not careful, we can get pulled down this huge rabbit hole. That being said, I do think it's important to be familiar with the process. We don’t need to understand it in depth. I just want you to be able to understand and recognize some of the terms and basic concepts associated with this toolchain. Specifically, we’ll discuss: What Is a Toolchain A Toolchain Analogy Toolchain Basics What in the World Is a Toolchain? So, what is a toolchain in the first place? In programming, a toolchain is just a series of programming tools that work together in order to complete a task. If we were cooking something, like carrot soup, the toolchain might include a carrot peeler, a produce knife, a pot, some water, and a stove. Together, these tools help you create the desired output, carrot soup. When we're developing programs for Arduino, we'll also be using a toolchain. This all happens behind the scenes. On our end, we literally only have to press a button for the code to get to the board, but it wouldn’t happen without the toolchain. A Helpful Analogy So, I want to start peeling back the curtain on this Arduino toolchain. Imagine for a moment that you're an author. In fact, you're a New York Times bestselling author... just like me. What type of toolchain might you use? Maybe you start off with text editing software, just like Microsoft Word, to type your awesome story. Once you're done with that manuscript, you send it off to a professional editor at a publishing company. That professional editor is part of this toolchain. He will look over your manuscript and point out any errors. He might do some rearranging and other things, as well. After he sends the suggested edits back to you, you make any necessary corrections. Then, you give the manuscript back to that professional editor to do one last check for errors. He then hands it off to the office next door at that publishing company. The publishing company can't just take that Microsoft Word file and send it off to a printer. They need a special file type to format the book for how it should look on a physical page when it actually gets printed. Therefore, they take the manuscript in a Microsoft Word file format, and they turn it into a new file format. Once this is done, the publisher can send it off to be printed. Luckily, to make the process of printing a whole lot easier, this publisher has an in-house printer. So, he simply needs to just go right down the hall, so to speak. The printer takes that file and prints it onto an actual physical page. So, let's review this author's toolchain. The author writes with a text editor program. Then, he sends the manuscript to an editor at a publishing company. That editor reviews the manuscript until it is perfect. He then sends it next door to be formatted. The manuscript is converted into the proper file format, and it is sent off to the printer to create the physical book. Finally, voilà, somebody buys your book from Amazon to read all about zombies over a warm cup of latte. Arduino Toolchain Basics Why did I go through that long scenario? Well, the Arduino has a similar toolchain. When we start writing our code, and we become the author. We do this in the Arduino IDE, which is akin to a text editor. We also write the code in a programming language called C++, with a file type extension of .ino. The code that we write is called human readable code since it's meant for us to read and, hopefully, understand. However, the Arduino hardware doesn't understand C++ code. It needs what's called machine code. In order to generate that machine code, we use a software tool called a compiler. Remember that Verify button in the Arduino IDE that looks like the checkmark? When you press this button, it compiles the code using compiler software called AVR-GCC. This compiler software does a bunch of stuff. The main thing it does it rearrange some code and check for errors. This is like the professional editor at the publishing company. The compiler also translates the human readable code into machine code. There are some in-between file types and other fuzzy things that go on, but the final output of the compiler is a machine language saved as a .hex file. In order to get this .hex file loaded onto our Arduino's integrated circuit, we need to press the Upload button. This begins another piece of software called AVRDUDE, which sends the file to the integrated circuit. Normally, we would have to use some external hardware to load that circuit. However, in Arduino’s infinite wisdom, they loaded a small piece of software onto the integrated circuit that automatically comes with an Arduino board. That piece of software is called a bootloader. It works with ARVDUDE to take the outputted .hex file and put it onto the flash memory of that Arduino's integrated circuit using only the USB cable. Again, all we had to do was press the Upload button. This whole process happens behind the scenes. Now the process is complete. So, what was our toolchain? We have the Arduino IDE Editor. Then, we have the compiler, which is AVR-GCC. The result is a .hex file. Next, we have AVRDUDE and the bootloader on the integrated circuit of the Arduino board. These work together to upload the .hex file to the board. REVIEW That was a lot of information to absorb. Let’s summarize what we learned in this lesson. First, we learned that in programming, a toolchain is simply a group of software tools used to complete a task. Then we discussed the book publishing analogy to help illustrate that point. Lastly, we walked through the Arduino toolchain. As an encore, we’ll go over that toolchain one more time. We start by writing human-readable C++ code in the Arduino IDE Editor. Then, we click Verify. The compiler program, called AVR-GCC, checks the code for error and adjusts some of the code for us. The result is machine code in a .hex file. When we press the Upload button, AVRDUDE takes that .hex file and works with the bootloader. The bootloader is pre-installed on the Arduino's integrated circuit, and it helps get the machine code loaded onto the Arduino's integrated circuit. Wow, I'm so glad that all happens behind the scenes! Again, this was meant only to be a cursory overview. I wanted to make sure that if you see AVR-GCC in error message or hear the word compiler or any of the other jargon we discussed here, at least you now have an idea of their significance. You now know where they are in the Arduino toolchain.
Discussion: Now that you have downloaded and set preferences, you need to become familiar with the Arduino Integrated Development Environment, or IDE for short. It works just like a text editor program. I'm only going to cover what I think is important for us to know right now. We do a deeper dive on an as needed basis as we progress through the course. Specifically, in this lesson we'll cover: Selecting an Arduino Board and Serial Port Saving an Arduino File The Editor, Message Area, and Console A Few Other “Good to Know” Items So let's open the Arduino Integrated Development Environment (IDE) and get started. Do this by clicking the Arduino icon. Which Board and Serial Port Should I Use? The first thing we're going to discuss is selecting the correct board. We have to let the Integrated Development Environment know what Arduino board you're using. Go to the “Tools” tab, and then go down to where it says “Board”. You'll notice I selected the Arduino Uno since that is what I will use throughout the course. I recommend that you use an Uno or an Uno derivative throughout the course, as well. This will standardize our work in these lessons. Once you've selected the board, next you need to select your serial port. People can sometimes be intimidated by this technical term, but you don’t have to be. Serial ports are just the different things connected to your computer. The easiest way to find out which of the ports listed is your Arduino is to first unplug the Arduino from the computer. Go to the ports list under the “Tools” tab, and write down the names of these ports. You only need to write enough to differentiate one from the next - maybe the last word or last few letters. Then, close your Arduino IDE. Plug your Arduino board back in via the USB cable to your computer. Open the Arduino IDE. You should now be able to see an additional serial port not on the list you originally wrote down. That will be the serial port to which your Arduino is connected. For Mac, you'll usually see cu or tty after the “dev/”. Those are the common ways Arduino will show up on the serial port for a Mac. For a PC, it shows up as a COM port, but it's hard to know which one it will be. It could be one, two, four, etc. That’s why the best method, although primitive, is just to unplug and plug the Arduino back into that port. Once you’ve chosen the board and port the first time, these settings will stay the same for any subsequent times you reopen the Arduino IDE. The reason I point this out is that if you happen to get a different board at some point, you will have to remember to change the board that is selected. The Arduino File When you open the Arduino IDE for the first time, it will open up a file for you, giving it a default name. That default is sketch, underscore, and the current date. That name also appears at the top of the IDE, along with the version of Arduino you're using. To save this, go to the “File” tab and then to “Save”. It's just like saving any other file. Notice it asks you to save the file in “Documents”. Remember that in Arduino, files are referred to as sketches. So, the collection of our sketches is known as the sketchbook. The sketchbook folder is where all of the sketches we write will be saved. Of course, you can also nest your files in that folder just like you could in any other program where you're saving files. It's really no different. Take a look at the name I chose for my file. There are certain rules you must follow when choosing a name for your sketch. When you're naming a file, you can't use any spaces between the words. One common method is to use an underscore where you would have normally preferred a space. You can't use special characters, either. You can use numbers in the name, but you can't have a number as the first character. Lastly, the names are limited to 64 characters. So, using these rules, name your sketch and save it. You'll see that the name on the tab and at the top of the screen now displays the name of your newly saved sketch. So, saving is really easy. The shortcut command is Ctrl S. There is also a down arrow that you can click. The Editor, Message Area, and Console There are three main areas of the Integrated Development Environment: the editor, the message bar, and the console. The editor is the big white space. It’s where you type the Arduino code. It has number lines down the side - as long as that was one of the preferences you checked from our last lesson on choosing your settings. Right now it shows one through nine. If we were to add more code or move our cursor down further, it would adds numbers as lines are added. I want to point out one thing in this name here. Do you see the little funky looking “s”? Every time you make a change to the sketch that has not been saved, that s will be displayed. If I save the file, it goes away. If I were to type something in the sketch again, the funky little s would come back. It’s just a visual reminder to save your changes. Personally, I am a save fanatic. For just about every single line of code I write, I use the shortcut key Control S to save before I go on to the next line. I want to make sure I don't lose anything in the event that I have an issue with either the Arduino IDE, my computer, unexpected interruptions, or whatever might happen. There is something interesting you might have noticed when you open a new sketch in Arduino. It auto-populates two of the mandatory functions for coding in Arduino. This is why you see void setup an void loop. We'll talk about these in depth later, but it's perfectly normal for these to show up. It’s just a way of helping you save time when you code. On top of the editor area are two very important buttons. The first one is a check mark. It is the Verify button. When you click this, the code gets compiled. Compiling, as discussed before, is taking the human readable code that we've written and translating it into machine code. As it compiles, the program will point out any errors found in that code. It also does some optimization. This is a way behind the scenes concept that you don't have to worry about right now, though. You constantly want to check for errors in your code. I like to verify my code at almost every line of code I write along the way. The more you verify, the more quickly you can identify where you might have introduced an error into the code, i.e. find and fix a bug. We'll be using this verify button all the time. The shortcut key for verify is Command R or Control R. You can also verify by going to the “Sketch” tab. That other button is the Upload button. That takes all of the code that we've written and uploads it to the Arduino board. When you click that button and look at your Arduino board (assuming that it’s hooked up to your computer via the USB cable), you'll see two lights blinking rapidly. That is the TX and RX buttons. This is a good visual indicator that you have a good connection between the Arduino board and the computer. The IDE is recognizing that you have a board hooked up. In other words, the lights tell you that the code is successfully being uploaded to the board. The shortcut key to upload is Control U or Command U. It is available in the dropdown under the “Sketch” tab, as well. The second main area of the IDE is this blue bar. It is the message bar. It will display information about what you've done recently in the program. For example, I just uploaded. You can see that it says, “Done Uploading.” If I press Control S to save, it would say, “Done Saving.” There are other pertinent messages that display while you are using the program. The third main area of the IDE is the black space below the message bar. It is called the Console. Now, you probably won't hear it referred to as the console very often. Many people just call it the error section, or some other generic term. If you want to increase the console’s space, there is a bar you can drag up. It may be hard to see, so I put a box around it. The console displays the error messages. It will tell you information about the current operation that you did. For illustration purposes, let me introduce an error into the code and verify it. I’ll just type a crude, uncoded line somewhere in the editor area. You can see that we get definitely get a reaction out of the Arduino IDE. First, the message bar gives us a quick note saying that you wasn’t declared. Again, don't worry about understanding the error itself or any of the terminology displayed. I just want you to see where different types of information shows up. Then, in the console much more detailed information about the error is displayed. It tells you what file it was in, what function it was in, and even the line of code. Here it says the error was in line three. If we look back up at line three in the editor, we can see that it gets highlighted. That's where we can start looking for our error. Unfortunately, it will not always point out the correct line of code for the error. You might have to do a little searching around, but that is a discussion for another time and another lesson. You now know the three big pieces of the Arduino IDE. We walked through the editor, the message bar, and the console. Miscellaneous Tidbits There are a few final items we should discuss that are good to know. At the very bottom of the IDE is a number. Currently ours shows the number three. That simply refers to the line of code where your cursor is located. It seems like such a small detail, but it is very handy. Once you begin to work with larger and larger sketches, it may be harder to keep track of your cursor. This is especially true if you decide not to display line numbers down the side. Also, in the far right corner you'll see some additional information. It is the name of the Arduino board and which serial port that you identified earlier that you’re using. In the top right, there is a little magnifying glass. This is for the Serial Monitor. If you click it, a window like this opens: The Serial Monitor window allows us to see communication occurring between the Arduino and the computer, and vice versa. We'll have an entire lesson later down the road about the Serial Monitor and communications. For now, just know that the button is there. The shortcut key for the Serial Monitor is Shift-Control(or Command)-M. Now Get Going! You now know enough information to start using the Arduino IDE. You can see it's not too complex. The IDE is very simple and streamlined. Arduino was designed for ease of use. There's not a bunch of bells and whistles that can sometimes get in your way. I have no doubt you’ll be an Arduino pro in no time.
Discussion: Before you begin using the Arduino IDE, you must first learn how to download, install, and set your preferences. This lesson is specifically tailored for those who use a Mac. (The last lesson covered this same topic, but for PC users.) I'm currently running Mac OS X Yosemite. You are probably running a newer version of Windows. However, the following instructions will be almost identical from one version to the next. If this should ever change, I’ll update this lesson to reflect those changes. Find the Arduino IDE Download First, jump on the internet with your favorite browser, and navigate to www.arduino.cc. Look for the tab labeled “Download”. The page on which you land might look a little different than this. It does change from time to time, but there will always be an obvious tab for Download. Go ahead and click Download. We're currently working on version 1.6.5, and what you'll do is select your operating system. Click on that “Downloads tab”. That will bring you to the “Download the Arduino Software” page. Once on this page, choose your operating system. For Mac users, you have two options. You can download from the green panel: Or you can get the absolute latest, razor-sharp release of the Arduino IDE. This is found in the section labeled “Hourly Builds”. If you want the most recent update, you can download from this section. But this is just as the name implies. The information here can be updated as often as hourly, and may not be as stable as an official public release. Therefore, in this lesson, I will demonstrate the Windows Installer. This is the best route to go in almost any case. It’s rare that another option is better. Download and Install I’m using Mac OS X. Therefore, I'll click that. It then prompts me to save a Zip file. It doesn't matter where you save this Zip file. I'm going to save it to my Downloads folder. I'm going to save it to my downloads folder. This will initiate the download. It’s not a big file. It’s around 131 Megabytes for this current release. I have just an everyday, run of the mill cable internet connection, and yet it still doesn’t take very long to download. Once it's completely downloaded, I'm going to find it using “Finder”. It found it in my Downloads folder. Double-click your Zip file. The Archive Utility for Mac will automatically unzip it for you. After the Zip file has been unzipped, you'll see that the Arduino IDE icon will be created inside whatever folder you unzipped the Zip file. (I'm just trying to see how many times I can say "Zip".) I'm going to move the Arduino program to the Applications folder on my Macintosh computer. So go to the Macintosh hard drive, then Applications, and then drop it in there. Now, I already have Arduino installed. If you already have an older version of Arduino installed, it will ask if you want to first uninstall the older version before continuing the download of the newer version. My recommendation is to select “Replace” to uninstall the older version. It will not harm anything or delete any work you have done. It simply gets rid of the older Arduino IDE, not your sketch folder. If you don't know what that means, it’s not important. Just know that you will not lose anything if you uninstall. Next, it will run through the uninstallation process. Once completed, you can see that the Arduino icon is in the Applications folder on my Mac. Right-click on this and choose to open it. It's going to give me a prompt the first time I open up the Arduino IDE. It double check whether or not you really want to open it since it is from an unidentified developer. Just click “Open”. By the way, if you try to open the Arduino icon from the Applications folder in your dock, you may not even get an “Open” option. In this case, locate the Arduino icon in the Finder and right click to open. Set Preferences for Arduino IDE Now that the Arduino IDE is open, maximize it. In another video, we'll discuss how this works in-depth, but for now I just want to set some preferences. Go up to Arduino, then click “Preferences”. Probably the most important thing to look at is the first line that comes up - the Sketchbook location. When we write a program in the Arduino IDE, it's called a sketch. All sketches are saved within a Sketchbook. The Sketchbook is a folder where you can to keep all of your work. The default location is usually under UsersThe User’s NameDocuments and then a folder created that is named Arduino. If yours does not look like this, or if you would prefer the Sketchbook folder be in a different place, you can browse to select a different location. I would definitely recommend using a folder named Arduino. This default location has always worked pretty well for me. The next preference to set is the Editor language. You can pick from a bunch of different languages. I'm using English, obviously. Another setting is editor font size. The default is 12, but I prefer a larger font. Font size 18 works very well for me. Be aware that sometimes if you make the font too big, you'll see that one line actually gets written overtop of the other. Therefore, you might have to play around with font to find your optimal size. There are a few other things that I think are good to set in preferences. One is whether or not to display the line numbers. I suggest you check the box for this. It means that each line of your program, or sketch, will be displayed on the left side of the Arduino IDE. Another preferences I suggest you choose is to verify the code after upload. This won't mean anything to you now, but you’ll see later why this it’s an excellent idea to check this feature. The next setting I usually choose is to check for updates on startup. It's not imperative. You can check or uncheck this box depending upon your own personal taste. It depends on whether or not you want to stay with the same current version the whole time. If you just want the most updated version, you can keep that box checked. I do recommend, however, keeping the “Update sketch files to new extension” checked. Basically, this means that whenever you open an Arduino file, it ensures that if the file doesn’t have the proper extension, then that file will automatically be converted to .ino. Arduino files used to have a .pde extension. However, now they are .ino files. That’s why it’s handy to keep this option active. Finally, I think having the last preference chosen is also a good idea. That setting is to save the file when you are verifying or uploading. Again, we'll talk about verifying and uploading in depth in later lessons, but just take my word for now that it is always good practice to save as frequently as possible. Going Old School Not all versions are the same. It could be that maybe you prefer the look and feel of a previous version. Or maybe you’re just really familiar with and used to working within the framework of a certain version. If you prefer to download and use a previous version of Arduino, never fear. We have a solution for you that like to go old school. On the Arduino website for downloads, look to the bottom right panel. There is the section for previous releases. Clicking that will show you a list of all previous releases for each type of operating system, along with the date they were released. Click which you prefer, and from there downloading is the exact same process as before. Again, this lesson applies to those who own Macs. If you are using a PC, you can go back one lesson and see this same download, installation, and preference concept for your particular operating system.
Discussion: Before you begin using the Arduino IDE, you must first learn how to download, install, and set your preferences. This lesson is specifically tailored for those who use a PC. The next lesson will cover this same topic, but for Mac users. I'm currently using a Windows 8.1. You are probably running a newer version of Windows. However, the following instructions will be almost identical from one version to the next. If this should ever change, I’ll update this lesson to reflect those changes. Find the Arduino IDE Download First, jump on the internet with your favorite browser, and navigate to www.arduino.cc. Look for the tab labeled “Download”. The page on which you land might look a little different than this. It does change from time to time, but there will always be an obvious tab for Download. Click on that “Downloads tab”. That will bring you to the “Download the Arduino Software” page. Once on this page, you have several options. You can download the Windows Installer, or you can download a Windows ZIP file if you are a non-administrator. The third option is to get the absolute latest, razor-sharp release of the Arduino IDE. This is found in the section labeled “Hourly Builds”. If you want the most recent update, you can download from this section. But this is just as the name implies. The information here can be updated as often as hourly, and may not be as stable as an official public release. Therefore, in this lesson, I will demonstrate the Windows Installer. This is the best route to go in almost any case. It’s rare that another option is better. Download and Install When you click on the “Windows Installer” link, it takes you to a contributions page. It’s completely up to you if you want to contribute to the Arduino cause. It is a great idea if you do. However, since this is simply a demonstration, I'm just going to choose download. Next, a popup window opens so that you can direct where to save the ZIP file. It really doesn't matter where you save it. I'm going to save it to my downloads folder. It will then immediately start to download. It’s not a big file. It’s around 77.7 Megabytes for this current release. I have just an everyday, run of the mill cable internet connection, and yet it still doesn’t take very long to download. Once the file is done downloading, double click the executable file. This will open a couple of popup windows. The first one is dependent upon whether or not you already have a older version of Arduino installed. If you already have an older version of Arduino installed, it will ask if you want to first uninstall the older version before continuing the download of the newer version. My recommendation is to select “Ok” to uninstall the older version. It will not harm anything or delete any work you have done. It simply gets rid of the older Arduino IDE, not your sketch folder. If you don't know what that means, it’s not important. Just know that you will not lose anything if you uninstall. Next, it will run through the uninstallation process. Once completed, click “Ok”. Then, close the uninstall box. Afterwards, agree to the new license, which is just like any other license that basically says you owe Arduino your children. The popup window then asks you to set a few installation options. Just leave all these checked. Finally, you select the install location. I personally put it into my programs folder. Once you click “Install”, it will start extracting. That's really it for the installation. It does take a little longer than you might expect - maybe a minute or two to install the whole package. Set Preferences for Arduino IDE Once installed, open the Arduino IDE. You can either use the desktop icon or go to your programs folder to use the icon there. We're going to set some Preferences. Go to “File” and then “Preferences”. Probably the most important thing to look at is the first line that comes up - the Sketchbook location. When we write a program in the Arduino IDE, it's called a sketch. All sketches are saved within a Sketchbook. The Sketchbook is a folder where you can to keep all of your work. The default location is usually under UsersThe User’s NameDocuments and then a folder created that is named Arduino. If yours does not look like this, or if you would prefer the Sketchbook folder be in a different place, you can browse to select a different location. I would definitely recommend using a folder named Arduino. This default location has always worked pretty well for me. The next preference to set is the editor language. You can pick from a bunch of different languages. I'm using English, obviously. Another setting is editor font size. The default is 12, but I prefer a larger font. Font size 18 works very well for me. Be aware that sometimes if you make the font too big, you'll see that one line actually gets written over top of the other. Therefore, you might have to play around with font to find your optimal size. There are a few other things that I think are good to set in preferences. One is whether or not to display the line numbers. I suggest you check the box for this. This means that each line of your program, or sketch, will be displayed on the left side of the Arduino IDE. Another preferences I suggest you choose is to verify the code after upload. This won't mean anything to you now, but you’ll see later why this it’s an excellent idea to check this feature. The next setting I usually choose is to check for updates on startup. This is not imperative. You can check or uncheck this box depending upon your own personal taste. It depends on whether or not you want to stay with the same current version the whole time. If you just want the most updated version, you can keep that box checked. I do recommend, however, keeping the “Update sketch files to new extension” checked. Basically, this means that whenever you open an Arduino file, it ensure that if the file doesn’t have the proper extension, then that file will automatically be converted to .ino. Arduino files used to have a .pde extension. However, now they are .ino files. That’s why it’s handy to keep this option active. Finally, I think having the last preference chosen is a good idea. That setting is to save the file when you are verifying or uploading. Again, we'll talk about verifying and uploading in depth in later lessons, but just take my word for now that it is always good practice to save as frequently as possible. Going Old School Not all versions are the same. It could be that maybe you prefer the look and feel of a previous version. Or maybe you’re just really familiar with and used to working within the framework of a certain version. If you prefer to download and use a previous version of Arduino, never fear. We have a solution for you that like to go old school. On the Arduino website for downloads, look to the bottom right panel. There is the section for previous releases. Clicking that will show you a list of all previous releases for each type of operating system, along with the date they were released. Click which you prefer, and from there downloading is the exact same process as before. Again, this lesson applies to those who own PCs. The next lesson explains this same download, installation, and preference concept, except it is for those that work on a Mac.
Discussion: The following videos will show you step by step how to download and install the Arduino Integrated Development Environment, or IDE for short. We'll also be setting up some preferences in the IDE. The phrase Integrated Development Environment may sound complicated and crazy, but it's really not. To be perfectly honest, it looks and feels a lot like a text editor, such as Microsoft Word or Notepad. Arduino IDE is simply a small software program that we're going to load on our computer. It's where we'll write the code that actually gets loaded onto the Arduino board. Consistent Look and Feel It is completely free to download and use. Understand, though, that it's updated all the time. Being kept updated is a good thing. You just need to make sure you are aware of which version you are using. Usually the updates are fairly minor and only affect the appearance of the IDE. Maybe the some of the menu options will be reorganized, or maybe some keyword coloring will change. However, generally speaking, the IDE maintains a consistent look and feel from one version to the next. I really can't stress enough that it doesn't matter which version of the Arduino IDE you're using while you follow along in the course. The Version for This Course For this course and all of the videos, I used Version 1.6.6. Depending on when you take the course, there may be a newer version of the Arduino IDE available. Maybe some of you already have a different version installed. As I said before, the lion's share of the changes from one version to the next are very trivial. The computer code and concepts taught in this course, though, always stay the same. Now, I understand if you want to get the exact same version that we use in the course. This will ensure that everything you see in the videos is a mirror image of what you'll see in your Arduino IDE software. To do this, just make sure you click on Version 1.6.6 when you install. This and all past versions of the Arduino IDE are kept on the Arduino website. We'll discuss this further as we walk through the next few lessons. I can’t wait to get you up and running!
Discussion: Before we can start diving into programming the microcontroller on the Arduino, we need to have a solid understanding of the tools used to make it happen. Therefore, in this particular lesson, we're just going to do an overview of what you'll learn in this familiarization module. As the name implies, this module will get you familiar with the software and hardware tools used throughout this course and beyond. More specifically, this section will cover: The Arduino IDE Version Used in This Course How to Download, Install, and Set Preferences The Arduino IDE Itself The Arduino Board The Arduino Toolchain First, however, I want to explain how best to learn the objectives of this and any other module. There are several things provided in each lesson that can help you be more successful as you move through the course. Obviously, you need to become familiar with the Arduino software and hardware. In addition to this, each lesson has accompanying videos, challenges, and further reading suggestions. Take advantage of these, and you'll easily rock this course! Get to Know Arduino Integrated Development Environment (IDE) In the beginning of this module, we'll discuss administrative items regarding the version of the Arduino IDE used here. Then, I'll walk you step-by-step through downloading and installing the Arduino IDE. We'll also talk about setting up some of the preferences. Once we have it installed, then we'll get familiar with the Arduino IDE itself - some of the buttons, tabs, and that type of thing. Afterwards, we'll take a close look at the Arduino board hardware. Finally, we'll do an overview of the Arduino toolchain. Even if you already have the Arduino IDE installed, and even if you have already been creating programs with it, I still say it's a great idea to watch the videos in this section. There might be a couple of things that can help expand your knowledge of the IDE and the hardware - maybe even some tricks or tips that you've not seen before. Doing the Challenges is the Key to Growth Check out the challenges at the end of each lesson. This lesson will not have challenges since it is just an introduction to the module. However, most lessons will have programming challenges after the lesson discussion. These will help cement in your mind the concepts taught in that lesson, as well as offer more ways for you to practice your newly acquired skills. Practice and repetition will help your grow your knowledge base. By diligently doing the challenges, you'll get some real programming and electronics experience under your belt. Also, pay close attention to the further reading section. It will contain links that will point out other tutorials and helpful online resources online. Of course, don't feel like you have to read every linked article. If there's a resource that I feel is exceptionally helpful, I'll make sure to make a note of it in the further reading section. Enjoy this module!
If Statement (and else-if), Comparison Operators and Conditions In the last lesson, we learned about the if statement. The if statement was the perfect choice for setting up instructions to run only when certain conditions were met. “If 30 seconds has passed – stop the heating element” or “If the sensor perceives a wall – turn 180 Degrees”. This lesson will expand on this amazingly useful function and show you how to stack different conditions to satisfy the flexibility you want in your designs. If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it. You Will Need Potentiometer (doesn’t matter what resistance range) 220 Ohm Resistor LED (any color) Jumper Wires (3) Alligator Clip Dull machete with wood handle Step-by-Step Instructions Place the potentiometer in the breadboard. Place a jumper wire from one of the outside leads of the potentiometer to the 5V pin on Arduino. Place a jumper wire from the other outside lead of the potentiometer to one of the GND pins. Place the final jumper wire from the center pin of the potentiometer to the A0 pin. Connect either side of the 220 ohm resistor to pin 13. Connect the short leg of the LED to GND (the GND pin next to pin 13 is the most convenient). Attach the other leg of the resistor to the long leg of the LED. Plug your Arduino into your computer with the USB cable. Open the Arduino IDE. Open the sketch for this section. Click the Verify button (top left). The button will turn orange and then blue once finished. Click the Upload button. The button will turn orange and then blue when finished. Open up the Serial Monitor window. Tools > Serial Monitor. Adjust the potentiometer and watch as the LED turns on and off based on the knob position. If Then Statement Conditionals Set up This image built with Fritzing. /* Conditionals - If statement This example demonstrates the use of if() statements. It reads the state of a potentiometer (an analog input) and turns on an LED only if the potentiometer goes above a certain threshold level. It prints the analog value regardless of the level. The circuit: * potentiometer connected to analog pin 0. Center pin of the potentiometer goes to the analog pin. side pins of the potentiometer go to +5V and ground * LED connected from digital pin 13 to ground * Note: On most Arduino boards, there is already an LED on the board connected to pin 13, so you don't need any extra components for this example. created 17 Jan 2009 modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/IfStatement */ // These constants won't change: const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 400; // an arbitrary threshold level that's in the range of the analog input void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize serial communications: Serial.begin(9600); } void loop() { // read the value of the potentiometer: int analogValue = analogRead(analogPin); // if the analog value is high enough, turn on the LED: if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } // print the analog value: Serial.println(analogValue); delay(1); // delay in between reads for stability } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 /* Conditionals - If statement This example demonstrates the use of if() statements. It reads the state of a potentiometer (an analog input) and turns on an LED only if the potentiometer goes above a certain threshold level. It prints the analog value regardless of the level. The circuit: * potentiometer connected to analog pin 0. Center pin of the potentiometer goes to the analog pin. side pins of the potentiometer go to +5V and ground * LED connected from digital pin 13 to ground * Note: On most Arduino boards, there is already an LED on the board connected to pin 13, so you don't need any extra components for this example. created 17 Jan 2009 modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/IfStatement */ // These constants won't change: const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 400; // an arbitrary threshold level that's in the range of the analog input void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize serial communications: Serial.begin(9600); } void loop() { // read the value of the potentiometer: int analogValue = analogRead(analogPin); // if the analog value is high enough, turn on the LED: if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } // print the analog value: Serial.println(analogValue); delay(1); // delay in between reads for stability } Discuss the Sketch In this sketch we measure voltage at an analog pin from 0 to 1023 – this voltage changes based on where the knob of the potentiometer is set. We then define a threshold value somewhere in this range, let’s pick the number 400. When the value measured at the analog pin is above 400, we turn on the LED at pin 13, when the voltage is below 400 we turn the LED off. It’s as easy as that. Make sure you read the sketch and try to figure out what is taking place before moving on. This program might look long to you – the previous ones were a bit shorter. A good way to approach any program long or short is to cut it up into chunks and only consider pieces of it at a time. The first chunk in this sketch is the multi-line comments that clearly describe: What the program will do Generally how the program will accomplish it How to set up the circuit and the components you will need Any pertinent notes The license the program is released under (if any) The author, date and version number This might seem like a lot of stuff – but I would recommend you do the same thing for your programs! This information will not only help you understand what the heck you intended when you wrote the program but if you make the program available for others then your comments will help them as well. Some of the functions that are now integrated into the Arduino IDE were created by people just like you – they had a problem, they found a solution with some well-written code, they made it available to all the Arduino users in the world – and everybody else found it useful – and before you know it your code is famous and you win the Nobel peace prize. Enough of this tirade, let’s move onto the first block of code that will be executed by the Arduino. const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 400; // an arbitrary threshold level that’s in the range of the analog input 1 2 3 4 5 const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 400; // an arbitrary threshold level that’s in the range of the analog input Notice that all the variables have const in front of them. This keyword stands for constant. A constant is classified as a qualifier – it adjusts the behavior of the variable being declared. It is similar an adjective in a sentence – “The squishy material,” squishy qualifies what the material will behave. It might seem counterintuitive to the whole point of variables, but the constant qualifier will stop the variable from changing throughout your program. It protects the value from start to finish. Why do this? It protects you from unintentionally writing a new value to the variable. It happens more often than you might think – I recommend using constants when the variable will not change in the program. The integer constants we declare are pretty straightforward. The variables analogPin and ledPin are those pins the potentiometer and LED will be attached to on the Arduino board. Threshold is the arbitrary number chosen as the condition to turn our LED on or off. The next block of code is setup(). Here, we have to set the mode of a pin and set up serial communications. void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize serial communications: Serial.begin(9600); } 1 2 3 4 5 6 7 8 9 10 11 void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize serial communications: Serial.begin(9600); } Recall that all pins are by default set to INPUT, so we do not have to explicitly set the pin mode for our analogPin A0 as an INPUT – though I would argue it is best to do so for clarity. You should have serial communication down pat. We use the begin() function from the Serial library with a baud rate of 9600. Now that we have things setup, let’s get into the loop(). The first line of code we encounter reads from the value at the analog pin A0 and assigns this value to an integer variable called analogValue. int analogValue = analogRead(analogPin); 1 int analogValue = analogRead(analogPin); To do this, we use the analogRead() function. Recall that analogRead() will return a value between 0 and 1023. This value will change as we adjust the potentiometer. This line of code is checking the position of the potentiometer every time through the loop(). The next thing we want to do is compare the value we just read from the analog pin to our threshold value. The if-else statement is perfect for this. if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } 1 2 3 4 5 6 7 8 9 if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } You have seen the if statement before, now we add an else statement. The if statement checks a condition in the parenthesis, if it is TRUE, then the code in the curly brackets is executed – if the condition is not met (FALSE), then it moves to the else statement. Consider this pseudocode: if(apple is NOT rotten) { } else { } 1 2 3 4 5 if(apple is NOT rotten) { } else { } You can see that the else statement gives you control over what to do when the condition in the if statement is not met. In a later lesson we will talk about the else-if statement which will offer even further control over conditions. Explanation of iF-Then Statements In this example the condition we are interested in is: In this example the condition we are interested in is thus… analogValue > threshold 1 analogValue > threshold If this is TRUE we turn the LED on by using the digitalWrite() function: if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } 1 2 3 4 5 if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } If this condition is FALSE we turn off the LED by executing the code inside the curly brackets of the else statement: else { digitalWrite(ledPin, LOW); } 1 2 3 4 5 else { digitalWrite(ledPin, LOW); } Before we continue discussing the sketch, let’s do a quick overview of Comparison Operators. The condition set in an if-else statement will use what are called comparison operators. The list of comparison operators on the Arduino Reference page is as follows: == (equal to) != (not equal to) < (less than) > (greater than) = (greater than or equal to) These operators offer a broad spectrum of comparisons to use. It’s vital to pay close attention to the syntax of the comparison operators. Accidentally dropping an equal sign, or typing a > instead of a < is easy to do, and usually leaves you scratching your head when the program acts differently than you might have expected. Now that we have turned the LED on or off depending on the position of the potentiometer, let’s see exactly what values are being read. We want to do this to ensure the program is doing what we think it should and also to make sure our potentiometer (sensor) is working properly. // print the analog value: Serial.println(analogValue); 1 2 3 // print the analog value: Serial.println(analogValue); This line of code uses the println() function from the Serial library – which (as you know by now) sends the values from the Arduino to your computer. Adjust your potentiometer and watch the values change in the Serial Monitor window. Then adjust the potentiometer so the value is right at the 400 threshold and make sure the LED is responding appropriately. Finally, we want to slow down the readings to add some stability. We do this with the delay() function. delay(1); // delay in between reads for stability 1 delay(1); // delay in between reads for stability Let’s recap. First we read the value at the analog pin and assign that value to a variable. Next we check if that variable is more than or less than our threshold value. If it is above the threshold the LED turns on, if it is below the threshold the LED turns off. We also want to see the actual values at the analog pin, so we print them to the serial monitor. Finally, we wait a millisecond before our next reading – which starts the loop() at the top. You can see how handy the if-else statement can be. As I have said previously, the if-else statement is a staple of programming – you will see it (or a similar form of it), in any programming language you encounter henceforth. Try On Your Own Challenges Adjust the value of the threshold variable. Write an additional if statement to turn on the LED when the analogValue variable is less than 100. The LED should turn on when analogValue is greater than 400 and less than 100. Further Reading If-Else Statement – From the Arduino Reference More on the If-Else statement – The example sketch on the Arduino Website
In the last lesson you learned about using the analogRead() function to collect data from a sensor connected to one of the Arduino analog pins. The range of data we received from the analogRead() function was mapped between 0 to 1023. What if we want to know the actual voltage being applied at the pin? If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it. You Will Need Potentiometer (any resistance range will work) Jumper Wires – at least 3 Persian Rug Step-by-Step Instructions Place the potentiometer into your breadboard. Run a jumper wire from the 5-Volt pin of the Arduino to either one of the outside pins of the potentiometer. Run another jumper wire from one of the ground pins on the Arduino (labeled GND) to the other outside pin of the potentiometer. Run the final jumper wire from pin A0 on the Arduino to the middle pin of the potentiometer. Plug the Arduino into your computer. Open up the Arduino IDE. Open the sketch for this section. Click the Verify button on the top left side of the screen. It will turn orange and then back to blue once it has finished. Click the Upload button (next to the Verify button). It will turn orange and then back to blue once it has finished. On the menu bar, go to Tools > Serial Monitor – this will open the Serial Monitor window – you should see numbers rolling down this screen. Now adjust the knob of your potentiometer and watch the serial monitor window, the numbers should adjust between 0 and 5. Adruino Board Set up For Switch Case This image crafted with Fritzing. The Arduino Code /* ReadAnalogVoltage Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor. Graphical representation is available using serial plotter (Tools > Serial Plotter menu) Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. */ // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V): float voltage = sensorValue * (5.0 / 1023.0); // print out the value you read: Serial.println(voltage); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /* ReadAnalogVoltage Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor. Graphical representation is available using serial plotter (Tools > Serial Plotter menu) Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. */ // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V): float voltage = sensorValue * (5.0 / 1023.0); // print out the value you read: Serial.println(voltage); } Discuss the Sketch This sketch does the exact same thing as the last lesson sketch except for one important change. It takes the reading provided by the analogRead() function and converts it into the actual voltage value at the respective analog pin. Let’s start from the top to review what is taking place. We have no variables to declare and initialize at the beginning of the sketch so we jump right into the setup() function. Inside the curly braces of setup() we begin serial communications by setting the baud rate. This is done using the function Serial.begin(9600). void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } 1 2 3 4 5 6 7 void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } That is all there is to the setup() of this sketch. The next block of code is loop(). Inside the curly braces of loop() the first thing we do is read the value at analog pin A0 and assign it to an integer variable called sensorValue. int sensorValue = analogRead(A0); 1 int sensorValue = analogRead(A0); Once we have recorded this value, we want to convert it to an actual voltage. You will recall that the range returned by the analogRead() function is between 0 and 1023. We want this to reflect the actual voltage at the pin – which is between 0 and 5 volts depending on where the potentiometer knob is turned. So let’s take a look at how we might accomplish this… Explanation of analog sensor code float voltage = sensorValue * (5.0 / 1023.0); 1 float voltage = sensorValue * (5.0 / 1023.0); The first thing we encounter is a new data type – called float. A float is simply a number with a decimal point; say for example 3.14 or 2.17781778. Floats, also called floating point numbers, can be huge in value, and take much more time for the Arduino to churn through than integers – this is why they are used only when necessary. We want the voltage variable set as a float data type because it will provide more resolution than an integer. The voltage variable is set equal to a somewhat confusing calculation. Our goal is to take the value that analogRead() returns and convert it into an actual voltage value. We use a conversion factor to accomplish this feat. By multiplying sensorValue by (5.0/1023.0), it scales down the range from 0-1023 (which is the range that analogRead() returns) to the range 0-5 which is the actual range of the voltage. You can think of the conversion calculation by saying “sensorValue is to X volts as 5 volts is to 1023”, where X is the converted voltage value we are trying to determine. Once we have this new value, it is assigned to the variable voltage – all of this on one line of code. Let’s recap the program… Read the sensor value at an analog pin. Assign this value to a variable. Convert this value to a voltage Save the voltage measurement to another variable And then… Well, we print it back to the serial monitor window so we can see what the voltage is at our pin. The loop() will start over again, it will sample a new value at the pin, it will convert that value and print it, and loop and loop and loop – you get the idea. Try On Your Own Switch from using the 5-volt pin on the Arduino to the 3.3-volt pin. Make sure to adjust the conversion factor. Instead of converting to a voltage value, can you change the conversion factor to return a range from 0 to 100? Further Reading float map() – this function takes the work out of conversion factors – can you implement it here?
Knowing if something is on or off can be extremely useful, but often you will want to know more. How bright is the light? How fast is the satellite moving? These types of answers are often analog – they cover a large range of values, not just on or off. The Arduino handles analog inputs with 6 dedicated pins, labeled A0 through A5. These pins have access to an analog-to-digital converter, which takes the range of input values and creates a digital version by cutting up the range into tiny pieces. All this is handled behind the scenes – all you have to do is use some very simple functions and you will get what you need. You Will Need Potentiometer (any resistance range will work) Jumper Wires – at least 3 Bicycle tire Step-by-Step Instructions Place the potentiometer into your breadboard. Run a jumper wire from the 5-Volt pin of the Arduino to either one of the outside pins of your potentiometer. Run another jumper wire from one of the ground pins on your Arduino (labeled GND) to the other outside pin of the potentiometer. Run the final jumper wire from pin A0 on your Arduino to the middle pin of the potentiometer. Plug the Arduino into your computer. Open up the Arduino IDE. Open the sketch for this section. Click the Verify button on the top left side of the screen. It will turn orange and then back to blue once it has finished. Click the Upload button (next to the Verify button). It will turn orange and then back to blue once it has finished. On the menu bar, go to Tools > Serial Monitor – this will open the Serial Monitor window – you should see numbers rolling down this screen. Now adjust the knob of the potentiometer and watch the serial monitor window. The numbers should adjust between 0 and 1023. Using the Arduino analogread and map function with a potentiometer at pin A0 This image composed with Fritzing. The Arduino Code /* AnalogReadSerial Reads an analog input on pin 0, prints the result to the serial monitor. Graphical representation is available using serial plotter (Tools > Serial Plotter menu) Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. */ // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // print out the value you read: Serial.println(sensorValue); delay(1); // delay in between reads for stability } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /* AnalogReadSerial Reads an analog input on pin 0, prints the result to the serial monitor. Graphical representation is available using serial plotter (Tools > Serial Plotter menu) Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. */ // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // print out the value you read: Serial.println(sensorValue); delay(1); // delay in between reads for stability } Discuss the Sketch This sketch starts with a multi-line comment describing the sketch and the circuit. You will probably notice that the first block of code is the setup() function – we do not declare or initialize any variables at the beginning of this sketch – instead we will do this inside the loop() function, as in the last example. Inside the curly braces of setup() we revisit the Serial library and use the function Serial.begin(). void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } 1 2 3 4 5 6 7 void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } If you recall from the last lesson, Serial.begin() takes the baud rate as an argument (this will almost always be 9600). This function allows you to setup a communication channel between the computer and the Arduino. As you may know by now, setup() only runs once, and then we move on to the next block of code. But wait! Don’t we have to set the mode of the pin we will be using? Great point! What the Arduino does, by default, is set all the pins on the board as INPUTs unless you tell it otherwise. So in many cases, you do not have to explicitly set a pin as an input using the pinMode() function. That being said – I make it a habit to do this anyway – because it makes things clear to me – and that is worth it in space and effort. So I dare you, set the mode of the pin using the pinMode(A0, INPUT) function inside the curly braces of setup()– you won’t regret it. Moving on to the loop() function, we start with a variable declaration and initialization. int sensorValue = analogRead(A0); 1 int sensorValue = analogRead(A0); We declare a variable called sensorValue and we initialize it to the output of a new function. This new function is the glamorous analogRead(). So take a wild guess what this new function analogRead() does. It reads the value at the analog pin that you have chosen – in this case, it is the analog pin A0, where we have the center pin of the potentiometer connected. The voltage at pin A0 will be mapped to a number between 0 and 1023, and this value will be assigned to the variable sensorValue. If you recall from above, the actual voltage at pin A0 will be between 0 and 5 volts, depending on where your potentiometer is adjusted – this value gets mapped to the range 0 – 1023 with the help of the analog-to-digital converter. So we have a variable that has recorded the value at our potentiometer – what next? Well, let’s look at the value. To do that, we need to print it from the Arduino to our computer – and you guessed it, we will use the Serial library function println() to do just that… Serial.println(sensorValue); 1 Serial.println(sensorValue); No big surprises here – we send as an argument the sensorValue variable to the function Serial.println() and our serial monitor window will display the resulting values. To finish the sketch, we invoke the delay() function for one millisecond to make sure our next reading is a stable one and we start at the top of the loop() again. We record a new value using analogRead(), save it to the variable sensorValue and then print it to the computer. All this is good and well, you might be thinking, but what does a potentiometer have to do with sensors? A potentiometer doesn’t sense anything! You are right – but interestingly, many sensors work by applying the same principle that a potentiometer does – adjusting resistance. Take a photo-resister for example – it can be used to sense light – because the resistance changes based on the brightness of light that it is exposed to – this change in resistance will adjust the amount of voltage that a pin on the receiving end will receive. So now the ball is in your court – what can you use analogRead() for? Try On Your Own Change the analog pin to A2. Make adjustments in the code and the circuit. Try a different potentiometer in the circuit, does it affect the range of values displayed? Further Reading analogRead() Analog Input Pins potentiometer tutorial – this is good
As simple as it may seem, knowing when something is either on or off can be a great tool for designing something useful. This lesson will answer the following questions: Is a button being pressed? Has a switch been turned on? What is the on/off sensor status? When you can answer questions like these, you can implement actions based on the current status – if the button is pressed do this – otherwise, do that. If the sensor is HIGH take this action, otherwise do nothing. You get the gist. But before we can implement the actions, we have to be able to track the status and the changes of the digital pins. If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it. You Will Need A momentary push button – this is a button that is spring-loaded, i.e. it never stays in a down position unless it’s held down. Jumper wires (3) A 10,000 Ohm resistor more commonly referred to as a 10K resistor A very ripe banana, (1) – not completely useful, but nutritious Step-by-Step Instructions Connect the pushbutton to the breadboard. Connect one side of the pushbutton to the 5-volt pin on the Arduino board using a jumper wire. Connect one side of the 10K resistor to the other side of the pushbutton. Connect the other side of the resistor to the ground pin on the Arduino. You may have to use a jumper wire to make it reach. On the same side, the resistor is connected to the pushbutton, connect a jumper wire and run it to pin 2 on the Arduino board. Connect the Arduino to your computer with the USB cable. Open the sketch for this section. Click the Verify button in the top left corner of the IDE. The Verify button will turn orange and then back to blue when it has completed compiling. Click the Upload Button (located to the immediate right of the Verify button). This button will also turn orange and then back to blue once the sketch is uploaded to the Arduino board. Now go to the menu bar at the top and select Tools > Serial Monitor. Or you could use the shortcut key, Shift + Control + M. The serial monitor window will open and will be spouting off numbers. It should be a bunch of zeros. Press and hold the pushbutton – watch the serial monitor window, the numbers should now be ones. If the numbers are not scrolling, make sure you click Autoscroll at the bottom left of the serial monitor window. digitalRead Serial Port Circuit This image built with Fritzing. The Arduino Code /* DigitalReadSerial Reads a digital input on pin 2, prints the result to the serial monitor This example code is in the public domain. */ // digital pin 2 has a pushbutton attached to it. Give it a name: int pushButton = 2; // the setup routine runs once: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // make the pushbutton’s pin an input: pinMode(pushButton, INPUT); } // the loop routine runs over and over again forever: void loop() { // read the input pin: int buttonState = digitalRead(pushButton); // print out the state of the button: Serial.println(buttonState); delay(1); // delay in between reads for stability } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 /* DigitalReadSerial Reads a digital input on pin 2, prints the result to the serial monitor This example code is in the public domain. */ // digital pin 2 has a pushbutton attached to it. Give it a name: int pushButton = 2; // the setup routine runs once: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // make the pushbutton’s pin an input: pinMode(pushButton, INPUT); } // the loop routine runs over and over again forever: void loop() { // read the input pin: int buttonState = digitalRead(pushButton); // print out the state of the button: Serial.println(buttonState); delay(1); // delay in between reads for stability } Discuss the Sketch This sketch opens with a multi-line comment containing a short description of the program and circuit. The first block of code following the comment is where we declare and initialize variables. From the last lesson, we are familiar with the integer data type. int pushButton = 2; //This is the pin that our push button is connected to. 1 int pushButton = 2; //This is the pin that our push button is connected to. Notice how the variable pushButton is declared and initialized all on the same line. Also, notice the descriptive name of the variable – pushButton – the variable name implies its use within the program – this is a good example to follow. Let’s consider what we have done so far – we have made a variable that will store the pin number that our pushbutton is connected to. The next block of code we come to is the setup(). Inside these wily curly brackets there are two functions – a familiar one, pinMode() and another which we will learn to love – Serial.begin(). Serial.begin() is part of a family of functions referred to as a library. The name of the library is the Serial library. A library is just a group of functions that work toward a similar purpose. If you had a Circus library, it might contain the functions juggle(), balance() and flamingCircleOfDeath(). To access the functions in a library, you write the name of the library followed by the name of the function in the library, with a period in between. Circus.juggle(); 1 Circus.juggle(); Arduino has many preinstalled libraries. There are also many community-contributed libraries that you can add. You can view all of the preinstalled libraries and some of the contributed libraries at http://arduino.cc/en/Reference/Libraries. So what does the Serial library do? The Serial library helps establish communication between your computer and the Arduino board. If you ever go to marriage counseling, you will learn that communication involves sending and receiving. Data can flow both ways. If we want to establish this communication, we use the begin() function from the Serial library. Serial.begin(9600); 1 Serial.begin(9600); The begin() function takes one argument – the baud rate. What is the baud rate you ask? It is the rate at which data will flow between your computer and the Arduino. For most Arduino sketches a baud rate of 9600 is used as the argument. That’s all you really need to know about the baud rate to get started with serial monitoring. But I have a feeling you want to know more, so if you check out the further reading section at the end of this tutorial, there will be some links to tempt your insatiable desire for acquiring an understanding of all things in the universe. The next function after Serial.begin() is the pinMode() function. We want to set the mode of a pin and what is cool about pinMode() this time around is that we are changing the arguments we pass to the function. Instead of being an OUTPUT (as in the Blink sketch), we want our pin to be an INPUT because we want to read voltage at this pin, not provide it. pinMode(pushButton, INPUT) ; 1 pinMode(pushButton, INPUT) ; Here we use the variable pushButton to let the function know we are setting the mode at pin 2. Then we use the keyword INPUT, to say which mode we want. Those are the only two functions in the setup() curly braces – and just as a reminder – setup() only runs once. The next block of code is the function loop(). What do we see inside the curly braces of the loop()? int buttonState = digitalRead(pushButton); 1 int buttonState = digitalRead(pushButton); Whoa! What the heck is this? It looks like the programmer is declaring a variable! I thought variables were declared at the top of the sketch. While variables are often declared before the setup() function, you can actually declare and initialize a variable just about anywhere in a sketch. Soon you will see why this placement is the way to go. Let’s break down this statement. First, look at the data type and the name. We declare an integer and name it buttonState. Notice the variable name buttonState is indicative of its purpose, as we will see this variable is assigned the position of the button. To initialize the variable, we see something altogether new – the variable is set equal to the output of a function called digitalRead(). This is going to take a little recall power on your part. Do you remember the reason for the word void in front of the loop() function? We had to write void because the function loop() does not return a value. But that is not the case for the function digitalRead(). The digitalRead() function returns an integer – either 1 or 0. This value is then assigned to the variable buttonState. If it is 1, the voltage at the pin is HIGH, if the value is 0, the voltage at the pin is LOW. What pin you ask? Well the pin you pass as an argument in the digitalRead() function. In this case, we send the variable pushButton, because we want to read the state of pin 2 (if you recall pushButton was initialized to equal 2). All of this is in the following line of code: int buttonState = digitalRead(pushButton); 1 int buttonState = digitalRead(pushButton); This is why Arduino rocks – one line of code and you are on your way to dominating the world. Now the state of our pushbutton will be either HIGH (pressed) or LOW (not-pressed). HIGH will be reported as a 1, and LOW will be reported as 0. When we press the pushbutton, pin 2 is exposed to the 5-volts from the Arduino board, this is considered HIGH, and the digitalRead() function will return 1. If the button is not pressed, then all that pin 2 is exposed to is the ground voltage which is 0 and digitalRead() will return 0. Explanation of Digital Read Code In the next line of code we return to the Serial library for another function called println(). Serial.println(buttonState); 1 Serial.println(buttonState); The Serial.println() function returns the value of whatever variable you stick in as an argument. It will report this value to the serial monitor window on your Arduino IDE. To open up the serial monitor window all you have to do is click Tools > Serial Monitor (or SHIFT + CONTROL + M). This is one way to retrieve the data on your Arduino board. Keep in mind, that when you unplug your Arduino and use some batteries to charge it, the Serial.println() function won’t do you much good. But while you are creating the circuit and the sketch, there is no better way to troubleshoot than use the println() and print() functions from the Serial library. So let’s cover what we have done so far in the loop. First we read the state of digital pin 2 and save the state in a variable. Then we display the state in the serial monitor window. Finally, we use the delay() function and wait one millisecond – this allows the reading at the pin to stabilize. Once this is done, the loop starts from the top. We read another value at pin 2 – we are checking every time whether the button is pressed or not pressed – this value gets assigned to our buttonState variable, then we display the newly recorded value to serial monitor window – again. And we do this over and over – hundreds of times per second. So go ahead, press that button, watch the serial monitor window – I think you are already brewing applications for these functions… Try On Your Own Challenge Change the function Serial.println() to Serial.print(). What happens to the output in the serial monitor window? Can you tell the difference between the two functions? Change the pin that you are reading to pin 3. Make the circuit change and the changes to the sketch. Further Reading Baud Rate Serial Library Serial.begin() Serial.println() Serial.print()
The first program you usually write when learning a new programming language is called, “Hello World”. Its only function is to display the words “Hello World” on the computer monitor. When learning to program microcontrollers such as the Arduino, the equivalent of “Hello World” is a program that blinks an LED. Guess what it is called – Blink. You Will Need An LED (any color works fine) A 220 Ohm Resistor An alligator clip (not essential but makes the circuit easier) Fourteen small and smooth rocks from the a western pacific island (not essential but adds an esoteric feel) NOTE: On most Arduino boards there is an LED soldered right by pin 13 – it is actually connected to pin 13 – so if you do not have an LED laying around (or a resistor for that matter), you can use the board mounted LED – it will blink with the same sketch. Step-by-Step Instructions Insert the short leg of the LED into the GND pin on your Arduino (use the GND pin closest to pin 13). Connect the 220 Ohm resistor to pin 13 on the Arduino. It doesn’t matter which way you connect the resistor. Use the alligator clip to connect the long leg of the LED to the other leg of the resistor. If you do not have an alligator clip, twist the two leads together as best you can to get a steady electrical connection. Plug the Arduino board into your computer with a USB cable. Open up the Arduino IDE. Open the sketch for this section. Click the Verify button on the top left. It should turn orange and then back to blue. Click the Upload button. It will also turn orange and then blue once the sketch has finished uploading to your Arduino board. Now monitor the Arduino board – the LED should be blinking. This image was made using Fritzing. The Arduino Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 /* Blink Turns on an LED on for one second, then off for one second, repeatedly. Most Arduinos have an on-board LED you can control. On the Uno and Leonardo, it is attached to digital pin 13. If you're unsure what pin the on-board LED is connected to on your Arduino model, check the documentation at http://www.arduino.cc This example code is in the public domain. modified 8 May 2014 by Scott Fitzgerald */ // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin 13 as an output. pinMode(13, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(13, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } Discuss the Sketch On the previous page, you can see the Arduino code that constitutes the Blink program – make sure to read each line, even if doesn’t make any sense yet. Notice the comments at the top of the program. Note the use of the multi-line comments syntax /* */. It is always a good idea to take time and see what the programmer has to say about the sketch they wrote. The comments will likely be concise, describing how the program works or what it should accomplish. A few may even tell you how to connect the circuit. The next block of code you encounter in the Blink sketch is… 1 2 3 4 void setup( ) { // initialize the digital pin as an output. pinMode(led, OUTPUT); } Recall that the setup() function is in almost every Arduino sketch you encounter. Inside the curly braces is code that will only be run once by the Arduino. For this sketch notice the function pinMode() is inside the curly braces of the setup() function. Let me start by saying that pinMode() is a wonderful function. If you recall, functions can take arguments. The pinMode() function takes two arguments – it wants a pin number and a mode for that pin. The pin number is easy, 0 to 13 for digital pins, and A0 to A5 for analog pins. The mode is an easy designation as well, you want the pin to be either an INPUT (good for reading a sensor) or an OUTPUT (good for powering an LED). When a pin is set as an INPUT, it prepares the pin to read voltages that will be applied at the pin. When a pin is set as an OUTPUT, it prepares the pin to output voltage – more on this later. In this example, we want to light an LED, this requires that voltage is applied at pin 13. Therefore, we need the mode of pin 13 set as an OUTPUT. Keep in mind that setting the mode of the pin to OUTPUT does not apply a voltage, it enables the pin to supply a voltage once it is programmed to do so. Moving on to the final block of code, we come to our favorite and ubiquitous function void loop()… 1 2 3 4 5 6 void loop( ) { digitalWrite(led,HIGH);// turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led,LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } You may recall that void loop() runs over and over again. In this loop, we see two functions: digitalWrite() and delay(). The function digitalWrite() is used to apply either HIGH or LOW voltage to a pin. HIGH will apply 5 volts to the pin you designate and LOW will apply 0 volts. If you apply 5 volts to a pin that is connected through an LED to ground, then the LED will light up. There is a voltage difference between the pin and ground, thus current is able to flow through the LED. If you apply 0 volts to the same pin the LED will not light up because no current is being “pushed” through the circuit – the voltage at ground and at the pin are both zero. 1 2 digitalWrite() takes two arguments, the pin number and the level of voltage, either HIGH or LOW, as we have discussed above. digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) We want to start the loop by applying HIGH voltage to pin 13, where our LED is attached. In the digitalWrite() function we use the variable name ‘led’ to refer back to the value 13 – which was previously assigned. Notice that there is no need to explicitly write 13 in the digitalWrite() function, instead we are able to use the variable ‘led’. Variables are awesome like that – they can take the place of numbers and are much easier to change and track. Every time we use the ‘led’ variable, the Arduino will see 13. If we later decide to move our LED to pin 10, then all we have to do is change the value of ‘led’ once, and all the instances of ‘led’ are changed too. Once digitalWrite() function has been executed, the LED will get bright – we just applied 5 volts, so hey, that makes sense. The next thing we do is delay the Arduino sketch to enjoy the bright glow of our LED. To do this, we use the delay() function. The delay() function takes one argument – the number of milliseconds you want the program to delay. In this case, we want 1000 milliseconds, which equals one second. First we said, “apply high voltage” and now we say – wait one second. Our LED will glow for exactly one second. But that gets old, and we have to stay true to the name of the sketch, so next we tell the Arduino to write a LOW voltage to pin 13 – to do this we use the same function as before, namely digitalWrite(), but, this time, we want LOW voltage instead of HIGH. Now the LED goes dark because no current is flowing. In order to sustain that darkness we use the delay() function again for one second. Now the LED is dark for one second. We are at the end of the loop. We turned the LED on for a second, then we turned it off for a second – what next? Once the Arduino completes the loop, it starts at the top of the loop again and repeats like a broken record. Once again, the LED will light up, delay a second and then go dark for one second. And repeat – now you have a blinking LED – pretty cool for just a couple lines of code! Try on Your Own Challenge Change the value of the delay functions. What happens? Change the number of the led variable to 12 and move the long leg of your LED to pin 12. See what happens. Further Reading int pinMode() digitalWrite() delay()
Arduino Code & Syntax Overview As you learned in Module 01, IDE stands for Integrated Development Environment. Pretty fancy sounding, and should make you feel smart any time you use it. The IDE is a text editor-like program that allows you to write Arduino code. When you open the Arduino program, you are opening the IDE. It is intentionally streamlined to keep things as simple and straightforward as possible. When you save a file in Arduino, the file is called a sketch – a sketch is where you save the computer code you have written. The coding language that Arduino uses is very much like C++ (“see plus plus”), which is a common language in the world of computing. The code you learn to write for Arduino will be very similar to the code you write in any other computer language – all the basic concepts remain the same – it is just a matter of learning a new dialect should you pursue other programming languages. If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it. The code you write is “human readable”, that is, it will make sense to you (sometimes), and will be organized for a human to follow. Part of the job of the IDE is to take the human readable code and translate it into machine-readable code to be executed by the Arduino. This process is called compiling. The process of compiling is seamless to the user. All you have to do is press a button. If you have errors in your computer code, the compiler will display an error message at the bottom of the IDE and highlight the line of code that seems to be the issue. The error message is meant to help you identify what you might have done wrong – sometimes the message is very explicit, like saying, “Hey – you forget a semicolon”, sometimes the error message is vague. Why be concerned with a semicolon you ask? A semicolon is part of the Arduino language syntax, the rules that govern how the code is written. It is like grammar in writing. Say for example we didn’t use periods when we wrote – everyone would have a heck of a time trying to figure out when sentences started and ended. Or if we didn’t employ the comma, how would we convey a dramatic pause to the reader? And let me tell you, if you ever had an English teacher with an overactive red pen, the compiler is ten times worse. In fact – your programs WILL NOT compile without perfect syntax. This might drive you crazy at first because it is very natural to forget syntax. As you gain experience programming you will learn to be assiduous about coding grammar. Let’s get our hands dirty and introduce some syntax. PIcture of Arduino Code Syntax The Semicolon ; A semicolon needs to follow every statement written in the Arduino programming language. For example… int LEDpin = 9; 1 int LEDpin = 9; In this statement, I am assigning a value to an integer variable (we will cover this later), notice the semicolon at the end. This tells the compiler that you have finished a chunk of code and are moving on to the next piece. A semicolon is to Arduino code, as a period is to a sentence. It signifies a complete statement. The Double Backslash for Single Line Comments // //When you type a double backslash all the text that follows on the same line will be grayed out 1 //When you type a double backslash all the text that follows on the same line will be grayed out Comments are what you use to annotate code. Good code is commented well. Comments are meant to inform you and anyone else who might stumble across your code, what the heck you were thinking when you wrote it. A good comment would be something like this… //This is the pin on the Arduino that the LED is plugged into int LEDpin = 9 1 2 //This is the pin on the Arduino that the LED is plugged into int LEDpin = 9 Now, in 3 months when I review this program, I know where to stick my LED. Comments will be ignored by the compiler – so you can write whatever you like in them. If you have a lot you need to explain, you can use a multi-line comment, shown below… /* The multi-line comment opens with a single backslash followed by an asterisk. Everything that follows is grayed out and will be ignored by the compiler, until you close the comment using first an asterisk and then a backslash like so */ 1 /* The multi-line comment opens with a single backslash followed by an asterisk. Everything that follows is grayed out and will be ignored by the compiler, until you close the comment using first an asterisk and then a backslash like so */ Comments are like the footnotes of code, except far more prevalent and not at the bottom of the page. Curly Braces { } Curly braces are used to enclose further instructions carried out by a function (we discuss functions next). There is always an opening curly bracket and a closing curly bracket. If you forget to close a curly bracket, the compiler will not like it and throw an error code. void loop() { //this curly brace opens //way cool program here } //this curly brace closes 1 2 3 void loop() { //this curly brace opens //way cool program here } //this curly brace closes Remember – no curly brace may go unclosed! Functions ( ) Let’s switch gears a bit and talk about functions. Functions are pieces of code that are used so often that they are encapsulated in certain keywords so that you can use them more easily. For example, a function could be the following set of instructions… Wash Dog 1. Get a bucket 2. Fill it with water 3. Add soap 4. Find dog 5. Lather dog 6. Wash dog 7. Rinse dog 8. Dry dog 9. Put away bucket 1 2 3 4 5 6 7 8 9 10 Wash Dog 1. Get a bucket 2. Fill it with water 3. Add soap 4. Find dog 5. Lather dog 6. Wash dog 7. Rinse dog 8. Dry dog 9. Put away bucket This set of simple instructions could be encapsulated in a function that we call WashDog. Every time we want to carry out all those instructions we just type WashDog and voila – all the instructions are carried out. In Arduino, there are certain functions that are used so often they have been built into the IDE. When you type them, the name of the function will appear orange. The function pinMode(), for example, is a common function used to designate the mode of an Arduino pin. What’s the deal with the parentheses following the function pinMode? Many functions require arguments to work. An argument is information the function uses when it runs. For our WashDog function, the arguments might be dog name and soap type, or temperature and size of the bucket. pinMode(13, OUTPUT); //Sets the mode of an Arduino pin 1 2 pinMode(13, OUTPUT); //Sets the mode of an Arduino pin The argument 13 refers to pin 13, and OUTPUT is the mode in which you want the pin to operate. When you enter these arguments the terminology is called passing. You pass the necessary information to the functions. Not all functions require arguments, but opening and closing parentheses will stay regardless though empty. millis( ); //Retrieves the length of time in milliseconds that the Arduino has been running 1 2 millis( ); //Retrieves the length of time in milliseconds that the Arduino has been running Notice that the word OUTPUT is blue. There are certain keywords in Arduino that are used frequently and the color blue helps identify them. The IDE turns them blue automatically. Now we won’t get into it here, but you can easily make your own functions in Arduino, and you can even get the IDE to color them for you. We will, however, talk about the two functions used in nearly EVERY Arduino program. void setup ( ) The function, setup(), as the name implies, is used to set up the Arduino board. The Arduino executes all the code that is contained between the curly braces of setup() only once. Typical things that happen in setup() are setting the modes of pins, starting void setup( ) { //the code between the curly braces is only run once for setup() 1 void setup( ) { //the code between the curly braces is only run once for setup() You might be wondering what void means before the function setup(). Void means that the function does not return information. Some functions do return values – our DogWash function might return the number of buckets it required to clean the dog. The function analogRead() returns an integer value between 0-1023. If this seems a bit odd now, don’t worry as we will cover every common Arduino function in depth as we continue the course. Let us review a couple things you should know about setup()… 1. setup() only runs once. 2. setup() needs to be the first function in your Arduino sketch. 3. setup() must have opening and closing curly braces. void loop( ) You have to love the Arduino developers because the function names are so telling. As the name implies, all the code between the curly braces in loop() is repeated over and over again – in a loop. The loop() function is where the body of your program will reside. As with setup(), the function loop() does not return any values, therefore the word void precedes it. void loop( ) { //whatever code you put here is executed over and over 1 void loop( ) { //whatever code you put here is executed over and over Does it seem odd to you that the code runs in one big loop? This apparent lack of variation is an illusion. Most of your code will have specific conditions laying in wait which will trigger new actions. If you have a temperature sensor connected to your Arduino for example, then when the temperature gets to a predefined threshold you might have a fan kick on. The looping code is constantly checking the temperature waiting to trigger the fan. So even though the code loops over and over, not every piece of the code will be executed every iteration of the loop. Try On Your Own This course is based around the example sketches provided with the Arduino IDE. Open up your Arduino IDE and go to File > Example > 01.Basics and open up three different sketches. Identify the following syntax and functions that you find in the sketches: ; semi-colons // single line comments /* */ multi-line comments { } open and closing curly braces ( ) parenthesis void setup() – identify the opening and closing curly braces void loop() – identify the opening and closing curly braces some blue keywords like OUTPUT or INPUT Further Reading Go to the Arduino Reference page and check out all the syntax under Further Syntax that we talked about. You will find some further useful info on each of these elements.
IDE stands for Integrated Development Environment. Pretty fancy sounding, and should make you feel smart anytime you use it. The IDE is a text editor like program that allows you to write computer code for your Arduino board. When you open up the Arduino program, you are opening the IDE. It is intentionally stream lined to keep things as simple and straightforward as possible. When you save a file in Arduino, the file is called a sketch - a sketch is where you save all the computer code that you have written. Lets take a look at some of the buttons on the IDE. The button that looks like a checkmark is called "verify". When you press this, your code will be compiled and any errors will be displayed in the window at the bottom. The short cut key for verify is Control + R. The button in the shape of an arrow pointing right is the upload button. When you press this, the sketch will be uploaded to your Arduino board. The short cut key for upload is Control + U. The button on the far right side of the screen is the serial monitor button. When you use the serial monitor functions, you can send and receive information from your Arduino board while it is running. We will talk much more about serial monitor later, but I just wanted to point it out now. The shortcut key for serial monitor is Shift + Control + M. *Try On Your Own: This course is based around the example sketches provided with the Arduino IDE. Open up your Arduino IDE and go to File - Example - 01.Basics and open up three different sketches. Try loading the sketches to your Arduino using the mouse and the key board short cuts. *Further Reading:* Check out this Arduino.cc webpage and see if you can identify a couple things you learned and pick up on other things I did not cover.
One of the absolute best things about the Arduino IDE and platform is how easy it is to get started. The software that is installed on your computer is completely free and designed specifically for ease of use. The program is called an Integrated Development Environment, or IDE. The fancy name might intimidate you, but it runs just like a text editing program. As with any software install, you may have some peculiar things working on your computer that can hinder a smooth installation. I have loaded the Arduino several times on different operating systems and have had few problems. Once or twice I had to re-download the zip file that contains the Arduino IDE because somehow or other it got messed up during the download process. You may have to install drivers yourself for your Arduino board – this turns out to be fairly easy and is clearly explained on the Arduino.cc website. To provide you with the most accurate and up to date information about downloading and installing the Arduino IDE, I defer to the Arduino “Getting Started” page. They have done such a clear and concise job of describing the process, I see no reason to repeat it here.
Podcast Notes Stephen has been working hard on getting the crowd funding setup for the FX DEV Board. Video is being recorded now. Should have something to show next week about the video. Parker's bluetooth radio hack for his Jeep is going well. Tested the module and it works. A spare radio to hack on arrived so Parker can get to work. The MacroDuino Rev 2 is working! To make the ATmega328PB work with the Arduino IDE, Parker used the Watterott's ATmega328PB-Testing repo. See Figure 1 of it controlling a light tower. Wall Clock idea is in progress now. Parker will be ordering boards for it soon. Stay tuned for this one. Upgraded USB killer V2.5 U disk killer miniature high voltage pulse generator. Parker and Stephen talked about this on a previous podcast but this is a newer version. The description is full of broken English. High voltage, power must be off after standing for 2 minutes, until the release of more than electricity, and then carefully openings on the motherboard! Solve the USB killer V2.0 problem of unstable extension cable, By the test, extension line 5 meters long, killer can still release pulse. Nothing can stop it from releasing high voltage pulses. What’s New, ESP-32? Testing the Arduino Library. The new ESP-32 now has core support for GPIO, UART, SPI, I2C, and WiFi for the Arduino IDE. The code is on Espressif's github who are the designers of the chip. Interesting that the designers of the chip are pushing the Arduino platform for their hardware. Space Echo progress. Three quarters done. Should have it back together next podcast. Special thanks to whixr over at Tymkrs for the intro and outro!
Chris and Elecia talk about satellites, survey results, and entertainment. ESP8266 has an Arduino IDE (thanks, Karl!) Elecia will be speaking at Solid June 25th and ESC July 22nd. To celebrate the first 100 episodes, Elecia made a spreadsheet of all the guests and topics. Chris read and recommended Neal Stephenson's Seveneves. He was ambivalent about the latest incarnation of battlebots.
Charles Lohr spoke with us about $5 WiFi (ESP8266), hacking as a hobby, arcade games, and music visualization. Updated 06/02/2015: A listener pointed out that the Arduino IDE can program the ESP8266, probably an easier setup than Charles' original article. Also, the Linker post for this show is about getting started with BLE. Follow Charles on YouTube (or say hello on Google+ and Hackaday.io). To get you started, here are Elecia's favorites: High Res Wifi Signal Mapping (ESP8266) ColorChord 2 Wifi Cup (ESP8266) For more about the ESP8266: Charles' Hackaday write up (and github repository) Espressif site Electrodragon, Adafruit, and Sparkfun have modules ST 9 axis inertial measurement unit LSM9DSO
Today we interview Greg Kroah-Hartman and your hosts are Jason Kridner and Jeffery Osier-Mixon. Gerald will be back in two weeks.To provide questions or suggestions:Call +1-713-234-0535 orvisit the BeagleCast suggestions formLinks to the recordingsBeagleCast-20110325.mp3BeagleCast-20110325.oggLinks to show topicsSome in stock @ Digi-Key this week! A 300ms BeagleBoard boot? Using git submodule and busybox to track mainline developmentAnnouncing the Level One eXpansion (LOX) Board BeagleBoard at Embedded Linux Conference (CATCAN, Gumstix Stagecoach, SuperJumbo, Avnet, and WLAN hacking) Always Innovating talk at the 2011 Embedded Linux Conference Sandia cluster of 49 OMAP3s TI introduces OpenLink Processing and Processing-JS on the BeagleBoard under Angstrom BeagleBoard based oscilloscope using JavaScript and Processing.JS Arduino IDE and upload with avrdude to Trainerboard (AVRISP2) Processing on Beagleboard xM Making Processing/Arduino IDE/ReplicaorG work on ARM Android Oscilloscope on the Beagleboard xM using Rowboat Upcoming eventsMaker Faire Bay Area, May 21-22, 2011ESC Chicago, June 6-8, 2011Stompbox Design Summer Workshop at Stanford University, July 18-July 22, 2011 The Greg K-H interview is roughly the last 15 minutes.