Softivation

Sensor and circuit lab

The board and sensors behave like real chips: I2C address, ID register, sleep mode, byte order, scale, noise and offset. In each task, one sensor isn't working or is measuring wrong. Make a guess, run it, check the wiring diagram and the chart, then write the missing line.

  • The code runs in an area isolated from the rest of the site. It can't reach your account, this page or the internet.
  • On the first run, Python downloads into your browser (a few seconds); after that it's fast.

IMU: wake up the sleeping sensor

The MPU6050 shows up in the I2C scan and its ID is correct, but acceleration is always zero. Guess first: a broken wire, a faulty sensor, or something else?

import math
from sv_lab import Gorev
from sv_lab.devre import Kart, Ortam, MPU6050, s16

kart = Kart(Ortam("salinim"))          # elde sallanan kart
kart.bagla(MPU6050())
print("I2C adresleri:", [hex(a) for a in kart.i2c_tara()])
print("WHO_AM_I:", hex(kart.i2c_oku(0x68, 0x75)[0]))
# TODO: sensörü uyandırın (ipucu: kart.i2c_yaz(0x68, 0x6B, ...))

for _ in range(300):
    b = kart.i2c_oku(0x68, 0x3B, 6)    # ACCEL_XOUT_H … ACCEL_ZOUT_L, büyük uçlu
    ax, ay, az = (s16(b[i], b[i + 1]) / 16384 for i in (0, 2, 4))   # 2 g aralığı: 16384 LSB/g
    kart.kaydet("az (g)", az)
    kart.kaydet("roll", math.degrees(math.atan2(ay, az)))
    kart.bekle_ms(20)

Gorev("IMU'yu uyandır, ivmeden roll", [
    ("ivmeölçer yerçekimini görüyor", lambda k: max(k.seri("az (g)")) > 0.8),
    ("roll gerçeğe yakın (RMS < 3 derece)", lambda k: k.hata("roll", "roll")[1] < 3),
]).denetle(kart)
kart.devre()
kart.ciz("roll", gercek={"roll": "roll"}, birim="derece", baslik="Roll: ivmeden")
Stuck?

The MPU6050 powers up in sleep mode: it won't measure until 0 is written to the PWR_MGMT_1 (0x6B) register. You can also ask your own AI about the code. Run the line it suggests here and see which criteria it meets.

The full topic: Basic Drone Course: From Sensors to Flight

Complementary filter: the gyro drifts, the accelerometer jitters

Integrating the gyro makes the angle drift slowly, and the accelerometer reads noisy under motor vibration. How do you combine the two? Run it with ALFA = 0 and compare the three lines.

import math
from sv_lab import Gorev
from sv_lab.devre import Kart, Ortam, MPU6050, s16

kart = Kart(Ortam("salinim"))
kart.bagla(MPU6050(titresim=0.12))    # motorların titreşimi
kart.i2c_yaz(0x68, 0x6B, 0x00)
ALFA = 0.0   # TODO: jiroskoba ne kadar güveneceksiniz? 0 ile 1 arası, ör. 0.98
DT = 0.01
roll_jiro = roll_filtre = 0.0
for _ in range(1500):
    b = kart.i2c_oku(0x68, 0x3B, 14)  # ivme (6) + sıcaklık (2) + jiroskop (6)
    ay, az = s16(b[2], b[3]), s16(b[4], b[5])
    gx = s16(b[8], b[9]) / 131.0       # 250 derece/sn aralığı: 131 LSB/(derece/sn)
    roll_ivme = math.degrees(math.atan2(ay, az))
    roll_jiro += gx * DT
    roll_filtre = ALFA * (roll_filtre + gx * DT) + (1 - ALFA) * roll_ivme
    kart.kaydet("ivmeden", roll_ivme)
    kart.kaydet("jiroskoptan", roll_jiro)
    kart.kaydet("tümleyen", roll_filtre)
    kart.bekle_ms(10)

print("RMS hata  (derece)  ivmeden %.1f  jiroskoptan %.1f  tümleyen %.1f" % tuple(kart.hata(a, "roll")[1] for a in ("ivmeden", "jiroskoptan", "tümleyen")))
Gorev("Tümleyen filtre", [
    ("filtre gerçeğe yakın (RMS < 2,5 derece)", lambda k: k.hata("tümleyen", "roll")[1] < 2.5),
    ("filtre ivmeölçerden iyi", lambda k: k.hata("tümleyen", "roll")[1] < k.hata("ivmeden", "roll")[1]),
]).denetle(kart)
kart.ciz("ivmeden", "jiroskoptan", "tümleyen", gercek={"tümleyen": "roll"}, birim="derece", baslik="Roll")
Stuck?

ALFA = 0 uses only the accelerometer. Give the gyro more weight (e.g. 0.98). You can also ask your own AI about the code. Run the line it suggests here and see which criteria it meets.

