Arduino Cookbook: Recipes to Begin, Expand, and Enhance Your Projects - podcast episode cover

Arduino Cookbook: Recipes to Begin, Expand, and Enhance Your Projects

Jun 20, 202523 min
--:--
--:--
Download Metacast podcast app
Listen to this episode in Metacast mobile app
Don't just listen to podcasts. Learn from them with transcripts, summaries, and chapters for every episode. Skim, search, and bookmark insights. Learn more

Episode description

Offers recipes for beginning, expanding, and enhancing projects with Arduino microcontrollers. It covers a wide array of topics, from fundamental mathematical operations and programming concepts like variables, functions, and arrays, to intricate hardware interactions. The book details working with sensors for various inputs like light, sound, and temperature, and controlling physical outputs such as LEDs, motors, and displays. Furthermore, it explores advanced communication methods including serial, wireless, and network protocols like WiFi and Ethernet, providing practical advice on troubleshooting software and hardware issues along with insights into the Arduino build process and library creation.

You can listen and download our episodes for free on more than 10 different platforms:
https://linktr.ee/cyber_security_summary

Get the Book now from Amazon:
https://www.amazon.com/Arduino-Cookbook-Recipes-Enhance-Projects/dp/149190352X?&linkCode=ll1&tag=cvthunderx-20&linkId=4d781027646b90c1fcfef284acd5a893&language=en_US&ref_=as_li_ss_tl


Discover our free courses in tech and cybersecurity, Start learning today:
https://linktr.ee/cybercode_academy

Transcript

Speaker 1

Welcome to the deep Dive, the place where we take your source material and find the most valuable insights just for you.

Speaker 2

And today we're doing a deep dive into these excerpts from the The Ardueno Cookbook, third Edition. You've given us quite a collection.

Speaker 1

Here, right, a really good stack chapters appendices, covering well everything from the real basics like programming in math, all the way up to networking, sensors, motors, sound displays.

Speaker 2

And even the really nitty gritty stuff like low level hardware details and memory optimization.

Speaker 1

It's packed, it really is. Think of this deep dive as your guide, helping you navigate the practical side of making things with Arduino. We're pulling out the key ideas, the surprising details from these sources to get you informed fast.

Speaker 2

Yeah, the goal seems to be moving beyond just blinking an led Right, how do you build something interactive, something connected, something smarter?

Speaker 1

Exactly? So we'll explore the programming building blocks, how your board talks to things, how you sense the world and make things happen in it, connect online, manage time, and.

Speaker 2

Even peek under the hood at the hardware and how to make your code run efficiently.

Speaker 1

Okay, let's unpack this stack. Where do we start foundation? I guess programming basics.

Speaker 2

It makes sense Chapter two parts of the preface ye, chapter one. Yeah, they all lay this groundwork. And yeah, it confirms our dueno programming is based on C and C plus plus nine.

Speaker 1

It feels very practical, not theoretical totally.

Speaker 2

The focus is immediately on what you need to do, like that basic sketch structure you always see set.

Speaker 1

Up which runs just once right when you power up a resea.

Speaker 2

Exactly, and then loop which just well, loops runs over and over.

Speaker 1

And the sources also mention serial event.

Speaker 2

Ah. Yes, that's a handy one. It's a special function that runs automatically if there's new serial data waiting. Good for handling incoming messages without constantly checking in your main loop.

Speaker 1

But not on all boards you mentioned.

Speaker 2

Right, important caveat boards like the Leonardo anything based on the Ateen Mega three to two AT four, they don't support serial event in the same way you'd handle cereal differently there.

Speaker 1

Okay, so inside setup and loop you're dealing with data. The sources introduce data types like INNT and there's a catch there.

Speaker 2

Yeah, this is a good detail. They highlight and int isn't always the same size. On an HUNO an eight bit board it's two bytes okay, But on a thirty two bit board like a SAMD based one, and int is usually four bytes ah okay.

Speaker 1

That could definitely cause problems if you're not expecting it, especially sending data between different board types.

Speaker 2

Precisely, they point out that unsigned short inint is reliably two bytes on both, which can be useful if you need a consistent size.

Speaker 1

Good tip and for collections of data arrays. The sources seem pretty insistent about checking array bounds.

Speaker 2

