BTE1522 DRE2213 – Week 3 – Control Statements and Functions

Let’s explore learning programming by troubleshooting Codes   😀  – Flags and Scoring Systems in Python

Today’s coding session was all about debugging and enhancing a game we’ve been developing step by step. We dove into Act 4, 5, 6 and 7, focusing on how to fix some key issues in the game logic—specifically how to properly handle scoring during collisions between the player and enemies.

PBL – ‘The Problem’

We already had a working player and enemy system in the game. The player can move left and right, while an enemy drops down from the top of the screen. The challenge was ensuring the player’s score only increased by one upon a collision with the enemy. Instead, the score was skyrocketing with every game frame where the player touched the enemy, adding several points instead of just one.

This type of issue is common when developing games, where collisions can occur over multiple frames. But we only want the score to increment once per collision event. To fix this, we introduced an important concept: the flag.

Introducing Flags in Python

In programming, a flag is a boolean variable (True/False) used to indicate whether a certain condition has been met. For our game, we needed a flag to signal whether a collision between the player and enemy had already occurred. This would prevent the score from increasing continuously while the player and enemy rectangles overlap.

Using a Flag to Control Scoring

Here’s how we used the flag –

  1. Define the flag – We introduced a variable collision_occurred, which is initially set to False. This flag keeps track of whether the collision has already happened.
  2. Check the flag during collision – Every time the game checks for a collision between the player and the enemy, it also checks whether collision_occurred is True or False.
    1. If it’s False and a collision happens, the score increments by 1, and the flag is set to True. This prevents further increments until the enemy resets.
    2. If the flag is True, no further points are added, even if the player remains in contact with the enemy.
  3. Reset the flag – Once the enemy moves off-screen and reappears at the top, the flag is reset to False, allowing for another score increment during the next collision.

p/s Score Board is being implemented this year. One of the ways to monitor students progress in class

BTE1522

DRE2213

BTE1522 DRE2213 – Week 2 – Data Types and Control Statements

In Week 2 of the BTE1522 DRE2213 course, the focus was on fundamental programming concepts, specifically data types and control statements in Python. These are critical building blocks for developing logical structures within any programming language and are key to enabling students to design functional applications.

  1. Data Types in Python
    Understanding the various data types is essential in programming. Python offers several data types that students learned to apply during the class –

    • Integers (int): Whole numbers, like 1, 2, or 100.
    • Floating-point numbers (float): Numbers with decimal points, like 3.14 or 5.0.
    • Strings (str): Text data, enclosed in quotes, like “Hello, World!”.
    • Booleans (bool): True or False values, used for conditional logic.
    • Lists and Tuples: Students were introduced to lists, which are mutable sequences, and tuples, which are immutable sequences, to store multiple values.
  2. Control Statements in Python
    Control flow structures help in decision-making and looping through tasks. The students explored:

    • If, Elif, and Else Statements: Conditional statements that allow the program to execute specific blocks of code based on certain conditions.
    • While and For Loops: Used to repeat a block of code while a condition holds true.

Activity 1-3: Player Creation and Movement

Students applied their understanding of data types and control statements through practical coding exercises. In Activities 1-3, they created a basic player character and programmed its movement across the game window.

The coding exercise allowed students to implement:

  • Variables to define the player’s position, size, and color.
  • Control statements like if-elif-else to determine how the player moves in response to keyboard input.
  • Basic boundary control to prevent the player from moving off-screen.

Moving to the Second Phase – Five Challenges

After completing the initial activities, students moved to a more challenging phase involving code modifications and analysis. They were tasked with modifying and analyzing code to address five distinct challenges, each designed to deepen their understanding of data types and control statements.

Challenge 1: Modify Movement with Control Statements

Objective – Students were introduced to control statements such as if, elif, and else. They modified the code to allow the player to move based on specific conditions, such as different key presses resulting in different player actions.

Challenge 2: Boundary Control with Conditional Statements

Objective – In this challenge, students explored boundary detection using if and else statements. The goal was to prevent the player from moving outside the game window. This reinforced their understanding of how conditions can control flow in a program.

