5. Embedded programming¶
This week we tried programing micro-controller using 2 main languages namely they are, C++ and Micro-python through various applications and websites.
For more info - Visit Group Website
How to get the code?¶
Tinkercad¶
similulator for circuit extract code
Arduino (C++)¶
Online (Audrino IDE)¶
Project-Morse code
/*
Morse Code Project
This code will loop through a string of characters and convert these to morse code.
It will blink two LED lights and play audio on a speaker.
*/
//**************************************************//
// Type the String to Convert to Morse Code Here //
//**************************************************//
char stringToMorseCode[] = "Arduino Morse Code Project";
// Create variable to define the output pins
int led12 = 12; // blink an led on output 12
int led6 = 6; // blink an led on output 6
int audio8 = 8; // output audio on pin 8
int note = 1200; // music note/pitch
/*
Set the speed of your morse code
Adjust the 'dotlen' length to speed up or slow down your morse code
(all of the other lengths are based on the dotlen)
Here are the ratios code elements:
Dash length = Dot length x 3
Pause between elements = Dot length
(pause between dots and dashes within the character)
Pause between characters = Dot length x 3
Pause between words = Dot length x 7
http://www.nu-ware.com/NuCode%20Help/index.html?m...
*/
int dotLen = 100; // length of the morse code 'dot'
int dashLen = dotLen * 3; // length of the morse code 'dash'
int elemPause = dotLen; // length of the pause between elements of a character
int Spaces = dotLen * 3; // length of the spaces between characters
int wordPause = dotLen * 7; // length of the pause between words
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output for LED lights.
pinMode(led12, OUTPUT);
pinMode(led6, OUTPUT);
}
// Create a loop of the letters/words you want to output in morse code (defined in string at top of code)
void loop()
{
// Loop through the string and get each character one at a time until the end is reached
for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++)
{
// Get the character in the current position
char tmpChar = stringToMorseCode[i];
// Set the case to lower case
tmpChar = toLowerCase(tmpChar);
// Call the subroutine to get the morse code equivalent for this character
GetChar(tmpChar);
}
// At the end of the string long pause before looping and starting again
LightsOff(8000);
}
// DOT
void MorseDot()
{
digitalWrite(led12, HIGH); // turn the LED on
digitalWrite(led6, HIGH);
tone(audio8, note, dotLen); // start playing a tone
delay(dotLen); // hold in this position
}
// DASH
void MorseDash()
{
digitalWrite(led12, HIGH); // turn the LED on
digitalWrite(led6, HIGH);
tone(audio8, note, dashLen); // start playing a tone
delay(dashLen); // hold in this position
}
// Turn Off
void LightsOff(int delayTime)
{
digitalWrite(led12, LOW); // turn the LED off
digitalWrite(led6, LOW);
noTone(audio8); // stop playing a tone
delay(delayTime); // hold in this position
}
// *** Characters to Morse Code Conversion *** //
void GetChar(char tmpChar)
{
// Take the passed character and use a switch case to find the morse code for that character
switch (tmpChar) {
case 'a':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'b':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'c':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'd':
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'e':
MorseDot();
LightsOff(elemPause);
break;
case 'f':
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'g':
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'h':
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'i':
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'j':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'k':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'l':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'm':
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'n':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'o':
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'p':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 'q':
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'r':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 's':
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
case 't':
MorseDash();
LightsOff(elemPause);
break;
case 'u':
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'v':
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'w':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'x':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'y':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'z':
MorseDash();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;
default:
// If a matching character was not found it will default to a blank space
LightsOff(Spaces);
}
}
/*
Unlicensed Software:
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to
*/
Blink built-in¶
Blink Random¶
Fade built-in Example¶
Fade Edited¶
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(LED_BUILTIN, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
Morse-Code ‘SUIII’¶
Higher number to see the to detect result easily and check if the code is working as desired.
I noticed that the code from the app itself there is an error regarding the High (ON) and Low (OFF) were in experimentation is the opposite High (OFF) and Low (ON).
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
// '.' = 1000
// '-' = 2000
//GAP BETWEEN '.' & '-' = 500
// WORD: SUIII
void loop() {
// S '. . .'
// GAP AFTER FULL WORD '5 SECOND'
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
delay(5000); // 5 SECONDS
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
delay(500); // wait for 0.5 second
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for 0.5 second
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
// GAP '3 SECOND'
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(3000); // 3 SECONDS
// U '. . -'
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a 0.5 second
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(2000); // '-' 2 SECOND
// GAP '3 SECOND'
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
delay(3000); // 3 SECONDS
// I '. .'
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
delay(500); // wait for a 0.5 second
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
// GAP '3 SECOND'
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
delay(3000); // 3 SECONDS
// I '. .'
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
delay(500); // wait for a 0.5 second
digitalWrite(LED_BUILTIN, LOW); // turn the LED on (HIGH is the voltage level)
delay(1000); // '.' 1 SECOND
// GAP '3 SECOND'
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
delay(3000); // 3 SECONDS
// I '. .'
digitalWrite(LED_BUILTIN, LOW); // LED ON
delay(1000); // '.' 1 SECOND
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
delay(500); // wait for a 0.5 second
digitalWrite(LED_BUILTIN, LOW); // turn the LED on (HIGH is the voltage level)
delay(1000); // '.' 1 SECOND
}
Morse-code Translator¶
#include <string.h>
int dotLen = 1000;
int dashLen = dotLen * 3;
int elemPause = dotLen;
int Spaces = dotLen * 3;
int wordPause = dotLen * 7;
const char *morseCode[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
Serial.println("Enter a word or sentence:");
}
void MorseDot()
{
digitalWrite(LED_BUILTIN, LOW); // turn the LED on
delay(dotLen); // hold in this position
}
// DASH
void MorseDash()
{
digitalWrite(LED_BUILTIN, LOW); // turn the LED on
delay(dashLen); // hold in this position
}
// Turn Off
void LightsOff(int delayTime)
{
digitalWrite(LED_BUILTIN, HIGH); // turn the LED off
delay(delayTime); // hold in this position
}
void loop()
{
String word = Serial.readString();
word.toLowerCase();
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (c == ' ') {
LightsOff(wordPause);
} else {
int index = c - 'a';
const char *code = morseCode[index];
for (int j = 0; code[j] != '\0'; j++) {
if (code[j] == '.') {
MorseDot();
} else {
MorseDash();
}
LightsOff(elemPause);
}
LightsOff(Spaces);
}
}
LightsOff(wordPause);
}
Using AI tool (Gemini)¶
Translate from C++ to Micropython
Example morse-code conversion
Thooney (Micro-python)¶
Check code from internet
Set Up¶
Red is the Analog ( 3 ‘io26’) therefore 26 is the pin number led = machine.Pin(26,Pin.OUT)
Blink¶
import machine
import time
import random
led = machine.Pin(26, machine.Pin.OUT) # Setup the LED pin as output
while True:
led.value(1)
time.sleep(1) # 1 second ON LED
led.value(0)
time.sleep(3) # 1 second OFF LED
Blink Random¶
import machine
import time
import random
led = machine.Pin(26, machine.Pin.OUT) # Setup the LED pin as output
while True:
led.value(1)
time.sleep(random.randrange(0,5)) # Random ON LED
led.value(0)
time.sleep(random.randrange(0,5)) # Random OFF LED
Fade Code¶
from machine import Pin, PWM
from time import sleep
pwm = PWM(Pin(26))
pwm.freq(1000) # Control frequency
x = 20535 # get current duty cycle, range 0-65535
sm = 0.00001 # smoothining factor
while True:
for duty in range(x): # get current duty cycle, range 0-65535
pwm.duty_u16(duty)
sleep(sm) # smoothining factor
for duty in range(x, 0, -1): # get current duty cycle, range 0-65535
pwm.duty_u16(duty)
sleep(sm) # smoothining factor
Morse Code ‘SUIII’¶
import machine
import time
# Pin number for the LED
led_pin = 26 # Replace with your actual pin number
# Setup the LED pin as output
led = machine.Pin(led_pin, machine.Pin.OUT)
def blink(duration, gap):
led.value(1) # Turn LED OFF
time.sleep(duration)
led.value(0) # Turn LED ON
time.sleep(gap)
def loop():
# S '. . .'
blink(1, 0.5)
blink(1, 0.5)
blink(1, 0.5)
# 5-second gap
time.sleep(5)
# U '. . -'
blink(1, 0.5)
blink(1, 0.5)
blink(2, 0.5)
# 3-second gap
time.sleep(3)
# I '. .'
blink(1, 0.5)
blink(1, 0.5)
# 3-second gap
time.sleep(3)
# I '. .'
blink(1, 0.5)
blink(1, 0.5)
# 3-second gap
time.sleep(3)
# I '. .'
blink(1, 0.5)
blink(1, 0.5)
while True:
loop()
Morse Code Translator¶
import machine
import time
# Pin number for the LED
led_pin = 26 # Replace with your actual pin number
# Morse code mapping
morse_code = {
'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....',
'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.',
'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-',
'y': '-.--', 'z': '--..'
}
# Set up the LED pin
led = machine.Pin(led_pin, machine.Pin.OUT)
# Morse code functions
def dot():
led.value(1) # Turn LED off
time.sleep_ms(1000) # Adjust duration as needed
led.value(0) # Turn LED on
def dash():
led.value(1) # Turn LED off
time.sleep_ms(3000) # Adjust duration as needed
led.value(0) # Turn LED on
def pause(ms):
time.sleep_ms(ms)
def main():
while True:
word = input("Enter a word or sentence: ")
word = word.lower()
for char in word:
if char == ' ':
pause(7000) # Adjust word space as needed
else:
code = morse_code[char]
for symbol in code:
if symbol == '.':
dot()
else:
dash()
pause(1000) # Adjust element space as needed
pause(3000) # Adjust letter space as needed
if __name__ == "__main__":
main()
C++ and Python for Microcontroller Control: A Comparison¶
C++ and Python are both powerful programming languages, each with its own strengths and weaknesses when it comes to microcontroller control. Here’s a brief comparison:
C++¶
Pros:¶
High Performance: C++ code compiles directly into machine code, resulting in highly efficient and fast execution.
Low-Level Control: It provides direct access to hardware registers and memory, allowing for fine-grained control over microcontroller operations.
Widely Used: C++ is a well-established language with a large community and extensive libraries for microcontroller development.
Cons:¶
Steep Learning Curve: C++ has a complex syntax and requires a deep understanding of memory management and pointers.
Verbose Syntax: C++ code can be more verbose and less readable than Python.
Python¶
Pros:¶
Readability: Python’s syntax is concise and easy to learn, making it a great choice for beginners.
Rapid Prototyping: Python’s interpreted nature allows for quick development and testing of code.
High-Level Abstraction: Python provides a high-level abstraction of hardware, making it easier to work with complex devices.
Cons:¶
Performance Overhead: Python code is typically slower than C++ due to the overhead of the interpreter.
Limited Low-Level Control: Python doesn’t provide the same level of low-level control as C++.
Choosing the Right Language
The best language for your project depends on several factors:¶
Performance Requirements: If performance is critical, C++ is the better choice.
Development Time: If rapid prototyping is important, Python is a good option.
Hardware Complexity: For complex hardware interactions, C++ might be more suitable.
Developer Experience: If you’re comfortable with C++ and have experience with microcontroller programming, C++ is a good choice. If you’re new to programming or prefer a more high-level language, Python is a good option. Bridging the Gap: MicroPython
MicroPython¶
Python implementation designed specifically for microcontrollers. It provides a Python-like interface to hardware, making it easier to control microcontrollers with Python. However, it may have performance limitations compared to C++.
My Openion¶
Both C++ and Python can be effective for microcontroller control, each with its own strengths and weaknesses. The best language for your project will depend on your specific needs and preferences. By understanding the trade-offs between the two languages, you can make an informed decision.