Skip to content

4. Embedded Programming

view Checklists Checklist: personal
- [x] DeepL check spelling, grammar
- [ ] repair file links, replace .png -> .jpg; .mov -> .mp4, .webp
- [ ] remove audio from video, compress
- [ ] GPT check for better markdown
- [ ] compress all files before push
- [ ] double check the code, add comments
- [x] read the ATtiny412 datasheet
- [ ] check if it has a analog digital converter for processing signals form hall sensors
- [x] use ATtiny85 with - 2 button (replacement digital hall sensors) - red LED (rear light) - white LED (front light) - [slider poti (replacement for analog IR reflection sensor)] - 5 white LED's (replacement for surrounding light matrix) - [x] program AT tiny
- [x] create simulation for my AT Tiny board in Wokwi
- [ ] read the RP2040 datasheet
Checklist: Nueval: Student's checklist
- [x] Linked to the group assignment page
- [x] Browsed and documented some information from your microcontroller’s datasheet
- [x] Programmed your simulated board to interact and communicate
- [ ] Described the programming process(es) you used
- [x] Included your source code
- [x] Included ‘hero shot(s)’
Checklist: Task list Class/Nueval
Group assignment
- [ ] Demonstrate and compare the toolchains and development workflows for available embedded architectures
- [ ] Document your work to the group work page and reflect on your individual page what you learned
Individual assignment
- [x] Browse through the datasheet for your microcontroller
- [ ] Write a program for a microcontroller, and simulate its operation, to interact (with local input &/or output devices) and communicate (with remote wired or wireless connection)

Intro

My existing knowledge of embedded programming was very limited before this week. Before I started, I did some research on my team colleges pages and used Jarni's and Jakob's documentation.

My takeaways are:
- I want to use an AVR ATtiny 412 chip for my final project
- I want to use one of the XIAO's as the programmer device for the ATtiny

My prior experience before this week was:
- loading the blink program to the Arduino
- turning some LEDs on and off - lab class with a TI development board (with rotary encoders, leds, motor, sound)
- university class on Java for basic programming skills

and thats about it, thats why I start with the basics again!

Basic Knowledge

I used the Practical Microcontroller Primer Guide to get started!

These are my notes:

A micro… controller?

  • Microprocessor is just a processor
  • Microcontroller is
    • Microprocessor
    • RAM (typically SRAM)
    • ROM

Codes to Instructions

This overview is very helpful in understanding the layers of embedded systems programming.

layer / domain layer description
1 / code application code the software you wrote! human readable, logical description of how the computer should operate
2 / code algorithm / library other code modules; human readable, logical descriptions of generalized computing routines / sub-tasks
3 / compiler programming language the set of syntax / logical rules that each layer above abides: naming, typing, order of operations, conditionals, etc
4 / compiler assembly language a much “lower-level” (meaning less abstracted) programming language, with a strong correlation to machine operating codes (aka "symbolic machine code")
5 / compiler machine code the actual instructions that a machine (CPU) will read: numbers passed into registers and operated on, no symbols here
6 / compiler instruction set architecture the ISA is to machine code what a programming language is to application code: a list of instructions CPUs interpret if they implement the ISA
7 / physics micro architecture the actual design / implementation / layout of gates, busses, registers, etc; the shape of the CPU/device, fabricated with semiconductors
8 / physics devices (transistors) n-p-n baby
9 / physics physics / matter / time / quarks literal spacetime and matter propagating information/state about the universe, coordinated for meaningful operations on voltage levels
  • .bin .hex files are flashed to the MCU
    • are a binary file with 0 and 1

Programming / debug protocols

  • low level communication between MC and computer
  • flash protocol is baked into the micro's hardware
  • adapter requires for computer to speak low level protocol

Overview of protocols: - UPDI is one of them

Toolchains

The toolchain is a combination of different hardware and software tools that communicate with each other to transfer the binary file to the microcontroller.

Bootloaders