The full topic: Basic Drone Course: From Sensors to Flight

Barometer: altitude from pressure

The vehicle takes off at second 5 and climbs to 30 m. The BMP280 ID is correct and the calibration reads fine, but altitude is always zero. Why? Run it and look at the warning on the circuit diagram.

from sv_lab import Gorev
from sv_lab.devre import Kart, Ortam, BMP280, bmp280_dengele

kart = Kart(Ortam("kalkis"))
kart.bagla(BMP280())
print("Kimlik:", hex(kart.i2c_oku(0x76, 0xD0)[0]))      # 0x58
kal = kart.i2c_oku(0x76, 0x88, 24)                       # kalibrasyon bloğu
# TODO: ölçümü başlatın (ipucu: kart.i2c_yaz(0x76, 0xF4, ...))

p0 = None
for _ in range(40):
    b = kart.i2c_oku(0x76, 0xF7, 6)                      # basınç (20 bit) + sıcaklık (20 bit)
    adc_p = (b[0] << 12) | (b[1] << 4) | (b[2] >> 4)
    adc_t = (b[3] << 12) | (b[4] << 4) | (b[5] >> 4)
    sicaklik, p = bmp280_dengele(kal, adc_t, adc_p)
    p0 = p0 or p                                         # kalkış noktasının basıncı
    irtifa = 44330 * (1 - (p / p0) ** (1 / 5.255))
    kart.kaydet("irtifa", irtifa)
    kart.bekle_ms(1000)
print("Son ölçüm: %.1f C, %.0f Pa, %.1f m" % (sicaklik, p, irtifa))

Gorev("Barometrik irtifa", [
    ("yerdeyken irtifa ~0", lambda k: all(abs(v) < 1 for v in k.seri("irtifa")[:5])),
    ("30 m'de 1 m'den az hata", lambda k: abs(k.seri("irtifa")[-1] - 30) < 1),
]).denetle(kart)
kart.devre()
kart.ciz("irtifa", gercek={"irtifa": "irtifa"}, birim="m", baslik="İrtifa")
Stuck?

The BMP280 powers up in sleep mode: a measurement setting must be written to the ctrl_meas (0xF4) register (0x27 = temperature ×1, pressure ×1, normal mode). You can also ask your own AI about the code. Run the line it suggests here and see which criteria it meets.

The full topic: Basic Drone Course: From Sensors to Flight

Compass: calibrate the magnetic offset

The ground vehicle's board turns two full circles on its own axis. The electronics on the frame add a fixed offset to the compass. How far off is the heading without calibration? Guess, then find the offset from the maximum and minimum values.

import math
from sv_lab import Gorev
from sv_lab.devre import Kart, Ortam, HMC5883L, s16

kart = Kart(Ortam("donus"))            # kendi ekseninde 18 derece/sn
kart.bagla(HMC5883L())
kart.i2c_yaz(0x1E, 0x02, 0x00)         # sürekli ölçüm modu

def oku():
    b = kart.i2c_oku(0x1E, 0x03, 6)
    return s16(b[0], b[1]), s16(b[4], b[5])     # sıra X, Z, Y: Y son iki bayt

xs, ys = [], []
for _ in range(400):                   # 20 sn: bir tam turdan fazla
    mx, my = oku()
    xs.append(mx); ys.append(my)
    kart.bekle_ms(50)
x0, y0 = 0, 0   # TODO: sapmayı bulun: (max(xs) + min(xs)) / 2, y için de aynısı
print("Sapma: x0 = %.0f, y0 = %.0f" % (x0, y0))

for _ in range(200):
    mx, my = oku()
    kart.kaydet("yön", math.degrees(math.atan2(-(my - y0), mx - x0)) % 360)
    kart.bekle_ms(50)

Gorev("Pusula kalibrasyonu", [
    ("yön hatası 5 dereceden küçük", lambda k: k.hata("yön", "yaw")[0] < 5),
]).denetle(kart)
kart.ciz("yön", gercek={"yön": "yaw"}, birim="derece", baslik="Yön (pusula)")
Stuck?

The (hard iron) offset wasn't removed: on each axis it's (max + min) / 2. You can also ask your own AI about the code. Run the line it suggests here and see which criteria it meets.

The full topic: Basic Drone Course: From Sensors to Flight

GPS: position from an NMEA sentence

The multicopter flies 40 m north and 25 m east. The GPS sends a GGA sentence over the serial port. Is a latitude like 4011.31 equal to 40.1131°? Guess, then compare the tracks.

import math
from sv_lab import Arac, Gorev
from sv_lab.devre import Kart, Ortam, GPS

iha = Arac("multikopter", ad="SV-1")
iha.bekle(4).mod("GUIDED").arm().kalk(10)
iha.git(40, 25)
iha.calistir(40)

