Arduino C++ by Example

date
May 23, 2024
type
KnowledgeBase
year
slug
arduino-cpp-examples
status
Published
tags
Arduino
C++
Microcontroller
summary
Learn Arduino C++ by Example
🚧
Work in Progress
This page teaches you by example. The Arduino C++ page takes the opposite approach and explains all the basic concepts of programming, then gives appropriate examples. 🔀 Choose whichever you prefer!

Basics setup and Serial Output

  • setup() gets called once when you program starts
  • loop() runs repeatedly again and again and again for as long as your program runs
Let’s make an example where we create a variable called count, increment it every second and print the current value to the Serial port, so we can see it in the Serial Monitor:
Now if we run this program we can open the Serial Monitor and watch the output of our microcontroller!
notion imagenotion image

Serial Input

We can also send data back to our program via the Serial Monitor! In this next example we’re going to wait for the user to enter ‘1’ or ‘0’ and we’ll turn on an LED accordingly!
⚙️
This example is set up for an 🎮 Arduboy with a common cathode RGB LED. If you want to use the 🔆 internal LED of your Arduino instead:
  • Replace const int ledPin = 10; with const int ledPin = LED_BUILTIN;
  • Switch digitalWrite(ledPin, HIGH) and digitalWrite(ledPin, LOW) since single color LEDs usually turn ON when the pin is set to HIGH and OFF when the pin is set to LOW
  • ▶️ Run the program
  • Open the Serial Monitor
    • Make sure it’s set to 9600 baud
    • Set it to No Line Ending
    • Now enter 1 or 0 into the Message field, press enter to submit and watch the LED turn on or off!
notion imagenotion image

More Serial Input

This time we want to read a whole String, not just single characters! Let’s ask the user some questions!

Leave a comment