Most of the processor boards we carry have a pre-loaded program called a 'Bootloader'. A Bootloader is a program that allows you to load other programs via a more convenient interface like a standard USB cable. When you power-up or reset your microcontroller board, the bootloader checks to see if there is an upload request. If there is, it will upload the new program and burn it into Flash memory. If not, it will start running the last program that you loaded.
from Adafruit - Bootloaders

  • pice of code stored at the beginning of the flash
  • runs for the first few milliseconds to check for new flash request
  • takes up a bit of space on the flash

Special Function Registers

  • abbreviated SFR
  • schematic of a microcontroller is usually showing the SFR
  • small circuits that perform a specialized function
  • work independently of the CPU
    • SFRs don't reduce the CPU performance
  • examples
    • DAC's digital to analog converters
    • ADC's analog to digital converters
    • USB
    • SERCOM (for UART, SPI, I2C)
  • SFR's are addressed with static defined bits in the memory
  • SFR's are usually processor specific

Special Function Registers can be 'emulated' with software librarys. To implement everything in software is not efficient and hurts the performance of the CPU and the available space on the Flash memory.

Abbreviations and Vocabulary

EEPROM vs. Flash

Hardware features

EEPROM - Electrically Erasable Programmable Read-Only Memory

  • non volatile memory
  • EEPROM uses NOR type
  • has per-byte erase-and-write capabilities, which makes it slow
  • suitable for applications where frequent updates are not required
  • limited write-erase cycle endurance
  • EEPROM uses I2C and SPI Interface

Flash memory

  • special type of EEPROM
  • uses NAND-type memory
  • programmed and erased in large blocks

BOD - Brown-out Detection or Low Voltage Detect (LVD)

  • important feature to increase the reliability of a microcontroller after power-up
  • detects when supply voltage drops below threshold
  • places device in reset state
  • Low Voltage Detect (LVD)
    • more advanced version
    • can set interrupts before reset voltage level is triggered

Watchdog Timer (WDT)

  • piece of hardware
  • detects software anomalies
  • resets the processor after error
  • counts down from value to zero
  • software periodically restarts the machine before counter reaches zero

Real Time Clock (RTC)

  • pice of dedicated hardware or in the microcontroller
  • keeps track of the current year, month, date, and time

Protocols

Protocols allow communication from - chip to chip - chip to user - chip to peripheral - chip to programmer Interface converter chips exist to translate between different protocols!

UPDI - Single Pin Unified Program Debug Interface

  • programming protocol
  • typically uses 6 pin header on boards

UART - Universal Asynchronous Receiver Transmitter protocol

  • serial interface type
  • used in general purpose microcontrollers with moderate pin counts
  • has RX and TX pins for communication
  • extra start and stop bits to each byte, helping the receiver sync up to data as it arrives
  • both sides must also agree on the transmission speed (baud rate)
  • most devices only support a certain set of fixed baud rates
  • baud rate defines the speed of communication

USART - Universal Synchronous Asynchronous Receiver Transmitter protocol

  • is based on UART
  • uses RX and TX for communication
  • has a clock pin (XCK)
  • has direction pin (XDIR)
  • data rate is generated internally with clock
  • faster data rates than UART

I2C - Inter-Integrated Circuit

  • intended for short distances within a single device
  • requires only two signal wires
  • two wires can support up to 1008 peripherals
  • supports multi-controller system
  • hardware required to implement I2C is more complex than SPI, but less than asynchronous serial

SPI - Serial Peripheral Interface

  • intended for short distance
  • synchronous data bus
  • send data between microcontrollers
  • send small peripherals
    • SD cards
    • sensors
  • separate clock and data lines
  • keeps both sides in perfect sync
  • requires at least four wires
  • CS Chip Select line to select the device you want to talk to
  • multiple peripherals can be connected
    • CS line for each device
    • CS line for all devices (daisy chain)

Group Assignment

The group assignment can be found here