Oh, absolutely critical. It's so easy to write code that accidentally reads or writes past the end of your array.

Speaker 1

And the compiler one always warn you.

Speaker 2

Often it won't know, and then your sketch just crashes later, maybe seemingly randomly. It's super frustrating. Using a constant for the eray size and checking against it is key makes sense.

Speaker 1

Then there's text. The book compares our dueno string objects with C style character arrays. String seems easier.

Speaker 2

It is definitely more convenient for like joining text together, but there's a trade off, especially on boards with limited RAM like.

Speaker 1

The UNO memory issues.

Speaker 2

Yeah, string objects can use more memory both flash and RAM, and worse, heavy use of string manipulation in a complex sketch can fragment the RAM over time.

Speaker 1

Leading to those mysterious crashes.

Speaker 2

Again exactly so Sea style character arrays. While needing more manual handling, you have to manage the memory yourself, can be much more memory efficient and predictable. They mentioned the start talk function as an example for parsing Sea style strings.

Speaker 1

Good to know the options structuring code is also important.

Speaker 2

Functions defining functions, deciding what they return maybe an end, maybe nothing, void.

Speaker 1

What if you need a function to give back like two or three values.

Speaker 2

The practical way, often shown in examples is to have the function modify global variables rather than trying to return a complex structure. Maybe but it works.

Speaker 1

Okay, then control flowifles switch.

Speaker 2

Standard stuff with switch, Remember it needs numeric constants for the cases, and you must use brake after each case. Usually otherwise, execution just falls through.

Speaker 1

To the next case, ah, right and loops for for a while yep.

Speaker 2

And then operators lots of operators. Your basic math plus minus times divide.

Speaker 1

Increment decrement plus plus plus type. Though the book notes result result plus one is just as efficient and maybe clearer.

Speaker 2

Yeah, result plus plus is common but no real speed game readability is often better. Then there's modulus.

Speaker 1

Percent for remainders useful for checking even nod or wrapping counter.

Speaker 2

Super useful, and comparison operators. Yeah, the big one.

Speaker 3

Don't mix up it, please don't please don't get if value five compares value to five, if value five assigns five to value, and because five is non zero, the if condition becomes always true.

Speaker 1

A nightmare bug defined totally.

Speaker 2

Then logical operators in A and D or candy for combining conditions.

Speaker 1

And bitwise operators for fiddling with individual.

Speaker 2

Bits right and and dan. But often the helper functions are easier bitrid bitright, bitset, bit clear, bit much more readable.

Speaker 1

Good point operator precedents use parentheses to be sure.

Speaker 2

Always good advice, and the book mentions garbage in garbage out. Check your inputs even if example, skip it for brevity. Also, watch out for variable overflow.

Speaker 1

Where a calculation result is too big for the variable type.

Speaker 2

Yep, the ide might not warn you unless you turn warnings way up. For constants, const is better than hashtag define. Why's that? Because const variables have a type so the compiler can check if you're using them correctly. Hashtag define is just text replacement basically, Plus the compiler often optimizes constvarrables away if they aren't needed.

Speaker 1

Smart Lastly, on basics, board variations matter. Three point three V versus.

Speaker 2

Five V huge difference, and not just voltage but pin current limits. An UDO pin might handle forty million amps, but a thirty two bit board pin might only handle seven million amps.

Speaker 1

So you can't just drive an LED directly from any on any board.

Speaker 2

Nope, you have to check the SVATA sheet and form factors differ too, UNO MKR, Nano zero effcshield compatibility. Lots of practical details.

Speaker 1

Okay, solid foundation. Now how do these boards actually talk to things? Cereal I two CSBI right, Chapter four.

Speaker 2

And thirteen get into this. Cereal is kind of the workhorse. Flexible talks to computers other devices.

Speaker 1

Usually over that USB connection, which also uploads the sketch.

Speaker 2

Yep, you start with serial dot begin setting the BOD right, Yeah, crucial step both ends must match speed or yeah gibberish just random characters. Yeah, Then cerreal dot print or serial dot print to send data. A check serial dot available to see if data has arrived, then Cereal dot read to get a byte or serial dot parsit serial dot parse float for numbers.

Speaker 1

You need to decide how to structure the data right text versus binary exactly.

Speaker 2