Challenge 3: Change Player’s Color with Data Types

Objective – Students were introduced to the concept of variables and data types such as lists and tuples. The challenge was to change the player’s color based on certain conditions, like the player reaching specific coordinates.

Challenge 4: Score and Time Tracking with Variables

Objective – Students explored the use of variables and loops to add a scoring system and time limit. They learned how to create a variable that increments when the player performs specific actions and how to manage game time using a while loop.

Challenge 5: Advanced Activity: Collision Detection

Objective – The final challenge involved practicing control structures and Boolean data types to detect when the player collided with the screen edges. This challenge required students to think critically about game dynamics and how to implement collision logic.

Pedagogical Approaches in the Exercise

To ensure a thorough understanding, two pedagogical approaches were used throughout the five challenges:

  1. Code Modification/Generation
    Students in DRE2213 were required to actively modify their existing code based on the challenge descriptions. This hands-on approach allowed them to understand the logic behind each task and improve their problem-solving skills by directly interacting with the code.
  2. Code Analysis
    In BTE1522, students were provided with completed code and asked to map it to the challenge objectives. This method allowed them to break down complex code structures, understand how different components work together, and link theoretical concepts to real-world applications.

Week 2 was an essential part of the course as it introduced fundamental programming concepts like data types and control statements in Python. Through interactive activities and challenges, students not only learned to implement these concepts but also developed problem-solving skills by engaging in code modification and analysis. These exercises laid a strong foundation for the more advanced topics to come in the course.

Nurul Oct 15th

DRE2213   

 

BTE1522

Artificial Intelligence – Python Programming – Train the Trainers Workshop

A 4-days workshop crafted for academicians from Polytechnics Malaysia.

I recently conducted a comprehensive 4-day workshop to introduce participants (among academicians from Polytechnics in Malaysia) to both fundamental and advanced topics, offering hands-on activities that showcased the powerful applications of AI, electronics, and programming.

Thank you Pn Azlyn for coordinating the communication and facilitating the process :).

Below is a summary of the activities we conducted over the course of this workshop.

Day 1  Foundations of AI, Python, and Raspberry Pi
The workshop kicked off with an introduction to AI and the Raspberry Pi microprocessor. We started with a fun ice-breaker activity, Introduction BINGO, where participants got to know each other. Afterward, we delved into the fundamental concepts of hardware and electronic components, ensuring everyone was comfortable with the physical aspects of working with a Raspberry Pi.

Key Topics Covered –

  1. Hardware & Electronic Components – Understanding the basics of the Raspberry Pi, GPIO pins, and essential sensors.
  2. Raspberry Pi Microprocessor – Overview of how Raspberry Pi works and its applications in AI.
    This foundational day set the stage for the deeper dives into programming and hardware control that were to follow.

Day 2 Control Statements, Communication, and Sensors

We began Day 2 by introducing participants to Python control statements, providing the backbone for controlling the hardware components with Python scripts. This session included practical activities focused on various communication protocols like I2C and SPI, commonly used for sensor integration.

Key Activities and Topics –

  1. Python Control Statement – Introducing loops, conditions, and their use in hardware control.
  2. Communication Protocols – Learning how Raspberry Pi communicates with sensors using I2C and SPI.

Hands-on Activities –

  1. Act 1, 2 – LED ON and OFF Control – Participants learned to turn LEDs on and off using Python.
  2. Act 3 – LED Blinking – Adding logic to make LEDs blink at intervals.
  3. Act 4 – Keyboard Control – Using the keyboard to interact with hardware components like LEDs.
  4. Act 5 – OLED Display -We explored controlling an OLED display using Python libraries and the I2C protocol. This included displaying text and graphics, which captivated participants, demonstrating the versatility of the Raspberry Pi as an interface device.

Day 3 Exploring Sensors and Camera Controls

On Day 3, we moved into more complex sensor and camera integration. Participants worked hands-on with various sensors to collect and process real-world data.

