✦ VidyaVerseOpen interactive version

← Programming Concepts in Mechanical Engineering (25ME34I)

Suggested Tutorial Activities (Mini Projects)

Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III

Read with diagrams, search and self-test

B.1 Activity 1 – Plot the stress-strain curve from tensile test data

Data from a tensile test on a mild-steel specimen (gauge length 50 mm, diameter 10 mm) are stored as load (kN) and extension (mm). The program converts them to engineering stress and strain, estimates Young's modulus from the linear region, finds the yield and ultimate stresses and percentage elongation, and plots the curve.

# Activity 1: Stress-strain curve from tensile test data
import math
import matplotlib.pyplot as plt
L0, d0 = 50.0, 10.0
A0 = math.pi * d0 ** 2 / 4                       # mm^2
load_kN = [0, 5, 10, 15, 20, 21.5, 21.0, 21.6, 23, 25, 27,
           28.5, 29.2, 29.4, 28.8, 27.5, 25.0]
ext_mm = [0, 0.016, 0.032, 0.048, 0.064, 0.075, 0.30, 0.60, 1.2,
          2.2, 3.6, 5.2, 7.0, 8.6, 10.2, 11.4, 12.2]
stress = [P * 1000 / A0 for P in load_kN]        # N/mm^2
strain = [e / L0 for e in ext_mm]
E = (stress[4] - stress[1]) / (strain[4] - strain[1])
sy = stress[5]; su = max(stress)
elong = ext_mm[-1] / L0 * 100
print(f"Area = {A0:.2f} mm^2")
print(f"Young's modulus E = {E/1000:.1f} GPa")
print(f"Yield stress = {sy:.1f} N/mm^2, UTS = {su:.1f} N/mm^2")
print(f"Breaking stress = {stress[-1]:.1f} N/mm^2, "
      f"% elongation = {elong:.1f} %")
fig, ax = plt.subplots(figsize=(6.5, 3.6))
ax.plot(strain, stress, "o-", color="navy", ms=3)
ax.annotate("Upper yield", (strain[5], sy), (0.03, sy - 60),
            arrowprops=dict(arrowstyle="->"), fontsize=8)
iu = stress.index(su)
ax.annotate("UTS", (strain[iu], su), (strain[iu] - 0.05, su + 15),
            arrowprops=dict(arrowstyle="->"), fontsize=8)
ax.annotate("Fracture", (strain[-1], stress[-1]),
            (strain[-1] - 0.06, stress[-1] - 60),
            arrowprops=dict(arrowstyle="->"), fontsize=8)
ax.set_xlabel("Engineering strain"); ax.set_ylabel("Stress (N/mm²)")
ax.set_title("Stress-strain curve: mild steel"); ax.grid(alpha=.3)
plt.tight_layout(); plt.show()
OUTPUT
Area = 78.54 mm^2
Young's modulus E = 198.9 GPa
Yield stress = 273.7 N/mm^2, UTS = 374.3 N/mm^2
Breaking stress = 318.3 N/mm^2, % elongation = 24.4 %

The data can equally be read from a CSV file exported by a universal testing machine (Chapter 6).

B.2 Activity 2 – Obstacle-avoiding robot with ultrasonic sensor

Hardware, block diagram, algorithm and program are given in Section 9.7 (Program 9.7). Suggested extensions: (i) turn towards the side with more free space by mounting the sensor on a servo and measuring left and right distances; (ii) add a buzzer when an obstacle is near; (iii) log distance readings to a CSV file for analysis.

B.3 Activity 3 – Real-time monitoring of motor speed

Principle: a slotted disc (or a magnet) on the motor shaft passes through an IR slot sensor (or Hall sensor) connected to GPIO16. Each slot produces one pulse. If the disc has PPR (pulses per revolution) slots and n pulses are counted in time Δt seconds:

Speed N (rpm) = (n / PPR) × (60 / Δt)

# Activity 3: Real-time motor speed measurement
from gpiozero import DigitalInputDevice, Motor
import time
PPR = 20                                  # slots on the disc
sensor = DigitalInputDevice(16, pull_up=True)
motor = Motor(forward=23, backward=24, enable=18)
pulses = 0
def count():
    global pulses
    pulses += 1
sensor.when_activated = count
motor.forward(0.6)
try:
    while True:
        pulses = 0
        time.sleep(1.0)                   # gate time 1 s
        rpm = pulses / PPR * 60
        print(f"Speed = {rpm:6.1f} rpm")
except KeyboardInterrupt:
    motor.stop()
OUTPUT
Speed =  942.0 rpm
Speed =  945.0 rpm
Speed =  939.0 rpm

The behaviour can be studied without hardware by simulating the motor's first-order speed response to PWM steps and plotting it:

# Simulated speed response of a DC motor to PWM duty changes
import matplotlib.pyplot as plt
import random
dt, tau, Nmax = 0.05, 0.4, 1500   # s, time constant, rpm at 100 %
t, N, duty = 0, 0.0, 0
T, S, D = [], [], []
while t < 6:
    duty = 40 if t < 2 else (80 if t < 4 else 60)
    target = Nmax * duty / 100
    N += (target - N) * dt / tau        # first-order lag
    T.append(t); S.append(N + random.uniform(-8, 8)); D.append(duty)
    t += dt
print(f"Steady speeds approx: {S[39]:.0f}, {S[79]:.0f}, "
      f"{S[-1]:.0f} rpm")
fig, ax = plt.subplots(figsize=(6.5, 3))
ax.plot(T, S, label="Measured speed (rpm)")
ax2 = ax.twinx()
ax2.step(T, D, "r--", where="post", label="PWM duty %")
ax.set_xlabel("Time (s)"); ax.set_ylabel("Speed (rpm)")
ax2.set_ylabel("Duty cycle (%)"); ax2.set_ylim(0, 100)
ax.set_title("Motor speed monitoring"); ax.grid(alpha=.3)
plt.tight_layout(); plt.show()
OUTPUT
Steady speeds approx: 598, 1196, 900 rpm

B.4 Activity 4 – Simple smart-home automation system

Objective: control a light, a fan and a security buzzer automatically using sensors, with manual override.

DeviceGPIORule
Light (relay 1)GPIO1 7ON when PIR detects motion after dark (LDR module LOW)
Fan (relay 2)GPIO 22ON when temperature ≥ 30 °C (DHT11 on GPIO4)
BuzzerGPIO 26ON if motion is detected in "away" mode
PIR sensorGPIO 27Motion input
LDR module (digital out)GPIO 25Dark = 1
Mode switchGPIO 2Pressed = away mode
# Activity 4: Smart home automation
import time, board, adafruit_dht
from gpiozero import (MotionSensor, OutputDevice, Buzzer,
                      DigitalInputDevice, Button)
light = OutputDevice(17, active_high=False)
fan = OutputDevice(22, active_high=False)
buzzer = Buzzer(26)
pir = MotionSensor(27)
dark = DigitalInputDevice(25)
away = Button(2)
dht = adafruit_dht.DHT11(board.D4)
while True:
    try:
        temp = dht.temperature
    except RuntimeError:
        temp = None
    motion = pir.motion_detected
    light.value = motion and dark.value and not away.is_pressed
    if temp is not None:
        fan.value = temp >= 30
    buzzer.value = motion and away.is_pressed
    print(f"T={temp} motion={motion} light={light.value} "
          f"fan={fan.value} alarm={buzzer.value}")
    time.sleep(2)

Extensions: send alerts to a phone using Telegram or e-mail, add a camera to capture images when the alarm triggers, and build a web dashboard with Flask.

APPENDIX C