What did I lear from the Group Assignment

  • MCU - microcontroller group that shares the same architecture
    • AVR (Arduino uno type)
    • ARM (smartphones, powerful embedded systems)
    • PIC (made by Microchip Technology, 8Bit data)
  • Programming a chip
    • In-System Programming
      • programming after soldering it to the board
    • Pre-Programming
      • programming the microcontroller before it is mounted to the board

Individual Assignment

The Microcontrollers

ATTINY Arduino Toolchain

ATtiny412 (AVR)

I chose the ATtiny412 processor because it is very small cheap and has a low power consumption, which is ideal (later turned out to be wrong) for my plans for the final project.
Here is the basic information which is relevant for me about the chip.

I read parts of the official ATtiny412 Datasheet. The datasheet has 479 pages! I only used the information that was of interest to me. A lot of information was not (yet) useful for me, e.g.: - special positions in the memory - address maps for the cpu - stack pointer things - register descriptions - ... many more

Overview

Things I have not yet understood are italic:

  • CPU
  • AVR® 8-bit CPU
  • Running at up to 20MHz
  • Single Cycle I/O Access
  • Two-level Interrupt Controller
  • Two-cycle Hardware Multiplier

  • Memories

  • 2/4KB In-system self-programmable Flash Memory
  • 64/128B EEPROM
  • 128/256B SRAM

  • System

  • Power-on Reset (POR)
  • Brown-out Detection (BOD)
  • Clock Options:
    • 16/20MHz Low Power Internal RC Oscillator
    • 32.768kHz Ultra Low Power (ULP) Internal RC Oscillator
    • 32.768kHz External Crystal Oscillator
    • External Clock Input
  • Single Pin Unified Program Debug Interface (UPDI)
  • Three Sleep Modes:

    • Idle with All Peripherals Running and Mode for Immediate Wake Up Time
    • Standby
    • Configurable Operation of Selected Peripherals
    • SleepWalking Peripherals
    • Power Down with Wake-up Functionality
  • Peripherals

  • 6-channel Event System
  • One 16-bit Timer/Counter Type A with Dedicated Period Register, Three Compare Channels (TCA)
  • One 16-bit Timer/Counter Type B with Input Capture (TCB)
  • One 12-bit Timer/Counter Type D Optimized for Control Applications (TCD)
  • One 16-bit Real Time Counter (RTC) Running from External Crystal or Internal RC Oscillator
  • One USART with Fractional Baud Rate Generator, Auto-baud, and Start-of-frame Detection
  • Master/Slave Serial Peripheral Interface (SPI)
  • Master/Slave TWI with Dual Address Match
    • Standard Mode (Sm, 100kHz)
    • Fast Mode (Fm, 400kHz)
    • Fast Mode Plus (Fm+, 1MHz)
  • Configurable Custom Logic (CCL) with Two Programmable Lookup Tables (LUT)
  • Analog Comparator (AC) with Low Propagation Delay
  • 10-bit 115ksps Analog to Digital Converter (ADC)
  • 8-bit Digital to Analog Converter (DAC)
  • Five Selectable Internal Voltage References: 0.55V, 1.1V, 1.5V, 2.5V and 4.3V
  • Automated CRC Memory Scan
  • Watchdog Timer (WDT) with Window Mode, with Separate On-chip Oscillator
  • External Interrupt on All General Purpose Pins

  • I/O and Packages

  • 6 Programmable I/O Lines
  • 8-pin SOIC150

  • Temperature Ranges

  • -40°C to 105°C
  • -40°C to 125°C Temperature Graded Device Options Available

  • Speed Grades

  • 0–5MHz @ 1.8V – 5.5V
  • 0–10MHz @ 2.7V – 5.5V
  • 0–20MHz @ 4.5V – 5.5V

Here is an overview of the ATtiny Series 1 processors.
This is a good overview if I later need some additional ports or memory later.

This is the naming info on how the ATtiny naming scheme works.

Block Diagram for ATtiny212 and ATtiny412 (Page 12)

Pinout (Page 13)