Key Sensors Covered –

  1. Act 6 – I2C Accelerometer: Using accelerometers to measure movement and tilt.
  2. Act 7 – Ultrasonic Sensor: Measuring distances using ultrasonic waves.
    We also explored using the camera with the Raspberry Pi
  3. Act 8 – Camera / Image: Capturing still images and processing them.
  4. Act 9 – Video Streaming: Streaming live video using the Raspberry Pi camera, giving participants a look at real-time image processing.
    We ended the day by learning how to remotely control the Raspberry Pi using SSH Scripting for headless setups.
    Day 4: Advanced Camera Control and Project Development
    The final day was packed with creative development. Participants were introduced to more advanced concepts of camera control using Python and integrating this control into group projects.

Key Highlights

  1. Camera Control & Geany – Using Geany, a lightweight integrated development environment (IDE), to control cameras with custom scripts.
  2. Project Development – Each group was tasked with designing and developing a project, incorporating the skills learned over the past three days. The projects ranged from simple security systems to advanced sensor networks.
    1. Participants also learned how to set up their Raspberry Pi in Headless Mode, using SSH to control it without a dedicated monitor or keyboard.
    2. Project Presentation and Way Forward
    3. After completing their group projects, participants presented their creations, showcasing the applications of Python programming, sensors, and AI-based hardware control. The final session was a recap of the key concepts, where participants were encouraged to continue exploring AI and Raspberry Pi on their own. They also completed a Post-Test to measure their progress throughout the course.

Looking Forward
This workshop is just the beginning. The potential of Raspberry Pi combined with Python programming offers limitless possibilities, from creating AI-powered projects to building real-world applications. Participants left equipped with the skills and confidence to continue their journey in AI and embedded systems development.

Conclusion
In just four days, participants transitioned from having no experience with Raspberry Pi or Python to developing their own AI-based projects. This course laid a strong foundation for understanding hardware, software, and AI in a hands-on, engaging way. The combination of sensors, control statements, and camera-based projects showcased the immense power of integrating AI and Python with Raspberry Pi.

Stay tuned for more workshops that push the boundaries of AI and embedded programming!

I hope everyone had enjoyed the course as much as I did in facilitating it.

Nurul (Oct 3rd, 2024)

Day 4

Day 3

 

Day 2

Day 1

Misc

 

 

BTE1522 – Week 14 Project Assessment – Integrating Gallery Walk and Reciprocal Teaching

 

In today’s class – BTE 1522 – Innovation Python Programming and Raspberry Pi, we engaged in a dynamic and interactive learning session that combined elements of Gallery Walk and Reciprocal Teaching. This approach not only fostered collaboration and deeper understanding but also enhanced students’ ability to explain and defend their projects. Here’s a breakdown of how the session unfolded and the learning theories behind it.

Activity Overview
1 – Project Development

Students were divided into groups (1 through 5).
Each group developed a project using on Raspberry Pi, integrating sensors like BME280 & cameras, building databases, and creating dashboards.

2 – Reciprocal Teaching with a Twist

Instead of presenting their own work, each group was tasked with presenting the project of another group. For example, Group 2 (Angelina & Syarah) presented the work done by Group 1 (Amir, Azhad, Aiman).

This approach required students to thoroughly understand projects created by other groups. By presenting and understanding projects from other groups, students applied their Python coding knowledge to analyze and interpret how different groups implemented solutions using Raspberry Pi. This hands-on experience allowed them to see real-world applications of Python in sensor integration, data handling, and project implementation on the Raspberry Pi platform. It reinforced their learning by showing them diverse approaches to coding, problem-solving, and integrating hardware components like sensors, cameras, and GPS modules into functional systems.

3 – Gallery Walk Elements

After Group 1 presents their project on the Environmental Monitoring and Imaging System, the session transitions into an interactive phase. Students from Groups 3, 4, 5, and 6 ask one question each about the presented project. These questions delve into various aspects of the system, such as the integration of sensors like the BME280 for environmental data collection, the methodologies employed in Python programming to process and visualize this data, and the techniques utilized for imaging purposes.

This structured Q&A session serves multiple purposes. First, it allows students from other groups to gain deeper insights into the technical details and methodologies employed by Group 1. By asking pertinent questions, students from Groups 3, 4, 5, and 6 not only expand their understanding of different project components but also evaluate the comprehensiveness and innovation of Group 1’s work.

