3.1 Elektr Asoslari â Amaliyot
Laboratoriya ishi: Python simulyatsiya va Arduino amaliyot
1. Ohm Qonuni Simulyatsiyasiâ
import numpy as np
import matplotlib.pyplot as plt
def ohms_law_demo():
"""Ohm qonuni vizualizatsiya"""
# Turli qarshiliklar
R_values = [10, 50, 100, 200, 500] # Ohm
V = np.linspace(0, 12, 100) # Volt
plt.figure(figsize=(12, 5))
# V-I karakteristika
plt.subplot(1, 2, 1)
for R in R_values:
I = V / R * 1000 # mA
plt.plot(V, I, linewidth=2, label=f'R={R}ÎĐ')
plt.xlabel('Kuchlanish (V)')
plt.ylabel('Tok (mA)')
plt.title('V-I Karakteristika (Ohm Qonuni)')
plt.legend()
plt.grid(True)
# Quvvat
plt.subplot(1, 2, 2)
R = 100 # ÎĐ
I = V / R
P = V * I # Watt
plt.plot(V, P, 'r-', linewidth=2)
plt.fill_between(V, 0, P, alpha=0.3)
plt.xlabel('Kuchlanish (V)')
plt.ylabel('Quvvat (W)')
plt.title(f'Quvvat (R={R}ÎĐ)')
plt.grid(True)
plt.tight_layout()
plt.savefig('ohms_law.png', dpi=150)
plt.show()
ohms_law_demo()
2. RC Zanjir Simulyatsiyasiâ
import numpy as np
import matplotlib.pyplot as plt
def rc_circuit_simulation():
"""RC zanjir zaryadlanish/razryadlanish"""
R = 10000 # 10k Ohm
C = 100e-6 # 100 uF
tau = R * C # 1 s
V_source = 5 # V
dt = 0.01
t_max = 5 * tau
t = np.arange(0, t_max, dt)
# Zaryadlanish
V_charge = V_source * (1 - np.exp(-t / tau))
I_charge = (V_source / R) * np.exp(-t / tau)
# Razryadlanish (t=2.5 dan keyin)
t_discharge = t[t >= 2.5*tau] - 2.5*tau
V_discharge = V_source * np.exp(-t_discharge / tau)
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Zaryadlanish - kuchlanish
axes[0, 0].plot(t, V_charge, 'b-', linewidth=2)
axes[0, 0].axhline(y=V_source*0.632, color='r', linestyle='--', alpha=0.7)
axes[0, 0].axvline(x=tau, color='r', linestyle='--', alpha=0.7)
axes[0, 0].annotate(f'Ï = {tau:.2f}s', xy=(tau, V_source*0.632),
xytext=(tau+0.5, V_source*0.5))
axes[0, 0].set_xlabel('Vaqt (s)')
axes[0, 0].set_ylabel('Kuchlanish (V)')
axes[0, 0].set_title('RC Zaryadlanish')
axes[0, 0].grid(True)
# Zaryadlanish - tok
axes[0, 1].plot(t, I_charge * 1000, 'g-', linewidth=2)
axes[0, 1].set_xlabel('Vaqt (s)')
axes[0, 1].set_ylabel('Tok (mA)')
axes[0, 1].set_title('Zaryadlanish Toki')
axes[0, 1].grid(True)
# Razryadlanish
axes[1, 0].plot(t_discharge, V_discharge, 'r-', linewidth=2)
axes[1, 0].axhline(y=V_source*0.368, color='b', linestyle='--', alpha=0.7)
axes[1, 0].set_xlabel('Vaqt (s)')
axes[1, 0].set_ylabel('Kuchlanish (V)')
axes[1, 0].set_title('RC Razryadlanish')
axes[1, 0].grid(True)
# Energiya
E = 0.5 * C * V_charge**2 * 1000 # mJ
axes[1, 1].plot(t, E, 'm-', linewidth=2)
axes[1, 1].set_xlabel('Vaqt (s)')
axes[1, 1].set_ylabel('Energiya (mJ)')
axes[1, 1].set_title('Kondensatorda Saqlangan Energiya')
axes[1, 1].grid(True)
plt.tight_layout()
plt.savefig('rc_circuit.png', dpi=150)
plt.show()
print(f"Vaqt konstantasi Ï = {tau:.2f} s")
print(f"5Ï da zaryadlanish: {(1-np.exp(-5))*100:.1f}%")
print(f"Max energiya: {0.5 * C * V_source**2 * 1000:.2f} mJ")
rc_circuit_simulation()
3. Kuchlanish Bo'lgich Kalkulyatoriâ
import numpy as np
import matplotlib.pyplot as plt
def voltage_divider_calculator():
"""Interaktiv kuchlanish bo'lgich"""
def calc_vout(vin, r1, r2):
return vin * r2 / (r1 + r2)
def calc_r2(vin, vout, r1):
return r1 * vout / (vin - vout)
# Misol: 12V dan 5V olish
Vin = 12
Vout_target = 5
R1 = 10000 # 10k
R2 = calc_r2(Vin, Vout_target, R1)
print(f"Maqsad: {Vin}V â {Vout_target}V")
print(f"R1 = {R1/1000:.1f}kÎĐ")
print(f"R2 = {R2/1000:.2f}kÎĐ (yaqin standart: {round(R2/1000, 1)}kÎĐ)")
# R2 o'zgarishi ta'siri
r2_range = np.linspace(1000, 20000, 100)
vout_range = calc_vout(Vin, R1, r2_range)
plt.figure(figsize=(10, 5))
plt.plot(r2_range/1000, vout_range, 'b-', linewidth=2)
plt.axhline(y=Vout_target, color='r', linestyle='--', label=f'Maqsad: {Vout_target}V')
plt.axvline(x=R2/1000, color='g', linestyle='--', label=f'R2: {R2/1000:.1f}kÎĐ')
plt.xlabel('R2 (kÎĐ)')
plt.ylabel('Vout (V)')
plt.title(f'Kuchlanish Bo\'lgich (Vin={Vin}V, R1={R1/1000}kÎĐ)')
plt.legend()
plt.grid(True)
plt.savefig('voltage_divider.png', dpi=150)
plt.show()
# Quvvat hisob
I = Vin / (R1 + R2)
P_total = Vin * I
print(f"\nTok: {I*1000:.2f} mA")
print(f"Umumiy quvvat: {P_total*1000:.2f} mW")
voltage_divider_calculator()
4. RC Low-Pass Filtrâ
import numpy as np
import matplotlib.pyplot as plt
def rc_filter_analysis():
"""RC low-pass filtr chastota javob"""
R = 1000 # 1k
C = 0.1e-6 # 0.1uF
fc = 1 / (2 * np.pi * R * C)
print(f"Cutoff chastota: {fc:.0f} Hz")
f = np.logspace(1, 6, 500) # 10 Hz - 1 MHz
# Transfer function
H = 1 / np.sqrt(1 + (f/fc)**2)
H_dB = 20 * np.log10(H)
phase = -np.arctan(f/fc) * 180 / np.pi
fig, axes = plt.subplots(2, 1, figsize=(12, 8))
# Magnitude
axes[0].semilogx(f, H_dB, 'b-', linewidth=2)
axes[0].axvline(x=fc, color='r', linestyle='--', label=f'fc = {fc:.0f} Hz')
axes[0].axhline(y=-3, color='g', linestyle='--', label='-3 dB')
axes[0].set_xlabel('Chastota (Hz)')
axes[0].set_ylabel('Kuchlanish (dB)')
axes[0].set_title('RC Low-Pass Filtr - Chastota Javob')
axes[0].legend()
axes[0].grid(True, which='both')
axes[0].set_ylim([-40, 5])
# Phase
axes[1].semilogx(f, phase, 'm-', linewidth=2)
axes[1].axvline(x=fc, color='r', linestyle='--')
axes[1].axhline(y=-45, color='g', linestyle='--', label='-45° @ fc')
axes[1].set_xlabel('Chastota (Hz)')
axes[1].set_ylabel('Faza (°)')
axes[1].set_title('Faza Javob')
axes[1].legend()
axes[1].grid(True, which='both')
plt.tight_layout()
plt.savefig('rc_filter.png', dpi=150)
plt.show()
rc_filter_analysis()
5. PWM Simulyatsiyasiâ
import numpy as np
import matplotlib.pyplot as plt
def pwm_simulation():
"""PWM signal va filtering"""
f_pwm = 1000 # 1 kHz
T = 1 / f_pwm
t = np.linspace(0, 5*T, 5000)
duty_cycles = [0.25, 0.50, 0.75]
fig, axes = plt.subplots(len(duty_cycles), 2, figsize=(14, 10))
for i, D in enumerate(duty_cycles):
# PWM signal
pwm = np.where((t % T) < D * T, 1, 0) * 5 # 0-5V
# RC filter (low-pass)
R, C = 1000, 10e-6
tau = R * C
# Simple RC filter simulation
filtered = np.zeros_like(pwm)
for j in range(1, len(pwm)):
dt = t[1] - t[0]
alpha = dt / (tau + dt)
filtered[j] = alpha * pwm[j] + (1 - alpha) * filtered[j-1]
# PWM
axes[i, 0].plot(t*1000, pwm, 'b-', linewidth=1)
axes[i, 0].set_ylabel(f'D={int(D*100)}%')
axes[i, 0].set_ylim([-0.5, 5.5])
axes[i, 0].grid(True)
if i == 0:
axes[i, 0].set_title('PWM Signal')
if i == len(duty_cycles) - 1:
axes[i, 0].set_xlabel('Vaqt (ms)')
# Filtered
axes[i, 1].plot(t*1000, pwm, 'b-', alpha=0.3, linewidth=1)
axes[i, 1].plot(t*1000, filtered, 'r-', linewidth=2)
axes[i, 1].axhline(y=D*5, color='g', linestyle='--',
label=f'O\'rtacha: {D*5:.1f}V')
axes[i, 1].set_ylim([-0.5, 5.5])
axes[i, 1].legend(loc='right')
axes[i, 1].grid(True)
if i == 0:
axes[i, 1].set_title('RC Filtrlangan')
if i == len(duty_cycles) - 1:
axes[i, 1].set_xlabel('Vaqt (ms)')
plt.tight_layout()
plt.savefig('pwm_simulation.png', dpi=150)
plt.show()
pwm_simulation()
6. Arduino Kodi: LED PWMâ
// LED yorqinlik boshqarish (PWM)
const int LED_PIN = 9; // PWM pin
const int POT_PIN = A0; // Potentiometer
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Potentiometer o'qish (0-1023)
int potValue = analogRead(POT_PIN);
// PWM qiymatga o'zgartirish (0-255)
int pwmValue = map(potValue, 0, 1023, 0, 255);
// LED ga yozish
analogWrite(LED_PIN, pwmValue);
// Serial monitor
Serial.print("POT: ");
Serial.print(potValue);
Serial.print(" -> PWM: ");
Serial.print(pwmValue);
Serial.print(" (");
Serial.print(pwmValue * 100 / 255);
Serial.println("%)");
delay(100);
}
7. Arduino Kodi: Kuchlanish O'lchashâ
// Batareya kuchlanishini ADC bilan o'lchash
const int VOLTAGE_PIN = A0;
const float R1 = 10000.0; // 10k
const float R2 = 4700.0; // 4.7k
const float VREF = 5.0;
void setup() {
Serial.begin(9600);
Serial.println("Batareya Monitor");
}
void loop() {
// ADC o'qish
int adcValue = analogRead(VOLTAGE_PIN);
// ADC -> Kuchlanish (divider chiqishi)
float vOut = (adcValue / 1023.0) * VREF;
// Haqiqiy batareya kuchlanishi
float vBattery = vOut * (R1 + R2) / R2;
// Foiz (3S LiPo: 9.0V - 12.6V)
float percent = constrain(map(vBattery * 100, 900, 1260, 0, 100), 0, 100);
Serial.print("ADC: ");
Serial.print(adcValue);
Serial.print(" | Vout: ");
Serial.print(vOut, 2);
Serial.print("V | Batareya: ");
Serial.print(vBattery, 2);
Serial.print("V | ");
Serial.print(percent);
Serial.println("%");
delay(500);
}
8. Arduino Kodi: RC Vaqt O'lchashâ
// RC vaqt konstantasini o'lchash
const int CHARGE_PIN = 8; // Zaryadlash
const int MEASURE_PIN = A0; // Kuchlanish o'lchash
const float THRESHOLD = 0.632 * 5.0; // 63.2% of Vcc
void setup() {
Serial.begin(9600);
pinMode(CHARGE_PIN, OUTPUT);
digitalWrite(CHARGE_PIN, LOW);
delay(1000); // To'liq razryad
}
void loop() {
// Kondensatorni razryad qilish
digitalWrite(CHARGE_PIN, LOW);
delay(2000);
// Zaryadlashni boshlash
unsigned long startTime = micros();
digitalWrite(CHARGE_PIN, HIGH);
// Threshold ga yetguncha kutish
while (true) {
float voltage = analogRead(MEASURE_PIN) * 5.0 / 1023.0;
if (voltage >= THRESHOLD) {
break;
}
}
unsigned long tau = micros() - startTime;
Serial.print("Vaqt konstantasi Ï = ");
Serial.print(tau);
Serial.println(" Ξs");
delay(3000);
}
9. Python: Serial Monitoringâ
import serial
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from collections import deque
def arduino_monitor():
"""Arduino dan real-time ma'lumot olish"""
# Serial port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
# Data buffer
data = deque(maxlen=100)
fig, ax = plt.subplots(figsize=(10, 5))
line, = ax.plot([], [], 'b-', linewidth=2)
ax.set_xlim(0, 100)
ax.set_ylim(0, 5)
ax.set_xlabel('Vaqt')
ax.set_ylabel('Kuchlanish (V)')
ax.set_title('Arduino ADC Monitor')
ax.grid(True)
def update(frame):
try:
line_data = ser.readline().decode().strip()
if line_data:
# Parse (format: "ADC: 512 | Vout: 2.50V ...")
parts = line_data.split('|')
for part in parts:
if 'Vout:' in part:
voltage = float(part.split(':')[1].replace('V', '').strip())
data.append(voltage)
break
except:
pass
line.set_data(range(len(data)), list(data))
return line,
ani = animation.FuncAnimation(fig, update, interval=50, blit=True)
plt.show()
ser.close()
# arduino_monitor() # Arduino ulanganda ishga tushiring
10. Topshiriq: Motor H-Bridgeâ
def h_bridge_simulation():
"""
H-Bridge motor driver simulyatsiyasi
TODO:
1. 4 ta switch holatini modellang
2. PWM bilan tezlik boshqarish
3. Brake va coast rejimlarini qo'shing
"""
# Sizning kodingiz...
pass
# h_bridge_simulation()
Yechim
// Arduino H-Bridge Motor Control
const int ENA = 9; // PWM
const int IN1 = 8;
const int IN2 = 7;
void setup() {
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
Serial.begin(9600);
}
void forward(int speed) {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
analogWrite(ENA, speed);
}
void backward(int speed) {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
analogWrite(ENA, speed);
}
void brake() {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, HIGH);
analogWrite(ENA, 255);
}
void coast() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
analogWrite(ENA, 0);
}
void loop() {
Serial.println("Forward 50%");
forward(128);
delay(2000);
Serial.println("Forward 100%");
forward(255);
delay(2000);
Serial.println("Brake");
brake();
delay(1000);
Serial.println("Backward 75%");
backward(192);
delay(2000);
Serial.println("Coast");
coast();
delay(2000);
}
â Laboratoriya Tekshirish Ro'yxatiâ
- Ohm qonuni grafiklari
- RC zaryadlanish/razryadlanish
- Kuchlanish bo'lgich kalkulyator
- RC filtr chastota javob
- PWM simulyatsiya
- Arduino LED PWM
- Arduino ADC o'lchash
- H-Bridge motor control
Keyingi Mavzuâ
ð 3.2 Sensorlar