Text is easier to debug, maybe use commas as dilimiters. Binary is more compact, but you really need to know the data types on both ends. Functions like low byte and i bite help with multibyte values.

Speaker 1

The IDEs Serial monitor and serial quatter are useful.

Speaker 2

Here absolutely monitor for text, plotter for graphing numbers, visually great for sensors. And there are other terminal programs too, like qute com.

Speaker 1

What if you need more serial ports than the board has, like on a MOOO, That's where software Cereal comes in.

Speaker 2

It's a library that lets you use other digital pins to simulate a serial port. Not as fast or reliable as hardware Cereal, but a life saver. Sometimes boards like the Mega or newer ARM boards often have multiple hardware serial ports built in.

Speaker 1

Okay, moving from talking to the computer to talking between chips.

Speaker 2

I two C integrated circuit great protocol uses just two wires SDA and SEL plus power and ground. You can connect multiple devices to those same two wires.

Speaker 1

How does that work?

Speaker 2

Each device needs a unique address. The arduino acts as the master and it addresses the specific slave device it wants to talk to, like maybe a sensor A address serial by five.

Speaker 1

A using the wire library YEP.

Speaker 2

Wired up begin transmission, wired dot write, wired up in transmission to send wired dot request FROUM, and wired dot read to receive sound straightforward. Any catches voltage levels. If you have a five VR duino and a three point three v I two C sensor, you absolutely need a logic level shifter between them, otherwise you risk frying the sensor.

Speaker 1

Ah, good warning. The examples show reading e proms connecting our duenos, even a we nunchuck.

Speaker 2

Yeah, the nunchuck uses it two C for its accelerometer. Cool example.

Speaker 1

Okay, then there's SPI Serial peripheral interface.

Speaker 2

Right, often faster than it. Two C uses four main lines Mosai, MISO, SCK and ss or cs.

Speaker 1

Master out, slave in, master and slave out, clock and slave select exactly.

Speaker 2

MOSAI and MESA are separate data lines, which helps the speed. SCK is the clock signal.

Speaker 1

How do multiple SPI devices work?

Speaker 2

They share Mosai, MISO and SEK, but each slave device needs its own dedicated slave select SS or JIP select cspin controlled by the arduino, So.

Speaker 1

The arduena pulls one CS line low to talk to that specific device precisely.

Speaker 2

The example of using an SD card reader and a TFT display together illustrates this well. Both my use SPI. They share the main three lines, but you need two separate Arduino pins for their individual CS lines.

Speaker 1

Got it. Okay, we know how to program, how communicate. Now let's get our hands dirty interacting with the physical world inputs and outputs.

Speaker 2

Yeah, this is where it gets fun. Chapters five through eleven cover this, starting with inputs digital and analog.

Speaker 1

Digital is just high or low voltage right.

Speaker 2

Digital read after setting the pin with pin mode pin I nput and remember the voltage level for HGH differs between three point three V and five.

Speaker 1

V boards, and analog is analog.

Speaker 2

Reed reads a voltage on an analog input pin and converts it to a number, usually zero to kenna to twenty three. Unos have six analog pins, megas have sixteen.

Speaker 1

The book covers common inputs like switches potentiometers.

Speaker 2

Potentiometers are great examples of analog input and voltage division. Also photo resistors light sensors that change resistance. You need a fixed resistor with to create a voltage divider circuit.

Microphones too, Yeah, electro microphone breakouts. You read them with an analog read but you need to account for the DC offset in the signal temperature sensors like the analog TMP thirty six or the digital DS eighteen B twenty which uses a different protocol called one wire and GPS modules, those usually communicate over cereal sending streams of text data. Libraries like tiny GPS plus make parsing that data much easier.

Speaker 1

What about needing more analog inputs than the board has clever trick.

Speaker 2

Use a multiplexer chip like the forty five to one unless you switch one analog pin between multiple inputs. The book also shows measuring higher voltages using a voltage divider circuit and calculating the actual voltage and reading IR remote controls using the I Remote library.

Speaker 1

Cool now outputs making things happen.

Speaker 2

LED's first the classic, but watch that pin current limit we mentioned forty mari on Uno, maybe only seven marry out another's for bright LEDs or lots of immunia transistor or moss fat to handle the current.

Speaker 1

What about those fancy addressable LEDs NeoPixels very popular?