For Group 1, this session becomes an opportunity to demonstrate their expertise and depth of knowledge regarding their project. By articulating clear and detailed responses to the questions posed by their peers, Group 1 showcases their understanding of Python programming techniques applied to sensor integration, data processing, and system implementation. They also highlight their proficiency in problem-solving and innovation within the context of environmental monitoring and imaging systems.

This approach fosters a collaborative learning environment where students engage critically with each other’s work, exchange ideas, and enhance their technical and communication skills. It aligns with the assignment topics by emphasizing the application of Python programming in real-world IoT (Internet of Things) projects involving environmental monitoring, precision agriculture, GPS tracking, and photography with weather data integration.

Evaluation Criteria

  1. Marks were awarded based on the quality of the presentation by the presenting group.
  2. The ability of Group 1 to answer the questions accurately and comprehensively.
  3. The ability of the presenting group to explain another group’s project clearly.
  4. Learning Theories and Techniques

Reciprocal Teaching

By having students present projects they did not create, we leveraged the principles of reciprocal teaching. This method encourages active learning, critical thinking, and the ability to teach others, which in turn reinforces their own understanding.

Gallery Walk

Incorporating a Q&A session akin to a gallery walk allowed students to engage with multiple projects, ask insightful questions, and provide constructive feedback. This technique promotes active engagement, observational learning, and peer-to-peer interaction.

Peer Teaching

This hybrid approach facilitated peer teaching, where students learned from each other by presenting and questioning different projects. Peer teaching is known to enhance comprehension and retention of material as students explain concepts to their peers.

Collaborative Learning

Working in groups to understand and present different projects encouraged collaboration. Collaborative learning helps develop teamwork skills, enhances problem-solving abilities, and fosters a sense of community within the class.

 

 

 

 

Benefits of the Approach

  1. Improved Understanding – Students gained a broader perspective by engaging with multiple projects, understanding various approaches and solutions.
  2. Enhanced Communication Skills – Presenting another group’s work and answering questions honed students’ communication and presentation skills.
  3. Critical Thinking – The Q&A session encouraged critical thinking, as students had to think on their feet to ask relevant questions and provide accurate answers.
  4. Engagement and Motivation – This interactive approach kept students engaged and motivated, as they were actively involved in learning and teaching processes.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

To all the BTE1522 students (Sem 1 2024 2025), thank you very much for your active participation throughout the semester. I hope you’ve enjoyed the classes as much as I do =).

Nurul – June 16th 2024

BTE 1522 – Programming and Data Structure – Project Preparation

Today’s BTE 1522 class was an exciting dive into the world of GPS technology and its integration with Raspberry Pi. We explored the essential concepts, from importing relevant Python modules for GPS functionality to circuit construction and function coding. This session is a crucial part of our project development series, providing students with hands-on experience in incorporating GPS modules into their Raspberry Pi projects.

Understanding GPS and Its Importance

Global Positioning System (GPS) is a satellite-based navigation system that provides geolocation and time information to a GPS receiver anywhere on or near the Earth. Integrating GPS into Raspberry Pi projects opens up numerous possibilities, such as tracking, navigation, and location-based services, which are pivotal in various applications like autonomous vehicles, drones, and IoT devices.

Circuit Construction for GPS Integration

Components Needed:

  1. Raspberry Pi
  2. GPS Module (e.g., NEO-6M)
  3. Connecting Wires
  4. Breadboard (optional)

Steps:

  1. Connecting the GPS Module:

    • UART Communication: Connect the GPS module’s TX (transmit) pin to the Raspberry Pi’s RX (receive) pin and the GPS module’s RX pin to the Raspberry Pi’s TX pin. Additionally, connect the VCC pin to the 3.3V or 5V power supply (depending on your GPS module specifications) and the GND pin to the ground.
    • I2C Communication: If your GPS module supports I2C, connect the SDA (data) and SCL (clock) pins of the GPS module to the corresponding pins on the Raspberry Pi. Ensure the VCC and GND pins are also properly connected.
  2. Powering Up: Power on the Raspberry Pi and ensure all connections are secure.