Clock Controller (Page 56)
  • option for external clock
  • ultra low power clock – 32KHz Ultra Low Power oscillator (OSCULP32K) -(CLK_MAIN) is used by the CPU, RAM, and the IO bus
Sleep Controller (Page 70)

Three sleep modes:
- Idle - Standby - Power Down Configurable Standby sleep mode where peripherals can be configured as on or off.

ATtiny1624 (AVR)

I originally wanted to use the ATtiny412 for its small size and low cost, but for I/O reasons I moved up to the next larger chip in our lab, the ATtiny1624.

Overview

Things I have not yet understood are italic:

  • High-Performance Low-Power AVR® CPU
  • Running at up to 20 MHz
  • Single-cycle I/O access
  • Two-level interrupt controller with vectored interrupts
  • Two-cycle hardware multiplier
  • Supply voltage range: 1.8V to 5.5V

  • Memories

  • 16 KB In-System self-programmable Flash memory
  • 2 KB SRAM
  • 256B EEPROM
  • 32B of user row in nonvolatile memory that can keep data during chip-erase and be programmed while the device is locked
  • Write/erase endurance
    • Flash: 10,000 cycles
    • EEPROM: 100,000 cycles
  • Data retention: 40 years at 55°C

  • System

  • Power-on Reset (POR)
  • Brown-out Detection (BOD)
  • Clock options:
    • Lockable 20 MHz Low-Power internal oscillator
    • 32.768 kHz Ultra Low-Power (ULP) internal oscillator
    • 32.768 kHz external crystal oscillator
    • External clock input
  • Single Pin Unified Program Debug Interface (UPDI)
  • Three sleep modes

    • Idle with all peripherals running and immediate wake-up time
    • Standby with configurable operation of selected peripherals
    • Power-Down with full data retention
  • Peripherals

  • One 16-bit Timer/Counter type A (TCA) with a dedicated period register and three PWM channels
  • Two 16-bit Timer/Counter type B (TCB) with input capture and simple PWM functionality
  • One 16-bit Real-Time Counter (RTC) running from external 32.768 kHz crystal or internal 32.768 kHz ULP oscillator
  • Two Universal Synchronous Asynchronous Receiver Transmitters (USART) with:
    • Fractional baud rate generator
    • Auto-baud
    • Start-of-frame detection
  • Master/Slave Serial Peripheral Interface (SPI)
  • Master/Slave Two-Wire Interface (TWI) with dual address match:
    • Standard mode (Sm, 100 kHz)
    • Fast mode (Fm, 400 kHz)
    • Fast mode plus (Fm+, 1 MHz)
  • Event System for CPU independent and predictable inter-peripheral signaling
  • Configurable Custom Logic (CCL) with four programmable Look-Up Tables (LUT)
  • One Analog Comparator (AC) with scalable reference input
  • One 12-bit differential 375 ksps Analog-to-Digital Converter (ADC) with:
    • Programmable Gain Amplifier (PGA)
    • Up to 15 input channels
  • Multiple internal voltage references:
    • 1.024V
    • 2.048V
    • 2.500V
    • 4.096V
    • VDD
  • Automated Cyclic Redundancy Check (CRC) flash memory scan
  • Watchdog Timer (WDT) with Window Mode, with a separate on-chip oscillator
  • External interrupt on all general purpose pins

  • I/O and Packages

  • Up to 22 programmable I/O pins
  • 14-pin
    • SOIC
    • TSSOP
  • 20-pin
    • SOIC
    • SSOP
    • VQFN 3x3 mm
  • 24-pin

    • VQFN 4x4 mm
  • Temperature Ranges

  • -40°C to 85°C (standard)
  • -40°C to 125°C (extended)

  • Speed Grades (-40°C to 85°C)

  • 0–5 MHz @ 1.8V – 5.5V
  • 0–10 MHz @ 2.7V – 5.5V
  • 0–20 MHz @ 4.5V – 5.5V

  • Speed Grades (-40°C to 125°C)

  • 0–8 MHz @ 2.7V – 5.5V – 0-16 MHz @ 4.5V - 5.5V