Speaker 2

Use a library like a to fruit NeoPixel. You tell each pixel what color it should be, then call the show function to update the whole strip at once.

Speaker 1

They mention things like color HSV and gamma thirty two.

Speaker 2

Yeah, color HSV gives you HU saturation value control, which could be more intuitive than RGB sometimes, and gamma thirty two corrects the brightness so colors look more natural to our eyes. Big consideration power Lots of new epixels need a separate BF power supply.

Speaker 1

Okay, what about LED matrices? Lots of simple LEDs.

Speaker 2

Use techniques like multiplexing or Charlie plexing to control many LEDs with fewer pins. The book explains the concepts and wiring. It can get complex, especially animating Charlie plex displays and multiplexing can draw a surprising amount of power.

Speaker 1

Sometimes seven segment displays for numbers.

Speaker 2

Yep again often multiplexed. Understanding common cathode versus common and ode is key, but using an I two C driver chip like the HT sixteen K thirty three makes it much simpler.

Speaker 1

Just two wires plus power moving Beyond simple lights, displays like LCA.

Speaker 2

Text LCDs are common. Use the Liquid Crystal library, print text, set the curser position scroll. You can even create custom characters.

Speaker 1

What about graphical displays olds color LCDs.

Speaker 2

They offer much more detail, but yet more complex wiring. Usually monochrome O leads often use I two C or SPI libraries like Adafruit SSD one three zero six are common. Color LCDs typically use SPI like the ST seven seven seven three five or ST seven seven eight nine. Types. Again, with dedicated libraries, is.

Speaker 1

It hard to switch between display types?

Speaker 2

Sometimes not. Adafruit, for instance, tries to keep their graphics library APIs similar, which helps. The main trade off is often monochrome versus color, cost, memory usage, power draw okay.

Speaker 1

Visual output covered. Let's make things move.

Speaker 2

Servos easiest way to get precise rotational movement. Use the Serbo library attached to a pin tell at an angle with Servo dot write.

Speaker 1

Simple scoops are easy, but there was a timer conflict warning.

Speaker 2

Uh yes, good catch on the un The servil library uses Timer one. Dot analog rite on pins No. Ten also uses Timer one, so you can't use servos NPWM on those specific bins at the same time hardware limitation.

Speaker 1

Good to know DC motors like in Little Robots.

Speaker 2

Right, They need more power than an Ardueno pin can supply, and you usually want to control direction too, so you need external drivers transistors for simple on off or h bridges like the L two ninety three or L two ninety eight for speed and direction control using PWM motor shields bundle this up neatly.

Speaker 1

The book shows controlling motors based on sensors, yeah, like.

Speaker 2

Using photo resistors to make a simple light following robot.

Speaker 1

Classic project stepper motors for more precise positioning.

Speaker 2

Often driven using dedicated driver boards like the Easy Driver for bipolar steppers. The duino tills the driver the direction and when to step, and the driver handles the tricky coil energizing sequences. You might not even need the standard stepper library with that approach.

Speaker 1

Interesting. What about sound?

Speaker 2

Simplest way is the tone function. Connect a speaker or piezo buzzer to a digital pin, give it a frequency in duration beep.

Speaker 1

Can you play melodies?

Speaker 2

Sure? Store the note frequencies and durations in a raise, then loop through them using tone. The book even shows generating tones with more precise microsecond timing.

Speaker 1

MIDI output two YEP.

Speaker 2

Sending many messages out the serial TX pin. Just remember to disconnect anything connected to pin one TX when you upload a new sketch, otherwise the uproad.

Speaker 1

Might fail and complex sounds the odd winosketch.

Speaker 2

Ah yeah, that's a NEAT one, a software synthesizer using potentiometers for control, but the sources mentioned is likely only for eight bit boards like the UNO. A good reminder that some low level code isn't easily portable.

Speaker 1

So much interaction, but timing is crucial for.

Speaker 2

Orchestrating all this absolutely to chapter twelve and eighteen, focus on time. The basic pause is delay stops everything for milliseconds, delay microseconds for shorter pauses.

Speaker 1

There's also a pulse.

Speaker 2

Ent yeah, for measuring how long a digital pulse. Lasts useful, but it has limitations on the range and accuracy of pulses that can bear reliably.

