Arch Linux ARM 开发者培训:从零开始掌握嵌入式系统开发实战技巧

引言:为什么选择 Arch Linux ARM 进行嵌入式开发?
在嵌入式系统开发领域,选择合适的操作系统和开发环境至关重要。Arch Linux ARM 作为一个轻量级、高度可定制的 Linux 发行版,为嵌入式开发者提供了极大的灵活性和控制力。与传统的嵌入式 Linux 系统(如 Yocto 或 Buildroot)相比,Arch Linux ARM 具有以下优势:
滚动更新机制
:始终使用最新的软件包和内核版本
极简主义设计
:只安装需要的组件,减少系统开销
强大的包管理器
:pacman 提供高效的软件管理
活跃的社区支持
:丰富的文档和活跃的开发者社区
完整的开发工具链
:直接使用标准的 Linux 开发工具
第一部分:环境搭建与基础配置
1.1 硬件准备
在开始之前,你需要准备以下硬件:
开发板
:推荐使用树莓派(Raspberry Pi)系列、BeagleBone 或 Orange Pi 等主流开发板
存储设备
:Class 10 或更高速度的 microSD 卡(建议 16GB 以上)
电源适配器
:稳定的 5V 电源(根据开发板需求选择电流)
网络连接
:有线或无线网络连接
主机系统
:运行 Linux、macOS 或 Windows 的开发主机
1.2 下载与安装 Arch Linux ARM
步骤 1:下载镜像
访问 Arch Linux ARM 官方网站(
https://archlinuxarm.org/),根据你的开发板型号下载对应的镜像文件。以树莓派
4 为例:
# 使用 wget 下载镜像(示例命令)
wget http://os.archlinuxarm.org/os/ArchLinuxARM-rpi-aarch64-latest.tar.gz
步骤 2:准备 microSD 卡
在 Linux/macOS 主机上,使用
dd
命令写入镜像:
# 查找 SD 卡设备(注意:请确认设备名称,避免误操作)
lsblk

# 写入镜像(假设 SD 卡设备为 /dev/sdb)
sudo dd if=ArchLinuxARM-rpi-aarch64-latest.tar.gz of=/dev/sdb bs=4M status=progress
在 Windows 主机上,可以使用工具如 BalenaEtcher 或 Win32 Disk Imager。
步骤 3:首次启动配置
将 microSD 卡插入开发板,连接电源和网络,首次启动后需要完成以下配置:
# 登录系统(默认用户名:root,密码:root)
# 立即修改 root 密码
passwd

# 创建普通用户(建议)
useradd -m -G wheel -s /bin/bash yourusername
passwd yourusername

# 配置 sudo 权限
pacman -S sudo
visudo # 取消注释 %wheel ALL=(ALL) ALL
1.3 网络配置
有线网络配置
# 查看网络接口
ip link show

# 启用网络接口(假设接口为 eth0)
ip link set eth0 up

# 配置 DHCP(推荐)
systemctl enable dhcpcd@eth0.service
systemctl start dhcpcd@eth0.service

# 或者手动配置静态 IP
cat > /etc/systemd/network/eth0.network << EOF [Match] Name=eth0 [Network] Address=192.168.1.100/24 Gateway=192.168.1.1 DNS=8.8.8.8 EOF systemctl enable systemd-networkd systemctl start systemd-networkd 无线网络配置 # 安装无线工具 pacman -S wpa_supplicant # 配置无线网络 cat > /etc/wpa_supplicant/wpa_supplicant-wlan0.conf << EOF country=US ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheel update_config=1 network={ ssid="YourWiFiSSID" psk="YourWiFiPassword" } EOF # 启用无线网络 systemctl enable wpa_supplicant@wlan0.service systemctl start wpa_supplicant@wlan0.service 第二部分:开发工具链配置 2.1 基础开发工具安装 # 更新系统 sudo pacman -Syu # 安装基础开发工具 sudo pacman -S base-devel git vim nano # 安装交叉编译工具链(如果需要在 x86 主机上编译 ARM 代码) sudo pacman -S aarch64-linux-gnu-gcc aarch64-linux-gnu-binutils # 安装 Python 开发环境 sudo pacman -S python python-pip python-virtualenv # 安装 C/C++ 开发工具 sudo pacman -S gcc make cmake gdb 2.2 嵌入式开发专用工具 # 安装设备树工具 sudo pacman -S dtc # 安装串口通信工具 sudo pacman -S minicom screen # 安装网络调试工具 sudo pacman -S net-tools iproute2 tcpdump # 安装版本控制工具 sudo pacman -S git mercurial # 安装构建系统 sudo pacman -S scons ninja 2.3 集成开发环境配置 VS Code 配置 # 安装 VS Code sudo pacman -S code # 安装扩展(在 VS Code 中) # - C/C++ Extension Pack # - Python Extension Pack # - Remote - SSH (用于远程开发) # - Device Tree Support 配置 VS Code 远程开发 创建 .vscode/settings.json : { "files.associations": { "*.dts": "device-tree", "*.dtsi": "device-tree" }, "C_Cpp.default.compilerPath": "/usr/bin/aarch64-linux-gnu-gcc", "C_Cpp.default.intelliSenseMode": "linux-gcc-arm64", "python.defaultInterpreterPath": "/usr/bin/python" } 第三部分:嵌入式系统开发实战 3.1 GPIO 控制开发 基础 GPIO 操作 在 Linux 中,GPIO 通过 sysfs 接口暴露给用户空间: # 查看可用 GPIO ls /sys/class/gpio/ # 导出 GPIO 引脚(假设使用 GPIO 17) echo 17 > /sys/class/gpio/export

# 设置方向
echo out > /sys/class/gpio/gpio17/direction

# 控制 GPIO 状态
echo 1 > /sys/class/gpio/gpio17/value # 高电平
echo 0 > /sys/class/gpio/gpio17/value # 低电平

# 清理
echo 17 > /sys/class/gpio/unexport
使用 C 语言控制 GPIO
// gpio_control.c
#include
#include
#include
#include
#include

#define GPIO_PIN 17
#define GPIO_PATH “/sys/class/gpio/gpio17”

void export_gpio(int pin) {
char path[50];
sprintf(path, “/sys/class/gpio/export”);
int fd = open(path, O_WRONLY);
if (fd < 0) { perror("Cannot open export"); return; } char pin_str[5]; sprintf(pin_str, "%d", pin); write(fd, pin_str, strlen(pin_str)); close(fd); } void set_gpio_direction(int pin, const char* direction) { char path[50]; sprintf(path, "/sys/class/gpio/gpio%d/direction", pin); int fd = open(path, O_WRONLY); if (fd < 0) { perror("Cannot open direction"); return; } write(fd, direction, strlen(direction)); close(fd); } void set_gpio_value(int pin, int value) { char path[50]; sprintf(path, "/sys/class/gpio/gpio%d/value", pin); int fd = open(path, O_WRONLY); if (fd < 0) { perror("Cannot open value"); return; } char val_str[2]; sprintf(val_str, "%d", value); write(fd, val_str, strlen(val_str)); close(fd); } int main() { export_gpio(GPIO_PIN); set_gpio_direction(GPIO_PIN, "out"); // 闪烁 LED for (int i = 0; i < 10; i++) { set_gpio_value(GPIO_PIN, 1); sleep(1); set_gpio_value(GPIO_PIN, 0); sleep(1); } return 0; } 编译和运行: # 编译 gcc -o gpio_control gpio_control.c # 运行 sudo ./gpio_control 使用 Python 控制 GPIO # gpio_control.py import time import os class GPIOController: def __init__(self, pin): self.pin = pin self.export() def export(self): export_path = "/sys/class/gpio/export" with open(export_path, 'w') as f: f.write(str(self.pin)) def set_direction(self, direction): direction_path = f"/sys/class/gpio/gpio{self.pin}/direction" with open(direction_path, 'w') as f: f.write(direction) def set_value(self, value): value_path = f"/sys/class/gpio/gpio{self.pin}/value" with open(value_path, 'w') as f: f.write(str(value)) def cleanup(self): unexport_path = "/sys/class/gpio/unexport" with open(unexport_path, 'w') as f: f.write(str(self.pin)) # 使用示例 if __name__ == "__main__": led = GPIOController(17) led.set_direction("out") try: for i in range(10): led.set_value(1) time.sleep(1) led.set_value(0) time.sleep(1) finally: led.cleanup() 3.2 I2C 设备通信 I2C 基础操作 # 安装 I2C 工具 sudo pacman -S i2c-tools # 查看 I2C 总线 i2cdetect -l # 扫描 I2C 设备(假设使用总线 1) i2cdetect -y 1 使用 C 语言进行 I2C 通信 // i2c_communication.c #include
#include
#include #include
#include
#include

int main() {
int file;
char filename[20];
int addr = 0x48; // I2C 设备地址

// 打开 I2C 设备
sprintf(filename, “/dev/i2c-1”);
if ((file = open(filename, O_RDWR)) < 0) { perror("Failed to open i2c bus"); return 1; } // 设置设备地址 if (ioctl(file, I2C_SLAVE, addr) < 0) { perror("Failed to set slave address"); return 1; } // 写入数据 char buf[10] = {0x01, 0x02, 0x03}; if (write(file, buf, 3) != 3) { perror("Failed to write to i2c device"); return 1; } // 读取数据 char read_buf[10]; if (read(file, read_buf, 2) != 2) { perror("Failed to read from i2c device"); return 1; } printf("Read data: 0x%02X 0x%02X\n", read_buf[0], read_buf[1]); close(file); return 0; } 编译和运行: # 编译 gcc -o i2c_communication i2c_communication.c # 运行 sudo ./i2c_communication 3.3 SPI 设备通信 SPI 基础配置 # 查看 SPI 设备 ls /dev/spi* # 加载 SPI 内核模块 sudo modprobe spi_bcm2835 使用 Python 进行 SPI 通信 # spi_communication.py import spidev import time class SPIDevice: def __init__(self, bus=0, device=0): self.spi = spidev.SpiDev() self.spi.open(bus, device) self.spi.max_speed_hz = 1000000 # 1MHz def read_write(self, data): """发送并接收数据""" return self.spi.xfer2(data) def close(self): self.spi.close() # 使用示例:读取温度传感器 if __name__ == "__main__": sensor = SPIDevice() try: # 发送读取命令(假设命令为 0x01) response = sensor.read_write([0x01, 0x00]) temperature = (response[0] << 8) | response[1] print(f"Temperature: {temperature} °C") finally: sensor.close() 3.4 UART 串口通信 串口配置 # 查看串口设备 ls /dev/tty* # 安装串口工具 sudo pacman -S minicom # 配置 minicom sudo minicom -s # 选择 "Serial port setup" # 设置设备:/dev/ttyS0 或 /dev/ttyAMA0 # 设置波特率:115200 # 保存配置 使用 Python 进行串口通信 # uart_communication.py import serial import time class UARTDevice: def __init__(self, port='/dev/ttyAMA0', baudrate=115200): self.ser = serial.Serial( port=port, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1 ) def send(self, data): """发送数据""" if isinstance(data, str): data = data.encode() self.ser.write(data) def receive(self, size=1): """接收数据""" return self.ser.read(size) def close(self): self.ser.close() # 使用示例 if __name__ == "__main__": uart = UARTDevice() try: # 发送命令 uart.send("AT\r\n") time.sleep(0.1) # 读取响应 response = uart.receive(100) print(f"Response: {response.decode()}") finally: uart.close() 第四部分:内核与驱动开发 4.1 内核编译基础 获取内核源码 # 安装内核开发工具 sudo pacman -S linux-aarch64-headers # 或者从 GitHub 获取内核源码 git clone --depth 1 https://github.com/raspberrypi/linux.git cd linux 配置内核 # 复制默认配置 make bcm2711_defconfig # 树莓派 4B 的配置 # 或者使用 menuconfig 进行自定义配置 make menuconfig 编译内核 # 编译内核和模块 make -j$(nproc) Image modules dtbs # 安装模块到指定目录 sudo make modules_install INSTALL_MOD_PATH=/path/to/rootfs # 复制内核镜像 sudo cp arch/arm64/boot/Image /boot/kernel8.img sudo cp arch/arm64/boot/dts/broadcom/*.dtb /boot/ 4.2 编写简单的字符设备驱动 驱动程序代码 // simple_char_driver.c #include #include #include #include #include #include

#define DEVICE_NAME “simple_char”
#define CLASS_NAME “simple_class”
#define BUFFER_SIZE 1024

static int major_number;
static struct class* simple_class = NULL;
static struct device* simple_device = NULL;
static char device_buffer[BUFFER_SIZE];
static int buffer_size = 0;

// 文件操作函数
static int device_open(struct inode *inode, struct file *file) {
printk(KERN_INFO “SimpleChar: Device opened\n”);
return 0;
}

static int device_release(struct inode *inode, struct file *file) {
printk(KERN_INFO “SimpleChar: Device closed\n”);
return 0;
}

static ssize_t device_read(struct file *file, char __user *buf, size_t len, loff_t *offset) {
int bytes_to_read = min(len, (size_t)buffer_size);

if (copy_to_user(buf, device_buffer, bytes_to_read)) {
return -EFAULT;
}

buffer_size -= bytes_to_read;
if (buffer_size > 0) {
memmove(device_buffer, device_buffer + bytes_to_read, buffer_size);
}

printk(KERN_INFO “SimpleChar: Read %d bytes\n”, bytes_to_read);
return bytes_to_read;
}

static ssize_t device_write(struct file *file, const char __user *buf, size_t len, loff_t *offset) {
int bytes_to_write = min(len, (size_t)(BUFFER_SIZE – buffer_size));

if (copy_from_user(device_buffer + buffer_size, buf, bytes_to_write)) {
return -EFAULT;
}

buffer_size += bytes_to_write;
device_buffer[buffer_size] = ‘\0’;

printk(KERN_INFO “SimpleChar: Wrote %d bytes: %s\n”, bytes_to_write, device_buffer + buffer_size – bytes_to_write);
return bytes_to_write;
}

// 文件操作结构体
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = device_open,
.release = device_release,
.read = device_read,
.write = device_write,
};

// 模块初始化
static int __init simple_char_init(void) {
printk(KERN_INFO “SimpleChar: Initializing the simple character driver\n”);

// 动态分配主设备号
major_number = register_chrdev(0, DEVICE_NAME, &fops);
if (major_number < 0) { printk(KERN_ALERT "SimpleChar: Failed to register a major number\n"); return major_number; } // 创建设备类 simple_class = class_create(THIS_MODULE, CLASS_NAME); if (IS_ERR(simple_class)) { unregister_chrdev(major_number, DEVICE_NAME); printk(KERN_ALERT "SimpleChar: Failed to register device class\n"); return PTR_ERR(simple_class); } // 创建设备节点 simple_device = device_create(simple_class, NULL, MKDEV(major_number, 0), NULL, DEVICE_NAME); if (IS_ERR(simple_device)) { class_destroy(simple_class); unregister_chrdev(major_number, DEVICE_NAME); printk(KERN_ALERT "SimpleChar: Failed to create the device\n"); return PTR_ERR(simple_device); } printk(KERN_INFO "SimpleChar: Device class created successfully\n"); printk(KERN_INFO "SimpleChar: Device node created at /dev/%s\n", DEVICE_NAME); return 0; } // 模块退出 static void __exit simple_char_exit(void) { device_destroy(simple_class, MKDEV(major_number, 0)); class_unregister(simple_class); class_destroy(simple_class); unregister_chrdev(major_number, DEVICE_NAME); printk(KERN_INFO "SimpleChar: Module has been unloaded\n"); } module_init(simple_char_init); module_exit(simple_char_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Your Name"); MODULE_DESCRIPTION("A simple character device driver"); Makefile # Makefile obj-m += simple_char_driver.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean 编译和加载驱动 # 编译驱动 make # 加载驱动 sudo insmod simple_char_driver.ko # 查看内核日志 dmesg | tail -n 20 # 创建设备节点(如果未自动创建) sudo mknod /dev/simple_char c 250 0 # 使用实际的主设备号 # 测试设备 echo "Hello from userspace" > /dev/simple_char
cat /dev/simple_char

# 卸载驱动
sudo rmmod simple_char_driver
第五部分:系统优化与性能调优
5.1 内存管理优化
查看内存使用情况
# 查看内存统计
free -h

# 查看进程内存使用
ps aux –sort=-%mem | head -20

# 查看内存映射
cat /proc/meminfo
优化内存使用
# 调整交换空间
sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# 添加到 fstab 永久生效
echo ‘/swapfile none swap sw 0 0’ | sudo tee -a /etc/fstab

# 调整 swappiness(减少交换倾向)
echo ‘vm.swappiness=10’ | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
5.2 CPU 性能调优
CPU 频率调节
# 安装 cpufreq 工具
sudo pacman -S cpupower

# 查看当前 CPU 频率策略
cpupower frequency-info

# 设置性能模式(最大性能)
sudo cpupower frequency-set -g performance

# 设置省电模式
sudo cpupower frequency-set -g powersave

# 设置自定义频率范围
sudo cpupower frequency-set -d 800MHz -u 1.5GHz
进程优先级调整
# 使用 nice 调整进程优先级
nice -n -10 ./my_app # 高优先级
nice -n 10 ./my_app # 低优先级

# 使用 renice 调整运行中进程
renice -n -10 -p

# 设置实时优先级(需要 root)
sudo chrt -f -p 99
5.3 存储性能优化
文件系统优化
# 查看文件系统类型
df -T

# 优化 ext4 文件系统
sudo tune2fs -o journal_data_writeback /dev/mmcblk0p2

# 调整挂载选项
# 编辑 /etc/fstab,添加:
# /dev/mmcblk0p2 / ext4 defaults,noatime,nodiratime 0 1
I/O 调度器优化
# 查看当前 I/O 调度器
cat /sys/block/mmcblk0/queue/scheduler

# 设置为 deadline 调度器(适合嵌入式系统)
echo deadline > /sys/block/mmcblk0/queue/scheduler

# 永久生效(创建 udev 规则)
sudo tee /etc/udev/rules.d/60-scheduler.rules << EOF ACTION=="add|change", KERNEL=="sd[a-z]|mmcblk[0-9]*", ATTR{queue/scheduler}="deadline" EOF 第六部分:调试与故障排除 6.1 调试工具 GDB 调试 # 安装 GDB sudo pacman -S gdb # 编译带调试信息的程序 gcc -g -o my_program my_program.c # 启动 GDB gdb ./my_program # 常用 GDB 命令 # break main # 在 main 函数设置断点 # run # 运行程序 # next # 单步执行 # print variable # 打印变量值 # backtrace # 查看调用栈 Strace 跟踪系统调用 # 跟踪系统调用 strace ./my_program # 跟踪特定系统调用 strace -e trace=open,read,write ./my_program # 输出到文件 strace -o trace.log ./my_program Valgrind 内存检查 # 安装 Valgrind sudo pacman -S valgrind # 检查内存泄漏 valgrind --leak-check=full ./my_program # 检查未初始化内存 valgrind --track-origins=yes ./my_program 6.2 系统日志分析 查看系统日志 # 查看内核日志 dmesg | tail -n 50 # 查看系统日志 journalctl -n 50 # 查看特定服务的日志 journalctl -u sshd -n 20 # 实时查看日志 journalctl -f 自定义日志记录 // logger_example.c #include
#include

int main() {
// 打开系统日志
openlog(“my_app”, LOG_PID | LOG_CONS, LOG_USER);

// 记录不同级别的日志
syslog(LOG_INFO, “Application started”);
syslog(LOG_WARNING, “Low memory warning”);
syslog(LOG_ERR, “Failed to open file”);

// 关闭日志
closelog();

return 0;
}
6.3 网络调试
网络诊断工具
# 查看网络接口
ip addr show

# 测试网络连通性
ping 8.8.8.8

# 跟踪路由
traceroute 8.8.8.8

# 抓包分析
sudo tcpdump -i eth0 -w capture.pcap

# 查看网络连接
netstat -tulpn
ss -tulpn
第七部分:项目实战:构建一个物联网数据采集系统
7.1 系统架构设计
传感器层 (I2C/SPI/UART)
↓
数据采集层 (Python/C 程序)
↓
数据处理层 (本地存储 + 云端上传)
↓
用户界面层 (Web 或 CLI)
7.2 硬件连接
温度传感器:DS18B20(1-Wire)
湿度传感器:DHT22(GPIO)
光照传感器:BH1750(I2C)
数据存储:本地 SQLite 数据库
网络传输:MQTT 协议
7.3 软件实现
数据采集模块
# sensor_collection.py
import sqlite3
import time
import json
import paho.mqtt.client as mqtt
from datetime import datetime

class SensorCollector:
def __init__(self, db_path=”sensor_data.db”):
self.db_path = db_path
self.init_database()
self.mqtt_client = mqtt.Client()
self.mqtt_client.connect(“localhost”, 1883, 60)

def init_database(self):
“””初始化数据库”””
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(”’
CREATE TABLE IF NOT EXISTS sensor_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
temperature REAL,
humidity REAL,
light_level REAL
)
”’)
conn.commit()
conn.close()

def read_temperature(self):
“””读取温度(模拟)”””
# 实际项目中这里会读取真实的传感器
return 25.0 + (time.time() % 10)

def read_humidity(self):
“””读取湿度(模拟)”””
return 60.0 + (time.time() % 5)

def read_light_level(self):
“””读取光照(模拟)”””
return 500.0 + (time.time() % 100)

def save_to_database(self, temp, humidity, light):
“””保存数据到数据库”””
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(”’
INSERT INTO sensor_data (temperature, humidity, light_level)
VALUES (?, ?, ?)
”’, (temp, humidity, light))
conn.commit()
conn.close()

def publish_to_mqtt(self, temp, humidity, light):
“””发布数据到 MQTT”””
data = {
“timestamp”: datetime.now().isoformat(),
“temperature”: temp,
“humidity”: humidity,
“light_level”: light
}
self.mqtt_client.publish(“sensors/data”, json.dumps(data))

def run(self):
“””主循环”””
print(“Starting sensor collection…”)
try:
while True:
temp = self.read_temperature()
humidity = self.read_humidity()
light = self.read_light_level()

print(f”Temp: {temp:.1f}°C, Humidity: {humidity:.1f}%, Light: {light:.1f} lux”)

self.save_to_database(temp, humidity, light)
self.publish_to_mqtt(temp, humidity, light)

time.sleep(5) # 每5秒采集一次
except KeyboardInterrupt:
print(“\nStopping sensor collection…”)
self.mqtt_client.disconnect()

if __name__ == “__main__”:
collector = SensorCollector()
collector.run()
Web 界面(Flask)
# web_interface.py
from flask import Flask, render_template, jsonify
import sqlite3
from datetime import datetime, timedelta

app = Flask(__name__)

@app.route(‘/’)
def index():
return render_template(‘index.html’)

@app.route(‘/api/data’)
def get_data():
“””获取最近的数据”””
conn = sqlite3.connect(‘sensor_data.db’)
cursor = conn.cursor()

# 获取最近1小时的数据
one_hour_ago = datetime.now() – timedelta(hours=1)
cursor.execute(”’
SELECT timestamp, temperature, humidity, light_level
FROM sensor_data
WHERE timestamp > ?
ORDER BY timestamp DESC
LIMIT 100
”’, (one_hour_ago,))

data = cursor.fetchall()
conn.close()

return jsonify([{
‘timestamp’: row[0],
‘temperature’: row[1],
‘humidity’: row[2],
‘light_level’: row[3]
} for row in data])

@app.route(‘/api/latest’)
def get_latest():
“””获取最新数据”””
conn = sqlite3.connect(‘sensor_data.db’)
cursor = conn.cursor()
cursor.execute(”’
SELECT timestamp, temperature, humidity, light_level
FROM sensor_data
ORDER BY timestamp DESC
LIMIT 1
”’)

row = cursor.fetchone()
conn.close()

if row:
return jsonify({
‘timestamp’: row[0],
‘temperature’: row[1],
‘humidity’: row[2],
‘light_level’: row[3]
})
return jsonify({})

if __name__ == ‘__main__’:
app.run(host=’0.0.0.0′, port=5000, debug=True)
HTML 模板




物联网数据监控


物联网数据监控系统

温度

—
°C

湿度

—
%

光照

—
lux




7.4 系统部署与自动化
Systemd 服务配置
# /etc/systemd/system/sensor-collector.service
[Unit]
Description=IoT Sensor Data Collector
After=network.target

[Service]
Type=simple
User=yourusername
WorkingDirectory=/home/yourusername/iot-project
ExecStart=/usr/bin/python3 /home/yourusername/iot-project/sensor_collection.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
# /etc/systemd/system/web-interface.service
[Unit]
Description=IoT Web Interface
After=network.target sensor-collector.service

[Service]
Type=simple
User=yourusername
WorkingDirectory=/home/yourusername/iot-project
ExecStart=/usr/bin/python3 /home/yourusername/iot-project/web_interface.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
启用服务
# 启用并启动服务
sudo systemctl enable sensor-collector.service
sudo systemctl enable web-interface.service
sudo systemctl start sensor-collector.service
sudo systemctl start web-interface.service

# 查看服务状态
sudo systemctl status sensor-collector.service
sudo systemctl status web-interface.service

# 查看日志
sudo journalctl -u sensor-collector.service -f
sudo journalctl -u web-interface.service -f
第八部分:安全与最佳实践
8.1 系统安全加固
用户与权限管理
# 禁用 root 远程登录
sudo sed -i ‘s/#PermitRootLogin yes/PermitRootLogin no/’ /etc/ssh/sshd_config

# 创建专用服务用户
sudo useradd -r -s /bin/false iot-service

# 设置文件权限
sudo chown -R iot-service:iot-service /opt/iot-app
sudo chmod 750 /opt/iot-app
防火墙配置
# 安装防火墙
sudo pacman -S ufw

# 启用防火墙
sudo ufw enable

# 允许 SSH(如果需要)
sudo ufw allow ssh

# 允许 Web 端口
sudo ufw allow 5000/tcp

# 允许 MQTT 端口
sudo ufw allow 1883/tcp

# 查看规则
sudo ufw status verbose
8.2 数据安全
数据库加密
# encrypted_database.py
import sqlite3
import os
from cryptography.fernet import Fernet

class EncryptedDatabase:
def __init__(self, db_path, key_path=”secret.key”):
self.db_path = db_path
self.key_path = key_path
self.cipher = self._load_or_generate_key()

def _load_or_generate_key(self):
“””加载或生成加密密钥”””
if os.path.exists(self.key_path):
with open(self.key_path, ‘rb’) as f:
key = f.read()
else:
key = Fernet.generate_key()
with open(self.key_path, ‘wb’) as f:
f.write(key)
return Fernet(key)

def encrypt_data(self, data):
“””加密数据”””
if isinstance(data, str):
data = data.encode()
return self.cipher.encrypt(data)

def decrypt_data(self, encrypted_data):
“””解密数据”””
decrypted = self.cipher.decrypt(encrypted_data)
return decrypted.decode()

def save_encrypted(self, temp, humidity, light):
“””保存加密数据”””
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

# 创建表(如果不存在)
cursor.execute(”’
CREATE TABLE IF NOT EXISTS encrypted_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
encrypted_data BLOB
)
”’)

# 加密数据
data = f”{temp},{humidity},{light}”
encrypted = self.encrypt_data(data)

cursor.execute(”’
INSERT INTO encrypted_data (encrypted_data) VALUES (?)
”’, (encrypted,))

conn.commit()
conn.close()

def read_encrypted(self):
“””读取并解密数据”””
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

cursor.execute(”’
SELECT timestamp, encrypted_data FROM encrypted_data
ORDER BY timestamp DESC LIMIT 10
”’)

results = []
for row in cursor.fetchall():
decrypted = self.decrypt_data(row[1])
temp, humidity, light = decrypted.split(‘,’)
results.append({
‘timestamp’: row[0],
‘temperature’: float(temp),
‘humidity’: float(humidity),
‘light_level’: float(light)
})

conn.close()
return results
8.3 备份与恢复
自动备份脚本
#!/bin/bash
# backup.sh

BACKUP_DIR=”/backup”
DB_PATH=”/home/yourusername/iot-project/sensor_data.db”
LOG_FILE=”/var/log/backup.log”

# 创建备份目录
mkdir -p $BACKUP_DIR

# 备份数据库
timestamp=$(date +%Y%m%d_%H%M%S)
backup_file=”$BACKUP_DIR/sensor_data_$timestamp.db”

cp $DB_PATH $backup_file

# 压缩备份
gzip $backup_file

# 删除旧备份(保留最近7天)
find $BACKUP_DIR -name “*.gz” -mtime +7 -delete

# 记录日志
echo “$(date): Backup completed: $backup_file.gz” >> $LOG_FILE

# 可选:上传到远程服务器
# scp $backup_file.gz user@remote-server:/backup/
设置定时任务
# 编辑 crontab
crontab -e

# 添加以下行(每天凌晨2点执行备份)
0 2 * * * /home/yourusername/backup.sh
第九部分:进阶技巧与资源
9.1 性能分析工具
perf 性能分析
# 安装 perf
sudo pacman -S perf

# 记录性能数据
sudo perf record -g ./my_program

# 查看报告
sudo perf report

# 实时监控
sudo perf top
ftrace 跟踪
# 启用 ftrace
echo function_graph > /sys/kernel/debug/tracing/current_tracer
echo 1 > /sys/kernel/debug/tracing/tracing_on

# 运行程序后查看跟踪
cat /sys/kernel/debug/tracing/trace_pipe

# 停止跟踪
echo 0 > /sys/kernel/debug/tracing/tracing_on
9.2 实时性优化
PREEMPT_RT 补丁
# 下载 PREEMPT_RT 补丁
wget https://mirrors.edge.kernel.org/pub/linux/kernel/projects/rt/5.10/patch-5.10.78-rt54.patch.gz

# 应用补丁
zcat patch-5.10.78-rt54.patch.gz | patch -p1

# 配置实时内核
make menuconfig
# 选择: Preemption Model → Fully Preemptible Kernel (Real-Time)

# 编译并安装
make -j$(nproc)
sudo make modules_install
sudo make install
9.3 容器化部署
Docker 安装与配置
# 安装 Docker
sudo pacman -S docker

# 启动 Docker 服务
sudo systemctl enable docker
sudo systemctl start docker

# 将用户加入 docker 组
sudo usermod -aG docker $USER
# 需要重新登录
Dockerfile 示例
# Dockerfile
FROM archlinuxarm/base:latest

# 更新系统并安装依赖
RUN pacman -Syu –noconfirm && \
pacman -S –noconfirm python python-pip sqlite

# 创建应用目录
WORKDIR /app

# 复制应用代码
COPY . .

# 安装 Python 依赖
RUN pip install -r requirements.txt

# 暴露端口
EXPOSE 5000

# 启动命令
CMD [“python”, “web_interface.py”]
构建和运行容器
# 构建镜像
docker build -t iot-app .

# 运行容器
docker run -d \
–name iot-container \
-p 5000:5000 \
-v /dev:/dev \
-v /sys:/sys \
–privileged \
iot-app
9.4 持续集成/持续部署 (CI/CD)
GitLab CI 配置
# .gitlab-ci.yml
stages:
– build
– test
– deploy

variables:
ARCH: “aarch64”

build:
stage: build
image: archlinuxarm/base:latest
script:
– pacman -Syu –noconfirm
– pacman -S –noconfirm base-devel git python
– make
artifacts:
paths:
– build/

test:
stage: test
image: archlinuxarm/base:latest
script:
– python -m pytest tests/
dependencies:
– build

deploy:
stage: deploy
image: archlinuxarm/base:latest
script:
– ssh user@target-device “cd /opt/iot-app && git pull && sudo systemctl restart sensor-collector”
only:
– main
第十部分:总结与展望
10.1 学习路径建议
基础阶段
(1-2个月)
掌握 Linux 基础命令和系统管理
学习 C/Python 编程基础
理解嵌入式系统基本概念
进阶阶段
(2-3个月)
深入学习 Linux 内核和驱动开发
掌握各种通信协议(I2C, SPI, UART)
学习实时系统和性能优化
实战阶段
(3-6个月)
完成完整的物联网项目
学习安全加固和系统部署
掌握调试和故障排除技巧
10.2 推荐资源
官方文档
Arch Linux ARM 文档:
https://archlinuxarm.org/about
Linux 内核文档:
https://www.kernel.org/doc/html/latest/
Raspberry Pi 文档:
https://www.raspberrypi.com/documentation/
书籍推荐
《Linux设备驱动程序》(LDD3)
《嵌入式Linux系统开发技术详解》
《Python嵌入式开发实战》
在线课程
Coursera: “Embedded Systems”
edX: “Linux Foundation: Introduction to Embedded Linux”
Udemy: “Raspberry Pi Bootcamp”
10.3 社区与交流
Arch Linux ARM 论坛
:
https://archlinuxarm.org/forum
Raspberry Pi 官方论坛
:
https://forums.raspberrypi.com/
Stack Overflow
:使用标签 [arch-linux-arm], [embedded-linux]
GitHub
:关注相关开源项目
10.4 未来发展方向
边缘计算
:在设备端进行数据处理和分析
AI/ML 集成
:在嵌入式设备上运行轻量级机器学习模型
5G 与物联网
:利用 5G 网络实现低延迟通信
安全增强
:硬件级安全(TPM, Secure Boot)
云原生嵌入式
:Kubernetes 在边缘设备上的应用
结语
Arch Linux ARM 为嵌入式开发者提供了一个强大而灵活的平台。通过本培训,你已经从零开始掌握了嵌入式系统开发的核心技能。记住,实践是最好的老师,不断尝试新的项目和挑战,你将在这个领域不断成长。
关键要点回顾
:
Arch Linux ARM 的优势在于其轻量级和可定制性
从环境搭建到驱动开发,每一步都需要扎实的基础
实际项目是检验学习成果的最佳方式
安全性和性能优化是生产环境的关键
持续学习和社区参与是保持竞争力的关键
现在,开始你的嵌入式开发之旅吧!