Here is an overview of the ATtiny Series 2 processors.
This is a good overview if I later need some additional ports or more memory.

Here is the important info: More I/O pins!

XIAO ESP32-S3

The ESP32 series are chips based on the 32-bit Tensilica Xtensa LX6 processor. They are designed for IoT applications, but can be used in many other applications.

XIAO ESP32-S3 Datasheet (Hardware)

ESP32-S3 official datasheet

XIAO ESP32-S3 Programming (Software)
Installing the Arduino IDE

As far as I know, Arduino IDE can program - AVR (Arduino Uno's) - Tensilica (ESP32 boards) - probably many more I don't know about yet

Arduino IDE - Download

Setup for XIAO ESP32-S3

Right out of the box the XIAO ESP32-S3 comes with the 'Sens' program, which indicates touching the pinsby with lighting up the amber LED on the board. That worked!

To set up the Arduino IDE I used the official documentation.

To upload code to the XIAO I connected the right software port to write programs to the XIAO! It worked!

The last test was to compile and upload the 'Blink' program and it worked too! now I was ready to start my first adventures in the microcontroller world!

Push Button

The following 'Push Button' program was written with Jarni who helped with my Embedded Programming and Embedded Networking and Communications assignments.

The 'Push Button' is shown below or can be downloaded as an .ino file.
Download: push_button.ino

view push_button.ino code
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 1;  // the number of the pushbutton pin
const int ledPin = 2;    // the number of the LED pin

// variables will change:
int buttonState = 0;  // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}


After compiling and uploading my 'Push Button' program, it can be tested as seen in the video.

Simulation

Wokwi


Wokwi is a simulation platform for simulating code on embedded microcontroller boards including

  • Arduino
  • ESP32
  • STM32
  • Pi Pico

Wokwi simulates external hardware such as LEDs and buttons but not under real world conditions, so resistors are not needed.

Getting Started

To use Wokwi no installation is needed just go to Wokwi.com and create a new project. I also created an account to store all my projects.

Wokwi official documentation

For my first project I crated 'Blink' with an ESP32-S2 in the Arduino IDE environment.

Wokwi's limitations: - compilation time depends on server load - only public projects (only private with payment)

Shortcuts and usage

R - rotate object

use the 'Library Manager' to install standard libraries or install Wokwi libraries.

ATtiny85

official Wokwi ATtiny85 documentation

ATtiny85 - Starter Project

Since I want to use one of the ATtiny series processors in my final project, I chose the tiny85 template and recreated blink with this limited chip.

To help me debug my code, I first installed the TinyDebug library. The debug output can help me to debug my code with Wokwi, but later in hardware the debug messages are nowhere to be seen.

ATtiny85 - Software serial

Setting up a softwareSerial with the SoftwareSerial library.

ATtiny85 - I2C communication

TinyWireM - GitHub

ATtiny85 - Input-Output code for LUEDO (final project)

For the final project I plan to use the ATtiny412 which is available in our lab. Since Wokwi doesn't have the ATtiny412 as a simulation, I used the tiny85 instead. For the input and output devices I also used replacements.

Here are the components for my setup: - ATtiny 412 - replaced with ATtiny85 - digital hall sensor (A3144) - replaced with two switches - analog IR reflection sensor (TCR5000) - replaced by a slider potentiometer - red LED (back light) - white LED (front light) - 5 white LED's (replacement for surrounding light matrix)

After running the code, the LEDs would not turn off or blink randomly because I was missing the red pull-up wire.

The red pull-up wire quickly solved the problem.

This is the setup that should mimic the demonstrator board which I build before the FabAcademy. I tried to reuse the code, but realized that I would have to start from scratch and rewrite the code for the smaller chips.

At this point I realized, that I need more I/O pins for my final project to add another button and maybe later a temperature and voltage sensor for the battery.
Unfortunately, I will have to upgrade to a larger chip.

The next chip which is available in our lab is the ATtiny1624. Go back to the basics and read the Datasheet!

Arduino Uno R3

I decided to use the Uno R3 with the ATmega328 chip as a replacement for the ATtiny1624 I plan to use in my final project.

Arduino Uno R3 - Input-Output code for LUEDO (final project)

I used replacement components to represent sensors that are not available in Wokwi.

Component Actual Sensor
Right switch Digital Hall sensor (front)
Middle switch Digital Hall sensor (back)
Left switch Digital IR reflection sensor
Button Main button on the bike light
White LED Front beam light
Red LED Rear beam light
Yellow LEDs Ambient light array

Here is the final demonstration of the setup

For trying out the simulation yourself, just open the LUEDO_Uno_code_e Wokwi project

view 'LUEDO_Uno_code_e' Arduino Uno code
// Pin assignment
// Input pins
const int hallSensorFrontPin = 7; // Hall sensor front pin (white light)    //replaced with sliding switch
const int hallSensorBackPin = 8;  // Hall sensor back pin (red light)       //replaced with sliding switch
const int mainSwitchPin = 5;      // Main switch pin                        //green push button 
const int irSensorPin = 6;        // Infrared sensor pin                    //replaced with sliding switch
//output pins
const int whiteLedPin = 3;        // White LED pin                          
const int redLedPin = 2;          // Red LED pin
const int yellowLedPin = 4;       // Yellow LED pin

// Variables
unsigned long pressStartTime = 0; // Time when main switch was pressed
bool isAmbientMode = false;       // Status for ambient light mode
bool whiteLedOnBySwitch = false;  // Status of white LED controlled by main switch
bool yellowLedOnBySwitch = false; // Status of yellow LED controlled by main switch

void setup() {
  // Set the pin modes
  // Input pins
  pinMode(hallSensorFrontPin, INPUT);
  pinMode(hallSensorBackPin, INPUT);
  pinMode(mainSwitchPin, INPUT);
  pinMode(irSensorPin, INPUT);
  //output pins
  pinMode(whiteLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
  pinMode(yellowLedPin, OUTPUT);

  //Start serial communication
  Serial.begin(9600);             //set baud rate to standart 9600
  Serial.println("Arduino program started");
}
// void loop runs in a loop and runs all three functions after one another
void loop() {
  handleMainSwitch();   // jumps to function handelMainSwitch
  handleHallSensors();  // jumps to function handelHallSensor
  handleIRSensor();     // jumps to function handelIRSensor
  delay(200);           // Short wait time
}

void handleMainSwitch() {
  int mainSwitchState = digitalRead(mainSwitchPin);                   //sores if main switch is pressed == HIGH or not pressed == LOW
  unsigned long currentTime = millis();                               //stores the current time in milliseconds since the board was started

  // Check if the main switch is pressed for at least 500 ms and no Hall sensors are active
  if (mainSwitchState == HIGH && digitalRead(hallSensorFrontPin) == HIGH && digitalRead(hallSensorBackPin) == HIGH) {
    if (pressStartTime == 0) {
      pressStartTime = currentTime;
    } else if (currentTime - pressStartTime >= 500) {
      if (isAmbientMode) {
        // Turn off the yellow LED if main switch is pressed and lamp is in ambient mode
        yellowLedOnBySwitch = false;
        deactivateAllLEDs();
        Serial.println("Yellow LED turned off by main switch");
      } else {
        // Toggle white LED using the main switch
        whiteLedOnBySwitch = !whiteLedOnBySwitch;
        digitalWrite(whiteLedPin, whiteLedOnBySwitch ? HIGH : LOW);
        if (whiteLedOnBySwitch) {
          Serial.println("White LED turned on by main switch");
        } else {
          Serial.println("White LED turned off by main switch");
        }
      }
      pressStartTime = 0;
      delay(300); // Debounce
    }
  } else {
    pressStartTime = 0;
  }
}

void handleHallSensors() {
  // Front Hall sensor controls the white LED
  if (digitalRead(hallSensorFrontPin) == LOW) {
    deactivateAllLEDs();
    digitalWrite(whiteLedPin, HIGH);
    isAmbientMode = false;
    whiteLedOnBySwitch = false;
    Serial.println("Front Hall sensor activated - White LED on");
  } else if (!isAmbientMode && !whiteLedOnBySwitch) {
    digitalWrite(whiteLedPin, LOW);
    Serial.println("Front Hall sensor not activated - White LED off");
  }

  // Rear Hall sensor controls the red LED
  if (digitalRead(hallSensorBackPin) == LOW) {
    deactivateAllLEDs();
    digitalWrite(redLedPin, HIGH);
    isAmbientMode = false;
    Serial.println("Rear Hall sensor activated - Red LED on");
  } else {
    digitalWrite(redLedPin, LOW);
    Serial.println("Rear Hall sensor not activated - Red LED off");
  }
}

void handleIRSensor() {
  if (digitalRead(irSensorPin) == LOW && whiteLedOnBySwitch) {
    delay(500); // Wait time of 500 ms
    if (digitalRead(irSensorPin) == LOW) {
      digitalWrite(whiteLedPin, LOW);
      digitalWrite(yellowLedPin, HIGH);
      isAmbientMode = true;
      whiteLedOnBySwitch = false;
      Serial.println("IR sensor activated - Yellow LED on (Ambient Mode)");
    }
  }
}

void deactivateAllLEDs() {
  digitalWrite(whiteLedPin, LOW);
  digitalWrite(yellowLedPin, LOW);
  digitalWrite(redLedPin, LOW);
  isAmbientMode = false;
  whiteLedOnBySwitch = false;
  //Serial.println("All LEDs turned off");
}

I am planing to manufacture this circuit during the 8. Electronics Production week!

C Code Basics

source: Arduino Coding Guide
Most of the code that I have written so far is in the Arduino programming language, which is based on C/C++ but designed to be simpler and easier to learn. (library support, built-in assumptions about the target environment, ...)

There is a lot of documentation about the Arduino C flavour on the web, so I just used the existing documentation from EG1004 Lab Manual. Sparkfun

And I had an Arduino book at home that I used as well called "Das Franzis Arduino Lernpaket Das Handbuch" (German)

But here are some of my personal notes:

Data types

signed - variable allows positive and negative numbers unsigned - variable allows only positive numbers

Data Type Description
boolean (8 bit) Simple logical true/false
byte (8 bit) Unsigned number from 0–255
char (8 bit) Signed number from -128 to 127. May yield unexpected results when interpreted as a character
unsigned char (8 bit) Same as 'byte'; use 'byte' instead for clarity
word (16 bit) Unsigned number from 0–65535
unsigned int (16 bit) Same as 'word'. Use 'word' instead for clarity and brevity
int (16 bit) Signed number from -32,768 to 32,767. Commonly used in Arduino example code
unsigned long (32 bit) Unsigned number from 0–4,294,967,295. Often used to store results of millis() function
long (32 bit) Signed number from -2,147,483,648 to 2,147,483,647
float (32 bit) Signed number from -3.4028235E38 to 3.4028235E38. Not native; compiler works hard to support it
Function What it does
pinMode(pin, mode) Sets a pin as an input or output
digitalWrite(pin, value) Sets a digital output pin to HIGH or LOW
digitalRead(pin) Reads a digital input pin as HIGH or LOW
analogWrite(pin, value) Sets an analog output pin to a value 0–1023
analogRead(pin) Reads an analog output pin as a value 0–1023
delay(milliseconds) Pauses the program for a certain amount of time
Serial.begin(value) Begins the Serial Monitor with a baud rate of value
Serial.print(value) Prints the value (variable) to the Serial Monitor

const assigns a name to a constant

Learnings form this Week

© 2025 Richard Draxler – Creative Commons Attribution Non Commercial
Source code hosted at gitlab.fabcloud.org