Speaker 1

But delay stops everything, right, that's often bad.

Speaker 2

It often is. That's why the milli's function is so important. It returns the number of milliseconds since the board started. Use it for non blocking timing, like.

Speaker 1

The blink without delay example.

Speaker 2

Exactly check the current millise, compare it to when the last action happened, and if enough time has passed, do the action again and record the new time. This lets your loop keep running quickly, checking sensors, handlink communication, and blinking the LED seemingly all at once.

Speaker 1

Much better. What about scheduling tasks for later?

Speaker 2

The time and time alarms libraries are great for that. You can set alarms to trigger functions once time once or repeatedly time repeat any catches. You must call alarm dot delay frequently in your loop. That's the function that actually checks if any alarms are due. If you don't call it, your alarms won't fire, and there's usually a limit to how many alarms you can have active, like six on AVR boards by default.

Speaker 1

Okay. The book also mentions hardware timers under the hood.

Speaker 2

Yeah, the micro controller ship itself has dedicated hardware timers. Yeah. On the UNO's eighty Mega three twenty eight timers zero is used by Millie's delay and PWM on pins five to six. Timer one is for PWM on pins nine to ten, and the SERVERO Library Tier II is PWM on pins three eleven.

Speaker 1

Ah, So that's the hardware reason for the servo PWM conflict on pins nine to ten. They both need timer one exactly.

Speaker 2

Knowing this helps diagnose weird issues. You can even manipulate the timer registers directly for super precise PWM or timing, but that's getting advanced.

Speaker 1

There was also something about faster analog reads.

Speaker 2

Right, you can change the ADC analog to digital converter clock speed standard and allogreed takes about one hundred and ten microseconds. By tweaking a register, you can get it down to maybe seventeen microseconds on a sixteen megawords board.

Speaker 1

Wow, that's a huge speed up, useful for audio, perfect for.

Speaker 2

Things like audio sampling or capturing other fast changing signals.

Speaker 1

And the Watchdog timer for sleep YEP.

Speaker 2

It's mainly designed to reset the board if the code hangs, but you can also use it to put the board into a low power sleep for sure fixed periods fifteen milliseconds up to eight seconds. You can loop these sleeps for longer low power delays.

Speaker 1

Okay, we've got code communication IO timing. Yeah, what about connecting to the big wide world? Wi Fi and Ethernet?

Speaker 2

Chapter fifteen territory opens up huge possibilities. Ethernet is wired Wi Fi is wireless need specific hardware, of.

Speaker 1

Course, like an Ethernet shield or boards with built in Wi Fi exactly.

Speaker 2

Libraries like Ethernet or waifena handle the low level stuff. The super cheap espaight to sixty six modules are also mentioned, amazing value for adding Wi Fi, though maybe a bit more fiddly to get started with programming them initially.

Speaker 1

So Ardno can be a client or a server on the network. What does being a client involve?

Speaker 2

Initiating connections? Sending simple UDP messages for example, or very commonly acting like a web client, making requests to web servers to.

Speaker 1

Get data like fetching weather data or stock prices.

Speaker 2

Or the example in the book getting the current location of the International Space Station from the open Notify API. The key is making the request and then parsing the response.

Speaker 1

You get back extracting the actual numbers or texts you need from the HTML or JSON right.

Speaker 2

The book shows examples for strings, floats, iNTS. It also covers requesting XML data, sending data using HTTP post like filling out a web form, and getting the time using NTP, even sending tweets YEP, usually via a proxy service like think speak that handles the authentication and for IoT stuff, MQTT is.

Speaker 1

Key message queuing telemetry transport.

Speaker 2

That's the one. Using a library like pubsubclient, your Arduino can publish data like sensor readings to a central broker or subscribe to topics to receive commands or data from other devices. Very efficient for IoT.

Speaker 1

Okay, what about acting as a server.

Speaker 2

That means your Dueno listens for incoming connections. Most common is setting it up as a web server using the relevant.

Speaker 1

Library, so you could type its IP address into a browser and see a page exactly.

Speaker 2

Your Dueno sketch handles the incoming request, figures out what page was asked for, and sends back HTML to the browser.

Speaker 1

Could you control Arduino pins from that web page?

Speaker 2