kart = Kart(Ortam(arac=iha))           # kartı uçan aracın üstüne koyun
kart.bagla(GPS())
EV = (40.1885, 29.0610)                # kalkış noktası (derece)

def derece(nmea):
    x = float(nmea)
    return x / 100   # TODO: NMEA derece-dakikadır (ddmm.mmmm); ondalık dereceye çevirin

for _ in range(40):
    for satir in kart.seri_oku():
        p = satir.split(",")           # $GPGGA,saat,enlem,N,boylam,E,...
        en, boy = derece(p[2]), derece(p[4])
        kart.kaydet("kuzey (m)", (en - EV[0]) * 111320)
        kart.kaydet("doğu (m)", (boy - EV[1]) * 111320 * math.cos(math.radians(EV[0])))
    kart.bekle_ms(1000)
print("Son cümle:", satir)

Gorev("GPS konumu", [
    ("kuzey 3 m'den yakın", lambda k: k.hata("kuzey (m)", "kuzey")[0] < 3),
    ("doğu 3 m'den yakın", lambda k: k.hata("doğu (m)", "dogu")[0] < 3),
]).denetle(kart)
kart.ciz("kuzey (m)", "doğu (m)", gercek={"kuzey (m)": "kuzey", "doğu (m)": "dogu"}, birim="m", baslik="GPS konumu")
Stuck?

An NMEA latitude is degrees and minutes (ddmm.mmmm): int(x / 100) + (x % 100) / 60. You can also ask your own AI about the code. Run the line it suggests here and see which criteria it meets.

The full topic: Basic Drone Course: From Sensors to Flight

Battery: measuring with a voltage divider

The boat's 3S LiPo battery is at 12.6 V, but the board's analog input reads at most 5 V. How do you turn the value from a 10 kΩ / 3.3 kΩ divider into the correct voltage?

from sv_lab import Gorev
from sv_lab.devre import Kart, Ortam, GerilimBolucu

kart = Kart(Ortam("masa"))
kart.bagla(GerilimBolucu("A0", r1=10000, r2=3300))
ORAN = 1.0   # TODO: bölücü oranı: (R1 + R2) / R2

for _ in range(60):
    ham = kart.analog_oku("A0")        # 0–1023, 5 V referans
    v_pin = ham * 5.0 / 1023
    kart.kaydet("batarya (V)", v_pin * ORAN)
    kart.bekle_ms(1000)
print("Son okuma: %.2f V" % kart.seri("batarya (V)")[-1])

Gorev("Batarya gerilimi", [
    ("gerçeğe 0,05 V'tan yakın", lambda k: k.hata("batarya (V)", "batarya")[1] < 0.05),
    ("pin 5 V'u aşmadı", lambda k: not any("referansın" in m for _, m in k.olaylar)),
]).denetle(kart)
kart.devre()
kart.ciz("batarya (V)", gercek={"batarya (V)": "batarya"}, birim="V", baslik="Batarya")
Stuck?

The divider ratio is missing: Vbat = Vpin · (R1 + R2) / R2. You can also ask your own AI about the code. Run the line it suggests here and see which criteria it meets.

The full topic: Basic Drone Course: From Sensors to Flight

Ultrasonic distance: from time to meters

The HC-SR04 gives the echo's round-trip time. The board is sitting at 35 °C. How many centimeters off are you if you calculate with 343 m/s? Guess first.

from sv_lab import Gorev
from sv_lab.devre import Kart, Ortam, HCSR04

SICAKLIK = 35.0
kart = Kart(Ortam("salinim", sicaklik=SICAKLIK, mesafe=1.2))
kart.bagla(HCSR04(trig=9, echo=10))

for _ in range(100):
    kart.dijital_yaz(9, 1); kart.dijital_yaz(9, 0)   # 10 mikrosaniyelik tetik darbesi
    sure = kart.darbe_olc(10)                          # mikrosaniye
    mesafe = sure * 1e-6 * 343.0   # TODO: süre gidiş-dönüştür; ses hızı da sıcaklığa bağlı
    kart.kaydet("mesafe (m)", mesafe)
    kart.bekle_ms(100)

Gorev("Ultrasonik mesafe", [
    ("1 cm'den az hata (RMS)", lambda k: k.hata("mesafe (m)", "mesafe")[1] < 0.01),
]).denetle(kart)
kart.devre()
kart.ciz("mesafe (m)", gercek={"mesafe (m)": "mesafe"}, birim="m", baslik="Mesafe")
Stuck?

The time is a round trip (divide by two), and the speed of sound changes with temperature: 331.3 + 0.606·T. You can also ask your own AI about the code. Run the line it suggests here and see which criteria it meets.

The full topic: Basic Drone Course: From Sensors to Flight