Coding for GPS Integration

Python Modules:

  • gpsd: A popular library for interfacing with GPS modules.
  • serial: A library for handling serial communication.

UART Communication:

  1. Installing Libraries:

    sudo apt-get install gpsd gpsd-clients python-gps
  2. Python Code Example:

    python
     
    import gpsd # Connect to the local gpsd
    gpsd.connect() # Get GPS data
    def get_gps_data():
    packet = gpsd.get_current()
    latitude = packet.lat
    longitude = packet.lon
    time = packet.time return latitude, longitude, time # Print GPS data lat, lon,
    timestamp = get_gps_data() print(f"Latitude: {lat}, Longitude: {lon}, Time: {timestamp}")
     

I2C Communication:

  1. Enabling I2C:

    sudo raspi-config

    Navigate to ‘Interfacing Options’ and enable I2C.

  2. Python Code Example:

    python
     
    import smbus2 import time bus = smbus2.SMBus(1) address = 0x42 # Replace with your GPS module's I2C address
    def read_gps(): data = bus.read_i2c_block_data(address, 0, 16) return data while True:
    gps_data = read_gps()
    print(gps_data) time.sleep(1)

Communication Protocols

UART (Universal Asynchronous Receiver-Transmitter):

  • Pros: Simple to use, widely supported.
  • Cons: Limited to point-to-point communication.

I2C (Inter-Integrated Circuit):

  • Pros: Supports multiple devices on the same bus, more flexible.
  • Cons: More complex than UART, requires addressing.

Key Learning Outcomes

  • Circuit Construction: Students learned how to set up a GPS module with Raspberry Pi, ensuring correct connections for power, ground, and communication lines.
  • Coding Techniques: We explored Python coding for both UART and I2C communication protocols, highlighting the differences and use cases for each.
  • Real-Time Data Acquisition: Students gained practical skills in capturing and processing GPS data, which can be applied to various projects requiring geolocation capabilities.

Integrating GPS functionality into Raspberry Pi projects offers a robust foundation for creating advanced IoT applications and location-based services. Today’s class provided a comprehensive understanding of the hardware setup and coding techniques necessary to harness GPS data effectively. As we move forward, these skills will be crucial for the final project development phase, enabling students to implement sophisticated and innovative solutions.

 

 

 

 

BTE1522 Innovation – Week 12 – SSH and Data Visualisation

Today we explored SSH (Secure Shell) and data visualization using the Raspberry Pi platform. This is the final session before students embark on their final projects, providing them with essential skills in remote control and data acquisition.

SSH Connection with Raspberry Pi – We began by establishing an SSH connection to our Raspberry Pi using Putty, a widely-used SSH client. Through SSH, students learned how to remotely control their Raspberry Pi from their local machines, enabling seamless interaction with the Pi’s command-line interface. Navigational commands such as cd, ls, pwd, and mkdir were explored, empowering students to navigate the file system, create directories, and manage files effortlessly.

Data Visualization with Adafruit and BME280 -The session also featured a demonstration of data visualization using the Adafruit platform and the BME280 sensor. Students gained hands-on experience in acquiring environmental data such as temperature, humidity, and pressure using the BME280 sensor, a vital component for IoT (Internet of Things) applications. By visualizing this data, students could better understand real-world applications of sensor data and its significance in various projects.

Remote Python Program Execution -A key highlight of today’s activities was the execution of Python programs remotely via SSH. Students learned how to run Python scripts on their Raspberry Pi from their local machines, enabling them to execute code, perform data analysis, and control hardware components without direct physical access to the Pi. Commands such as nano for text editing and cat for displaying file contents further enriched their understanding of remote file management.

Exploring System Information:
To wrap up the session, we delved into exploring system information commands such as uname -a, df -h, and free -h. These commands provided insights into system specifications, disk space usage, and memory utilization, essential for monitoring and optimizing Raspberry Pi performance.

I look forward to the upcoming project phase, I am confident you  are well-prepared to could apply their this knowledge and skills in developing innovative Raspberry Pi-based solutions.

Nurul

May 24th