Absolutely? The book shows handling incoming form data like button clicks on the web page and parsing that data to turn pins high GH or low W.

Speaker 1

For instance, what if the web page has a lot of text memory issues?

Speaker 2

Again, definitely, that's where program and the f macro become absolutely essential. You store all that constant HTML text and flash memory, saving precious RAM. You really have to do this for non trivial server pages on an UNO got it?

Speaker 1

Are there other wireless options besides Wi Fi?

Speaker 2

The book briefly mentions modules like the RFM sixty nine HCW that use unlicensed radio frequencies good for point to point or simple networks over shorter distances use libraries like Radiohead. Also XB modules which are powerful but often more complex.

Speaker 1

To configure, and Bluetooth Low Energy BL using.

Speaker 2

The Rdueno BLE library. Let's shore r Dueno act as a BL peripheral like a sense of Your phone can connect to or connect to other BLE devices qew.

Speaker 1

That's a lot capability. Finally, let's talk practicalities, optimization, troubleshooting. The stuff in the appendices crucial stuff.

Speaker 2

Understanding the build process helps preprocessor compiler AVR GCC for many ar duenas, linker uploader abdude. Knowing these steps exists demystifies things a.

Speaker 1

Bit and memory management. We keep coming back.

Speaker 2

To that because it's critical on small devices. The book shows a function to check free RAM on AVR boards and reiterates use progemm for constant numeric data, use f text for constant text data. Saves RAM on ARM boards. Constant often does the job automatically.

Speaker 1

Okay, troubleshooting code won't compile.

Speaker 2

Check the error messages, and remember the actual error is often on the line before the highlighted one. Missing semicolons, typos case sensitivity, bad comments, using keywords as variable names, common mistakes. Compile often, and.

Speaker 1

If it compiles but doesn't.

Speaker 2

Work, serialed up, print as your best friend. Print out variable values. Print messages to see where your code is actually going. Build complex things incrementally.

Speaker 1

Test each piece hardware troubleshooting.

Speaker 2

Check connections meticulously. Use a multimeter. Wrong voltages are deadly short circuits too. Test components individually. Watch polarity on things like LEDs, dios, transistors, ices, resistors. Most capacitors are non polarized. Breadboards help definitely for prototyping. Fritzing for diagrams, and don't forget snubber.

Speaker 1

Diods for motors and relays.

Speaker 2

Yes, inductive loads create voltage spikes when turned off. A simple diode across the load gives that spike a safe path, protecting your r aduenopin super important.

Speaker 1

Final practical tips, read the data sheet.

Speaker 2

Always, especially for maximum ratings. Understand the code U six permissions from the book. Using snippets is fine. Wholesale copying isn't be careful what external power supplies.

Speaker 1

Wow, Okay, that was a really comprehensive dive through these are Dueno cookbook excerpts. We covered a.

Speaker 2

Ton really did. From the core programming concepts structured data control flow operators, right through communication protocols like serial IT, two C and SPI.

Speaker 1

Then getting hands on with inputs like sensors and switches and outputs like LED's displays, motors.

Speaker 2

Sound mastering time with Millie's and alarms, digging into hardware timers, even speeding up analog reads.

Speaker 1

And connecting outwards with Ethernet and Wi Fi, acting as clients and servers using MQTT plus other wireless tech, and.

Speaker 2

Wrapped up with vital optimization techniques especially for memory and solid troubleshooting advice for both software and hardware bugs.

Speaker 1

It's pretty amazing how these sources lay out practical recipes for tackling quite complex tasks with these little micro controller boards.

Speaker 2

Yeah, it breaks it down into manageable steps, showing you the libraries, the functions, and crucially those practical gotchas like timer conflicts or voltage levels.

Speaker 1

So for you listening, this deep dive should give you a really solid map of the practical techniques available. You've seen recipes for everything from reading a button to hosting a web page to driving a robot arm.

Speaker 2

So here's a final thought to take away. You've now seen how you can combine sensors to perceive the world, actuators and displays to effect it, communication to connect it, and timing to orchestrate it, all using these different ingredients from the cookbook. What kind of truly interconnected may be unexpected responsive project could you build? Now? What surprising interaction could you create by mixing these capabilities

Transcript source: Provided by creator in RSS feed: download file
For the best experience, listen in Metacast app for iOS or Android