示例代码
本文档介绍RS232、RS485、DI、DO、CAN 和 ADC 等接口的示例代码使用方法。
使用RS232-C代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/select.h>
#define PORT_SENDER "/dev/com3"
#define PORT_RECEIVER "/dev/com1"
#define BAUDRATE B115200
#define TIMEOUT_SEC 1
#define BUF_SIZE 256
int serial_open(const char *port) {
int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd < 0) {
perror("open serial failed");
return -1;
}
struct termios cfg;
tcgetattr(fd, &cfg);
cfmakeraw(&cfg);
cfg.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
cfg.c_iflag = 0;
cfg.c_oflag = 0;
cfg.c_lflag = 0;
cfg.c_cc[VMIN] = 0;
cfg.c_cc[VTIME] = TIMEOUT_SEC * 10;
tcsetattr(fd, TCSANOW, &cfg);
tcflush(fd, TCIOFLUSH);
return fd;
}
void sender(void) {
int fd = serial_open(PORT_SENDER);
if (fd < 0) return;
printf("Sender started: %s\n", PORT_SENDER);
int count = 0;
while (1) {
count++;
char msg[BUF_SIZE];
snprintf(msg, sizeof(msg), "Hello #%d", count);
tcflush(fd, TCIOFLUSH);
write(fd, msg, strlen(msg));
write(fd, "\n", 1);
printf("[Send] %s\n", msg);
usleep(100000);
char buf[BUF_SIZE] = {0};
int n = read(fd, buf, sizeof(buf)-1);
if (n > 0) {
buf[strcspn(buf, "\n")] = 0;
printf("[Got reply] %s\n", buf);
} else {
printf("[Timeout] No reply\n");
}
sleep(2);
}
close(fd);
}
void receiver(void) {
int fd = serial_open(PORT_RECEIVER);
if (fd < 0) return;
printf("Receiver started: %s, waiting...\n", PORT_RECEIVER);
while (1) {
char buf[BUF_SIZE] = {0};
int n = read(fd, buf, sizeof(buf)-1);
if (n > 0) {
buf[strcspn(buf, "\n")] = 0;
printf("[Received] %s\n", buf);
char ack[BUF_SIZE];
snprintf(ack, sizeof(ack), "ACK: %s\n", buf);
write(fd, ack, strlen(ack));
printf("[Reply] %s", ack);
}
usleep(10000);
}
close(fd);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s [sender|receiver]\n", argv[0]);
return 1;
}
if (!strcmp(argv[1], "sender")) {
sender();
} else if (!strcmp(argv[1], "receiver")) {
receiver();
} else {
fprintf(stderr, "Invalid mode\n");
return 1;
}
return 0;
}
使用RS232-Python代码
#!/usr/bin/env python3
import serial
import time
import sys
PORT_SENDER = "/dev/com3" # The port used by the sender
PORT_RECEIVER = "/dev/com1" # The port used by the receiver
BAUDRATE = 115200 # Set baud rate
TIMEOUT = 1 # The sender timed out waiting for a reply
def sender():
ser = None
try:
ser = serial.Serial(PORT_SENDER, BAUDRATE, timeout=TIMEOUT)
print(f"The sender has started, port {PORT_SENDER}")
count = 0
while True:
count += 1
msg = f"Hello #{count}"
ser.reset_input_buffer()
ser.reset_output_buffer()
ser.write((msg + '\n').encode('utf-8'))
print(f"[Send] {msg}")
time.sleep(0.1)
if ser.in_waiting > 0:
reply = ser.read(ser.in_waiting).decode('utf-8').strip()
print(f"[Got the reply] {reply}")
else:
print("[Timed out] Haven't received a reply")
time.sleep(2)
except KeyboardInterrupt:
print("\nThe sender has exited")
except Exception as e:
print(f"Serial port error: {e}")
finally:
if ser is not None:
ser.close()
def receiver():
ser = None
try:
ser = serial.Serial(PORT_RECEIVER, BAUDRATE, timeout=0.5)
ser.reset_input_buffer()
ser.reset_output_buffer()
print(f"The receiver has started, port {PORT_RECEIVER},Waiting to receive...")
while True:
if ser.in_waiting > 0:
data = ser.read(ser.in_waiting)
try:
text = data.decode('utf-8').strip()
print(f"[Got it] {text}")
reply = f"ACK: {text}"
ser.write((reply + '\n').encode('utf-8'))
print(f"[Reply] {reply}")
except UnicodeDecodeError:
print(f"[Got the raw data] {data.hex()}")
time.sleep(0.01)
except KeyboardInterrupt:
print("\nThe receiver has exited")
except Exception as e:
print(f"Serial port error: {e}")
finally:
if ser is not None:
ser.close()
def main():
if len(sys.argv) != 2:
print("Usage: python3 rs232.py [sender|receiver]")
sys.exit(1)
mode = sys.argv[1].lower()
if mode == "sender":
sender()
elif mode == "receiver":
receiver()
else:
print("Invalid mode, please choose sender or receiver")
sys.exit(1)
if __name__ == "__main__":
main()
使用RS485-C代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/select.h>
#define PORT_SENDER "/dev/com1"
#define PORT_RECEIVER "/dev/com2"
#define BAUDRATE B115200
#define TIMEOUT_SEC 1
#define BUF_SIZE 256
int serial_open(const char *port) {
int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd < 0) {
perror("open serial failed");
return -1;
}
struct termios cfg;
tcgetattr(fd, &cfg);
cfmakeraw(&cfg);
cfg.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
cfg.c_iflag = 0;
cfg.c_oflag = 0;
cfg.c_lflag = 0;
cfg.c_cc[VMIN] = 0;
cfg.c_cc[VTIME] = TIMEOUT_SEC * 10;
tcsetattr(fd, TCSANOW, &cfg);
tcflush(fd, TCIOFLUSH);
return fd;
}
void sender(void) {
int fd = serial_open(PORT_SENDER);
if (fd < 0) return;
printf("Sender started: %s\n", PORT_SENDER);
int count = 0;
while (1) {
count++;
char msg[BUF_SIZE];
snprintf(msg, sizeof(msg), "Hello #%d", count);
tcflush(fd, TCIOFLUSH);
write(fd, msg, strlen(msg));
write(fd, "\n", 1);
printf("[Send] %s\n", msg);
usleep(100000);
char buf[BUF_SIZE] = {0};
int n = read(fd, buf, sizeof(buf)-1);
if (n > 0) {
buf[strcspn(buf, "\n")] = 0;
printf("[Got reply] %s\n", buf);
} else {
printf("[Timeout] No reply\n");
}
sleep(2);
}
close(fd);
}
void receiver(void) {
int fd = serial_open(PORT_RECEIVER);
if (fd < 0) return;
printf("Receiver started: %s, waiting...\n", PORT_RECEIVER);
while (1) {
char buf[BUF_SIZE] = {0};
int n = read(fd, buf, sizeof(buf)-1);
if (n > 0) {
buf[strcspn(buf, "\n")] = 0;
printf("[Received] %s\n", buf);
char ack[BUF_SIZE];
snprintf(ack, sizeof(ack), "ACK: %s\n", buf);
write(fd, ack, strlen(ack));
printf("[Reply] %s", ack);
}
usleep(10000);
}
close(fd);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s [sender|receiver]\n", argv[0]);
return 1;
}
if (!strcmp(argv[1], "sender")) {
sender();
} else if (!strcmp(argv[1], "receiver")) {
receiver();
} else {
fprintf(stderr, "Invalid mode\n");
return 1;
}
return 0;
}
使用RS485-Python代码
#!/usr/bin/env python3
import serial
import time
import sys
PORT_SENDER = "/dev/com1" # The port used by the sender
PORT_RECEIVER = "/dev/com2" # The port used by the receiver
BAUDRATE = 115200 # Set baud rate
TIMEOUT = 1 # The sender timed out waiting for a reply
def sender():
ser = None
try:
ser = serial.Serial(PORT_SENDER, BAUDRATE, timeout=TIMEOUT)
print(f"The sender has started, port {PORT_SENDER}")
count = 0
while True:
count += 1
msg = f"Hello #{count}"
ser.reset_input_buffer()
ser.reset_output_buffer()
ser.write((msg + '\n').encode('utf-8'))
print(f"[Send] {msg}")
time.sleep(0.1)
if ser.in_waiting > 0:
reply = ser.read(ser.in_waiting).decode('utf-8').strip()
print(f"[Got a reply] {reply}")
else:
print("[Timed out] Haven't received a reply")
time.sleep(2)
except KeyboardInterrupt:
print("\nSender exited")
except Exception as e:
print(f"Failed to open the serial port: {e}")
finally:
if ser is not None:
ser.close()
def receiver():
ser = None
try:
ser = serial.Serial(PORT_RECEIVER, BAUDRATE, timeout=0.5)
ser.reset_input_buffer()
ser.reset_output_buffer()
print(f"The receiver has started, port {PORT_RECEIVER},Waiting to receive...")
while True:
if ser.in_waiting > 0:
data = ser.read(ser.in_waiting)
try:
text = data.decode('utf-8').strip()
print(f"[Got it] {text}")
reply = f"ACK: {text}"
ser.write((reply + '\n').encode('utf-8'))
print(f"[Reply] {reply}")
except UnicodeDecodeError:
print(f"[Got the raw data] {data.hex()}")
time.sleep(0.01)
except KeyboardInterrupt:
print("\nReceiver exited")
except Exception as e:
print(f"Failed to open the serial port: {e}")
finally:
if ser is not None:
ser.close()
def main():
if len(sys.argv) != 2:
print("Usage: python3 rs485.py [sender|receiver]")
sys.exit(1)
mode = sys.argv[1].lower()
if mode == "sender":
sender()
elif mode == "receiver":
receiver()
else:
print("Invalid mode, please choose sender or receiver")
sys.exit(1)
if __name__ == "__main__":
main()
使用DI-C代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
int gpios[] = {17,18,19,20};
const char* dis[] = {"DI4","DI5","DI6","DI7"};
int exit_flag = 0;
void sigint(int s)
{
exit_flag = 1;
printf("\nThe program has exited\n");
}
int get_di(int type, const void *arg)
{
char cmd[64], buf[128];
FILE *f;
if (type == 0)
{
int g = *(const int *)arg;
snprintf(cmd,64,"pinctrl get %d 2>/dev/null",g);
f = popen(cmd,"r");
if(!f || !fgets(buf,128,f))
{
if(f) pclose(f);
return -1;
}
pclose(f);
char *p = strchr(buf,'|');
if(!p) return -1;
while(*++p==' ');
char r[4];
sscanf(p,"%3s",r);
if(strcmp(r,"hi")==0) return 1;
if(strcmp(r,"lo")==0) return 0;
return -1;
}
else
{
const char *name = (const char *)arg;
snprintf(cmd,64,"sudo ed-gpio get %s 2>/dev/null",name);
f = popen(cmd,"r");
if(!f || !fgets(buf,32,f))
{
if(f) pclose(f);
return -1;
}
pclose(f);
return atoi(buf);
}
}
int main() {
signal(SIGINT, sigint);
while(!exit_flag) {
printf("==== DI0 ~ DI3 ====\n");
for(int i=0;i<4;i++) {
int v = get_di(0, &gpios[i]);
if(v>=0)
printf(" DI%d: %s -> %s\n",i, v ? "hi" : "lo", v ? "Invalid" : "Valid");
else
printf(" DI%d: Read failed\n",i);
}
printf("\n==== DI4 ~ DI7 ====\n");
for(int i=0;i<4;i++) {
int v = get_di(1, dis[i]);
if(v>=0)
printf(" %s: %s -> %s\n",dis[i], v ? "hi" : "lo", v ? "Invalid" : "Valid");
else
printf(" %s: Read failed\n",dis[i]);
}
printf("-----------------------\n");
sleep(2);
}
return 0;
}
使用DI-Python代码
#!/usr/bin/env python3
import subprocess
import time
DI_GPIO1 = [17, 18, 19, 20]
DI_GPIO2 = ["DI4", "DI5", "DI6", "DI7"]
def get_di_value(target, read_type):
try:
if read_type == "pinctrl":
# DI0~DI3
output = subprocess.check_output(
['pinctrl', 'get', str(target)],
text=True,
stderr=subprocess.DEVNULL
).strip()
if '|' not in output:
return (None, False)
after_pipe = output.split('|', 1)[1].strip()
level = after_pipe.split()[0]
if level not in ("hi", "lo"):
return (None, False)
return (level, level == "lo")
elif read_type == "edgpio":
# DI4~DI7
output = subprocess.check_output(
['sudo', 'ed-gpio', 'get', target],
text=True,
stderr=subprocess.DEVNULL
).strip()
level_num = int(output)
level_str = "lo" if level_num == 0 else "hi"
return (level_str, level_num == 0)
else:
return (None, False)
except Exception as e:
print(f"Read {target} failed: {e}")
return (None, False)
def print_di_status():
print("==== DI0 ~ DI3 ====")
for idx, gpio in enumerate(DI_GPIO1):
di_name = f"DI{idx}"
raw_val, active = get_di_value(gpio, "pinctrl")
if raw_val is None:
print(f" {di_name}: Read failed")
else:
print(f" {di_name}: {raw_val} -> {'Valid' if active else 'Invalid'}")
print("\n==== DI4 ~ DI7 ====")
for di_name in DI_GPIO2:
raw_val, active = get_di_value(di_name, "edgpio")
if raw_val is None:
print(f" {di_name}: Read failed")
else:
print(f" {di_name}: {raw_val} -> {'Valid' if active else 'Invalid'}")
def main():
try:
while True:
print_di_status()
print("-" * 30)
time.sleep(2)
except KeyboardInterrupt:
print("\n The program has exited.")
if __name__ == "__main__":
main()
使用DO-C代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
static volatile sig_atomic_t running = 1;
void handle_sigint(int sig) {
running = 0;
}
void set_do_level(const char *id, int level) {
char cmd[256];
if (id[0] == 'D') {
snprintf(cmd, sizeof(cmd), "sudo ed-gpio set %s %d > /dev/null 2>&1", id, level ? 1 : 0);
} else {
snprintf(cmd, sizeof(cmd), "pinctrl set %s op d%s > /dev/null 2>&1", id, level ? "h" : "l");
}
if (system(cmd) != 0) {
fprintf(stderr, "Failed to set %s\n", id);
}
}
int main() {
const char *gpios[] = {"12", "21", "22", "23"};
const char *donames[] = {"DO4", "DO5", "DO6", "DO7"};
int num_gpios = sizeof(gpios) / sizeof(gpios[0]);
int num_dos = sizeof(donames) / sizeof(donames[0]);
signal(SIGINT, handle_sigint);
while (running) {
// control DO0~DO3
for (int i = 0; i < num_gpios && running; i++) {
set_do_level(gpios[i], 1);
printf("DO%d set to high\n", i, gpios[i]);
sleep(2);
set_do_level(gpios[i], 0);
printf("DO%d set to low\n", i, gpios[i]);
sleep(2);
}
// control DO4~DO7
for (int i = 0; i < num_dos && running; i++) {
set_do_level(donames[i], 1);
printf("%s set to high \n", donames[i]);
sleep(2);
set_do_level(donames[i], 0);
printf("%s set to low\n", donames[i]);
sleep(2);
}
}
// set all DOs low before exiting
printf("\n when the program exits, set all DOs low \n");
for (int i = 0; i < num_gpios; i++) set_do_level(gpios[i], 0);
for (int i = 0; i < num_dos; i++) set_do_level(donames[i], 0);
return 0;
}
使用DO-Python代码
#!/usr/bin/env python3
import subprocess
import time
DO_GPIO1 = [12, 21, 22, 23]
DO_GPIO2 = ['DO4', 'DO5', 'DO6', 'DO7']
def set_do_level(do_id, level):
if isinstance(do_id, int):
if level == 'high':
cmd = ['pinctrl', 'set', str(do_id), 'op', 'dh']
elif level == 'low':
cmd = ['pinctrl', 'set', str(do_id), 'op', 'dl']
else:
raise ValueError("the level must be 'high' or 'low'")
try:
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError as e:
print(f"failed to set GPIO {do_id} to {level}: {e}")
elif isinstance(do_id, str) and do_id.startswith('DO'):
if level == 'high':
val = '1'
elif level == 'low':
val = '0'
else:
raise ValueError("the level must be 'high' or 'low'")
cmd = ['sudo', 'ed-gpio', 'set', do_id, val]
try:
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError as e:
print(f"failed to set GPIO {do_id} to {level}: {e}")
else:
raise ValueError("the do_id must be an integer GPIO number or a string in the format like 'DO4'")
def main():
try:
while True:
#control DO0 ~ DO3
for idx, gpio in enumerate(DO_GPIO1):
set_do_level(gpio, 'high')
print(f"DO{idx} set to high")
time.sleep(2)
set_do_level(gpio, 'low')
print(f"DO{idx} set to low")
time.sleep(2)
#control DO4 ~ DO7
for name in DO_GPIO2:
set_do_level(name, 'high')
print(f"{name} set to high")
time.sleep(2)
set_do_level(name, 'low')
print(f"{name} set to low")
time.sleep(2)
except KeyboardInterrupt:
print("\n the program exits")
# set all DOs low
for gpio in DO_GPIO1:
set_do_level(gpio, 'low')
for name in DO_GPIO2:
set_do_level(name, 'low')
if __name__ == "__main__":
main()
使用CAN-C代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define BITRATE 125000
#define MAX_CMD_LEN 512
#define MAX_ERR_LEN 1024
/**
* Execute the command and capture standard error (including output), then return the exit status.
* @param cmd The command to execute
* @param errmsg Output buffer (stores stdout + stderr of the command)
* @param errlen Buffer size
* @return 0 for success, -1 for failure (including popen/pclose failure or non-zero command exit code)
*/
int run_cmd(const char *cmd, char *errmsg, size_t errlen) {
char full_cmd[MAX_CMD_LEN];
snprintf(full_cmd, sizeof(full_cmd), "%s 2>&1", cmd);
FILE *fp = popen(full_cmd, "r");
if (!fp) {
snprintf(errmsg, errlen, "popen failed");
return -1;
}
size_t n = fread(errmsg, 1, errlen - 1, fp);
errmsg[n] = '\0';
int status = pclose(fp);
if (status == -1) {
snprintf(errmsg, errlen, "pclose failed");
return -1;
}
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
return 0;
}
return -1;
}
void setup_can(const char *can_dev) {
char cmd[MAX_CMD_LEN];
char errmsg[MAX_ERR_LEN];
snprintf(cmd, sizeof(cmd), "sudo ip link set %s type can bitrate %d", can_dev, BITRATE);
if (run_cmd(cmd, errmsg, sizeof(errmsg)) != 0) {
// If the error message contains "Device or resource busy", ignore it and continue.
if (strstr(errmsg, "Device or resource busy") == NULL) {
fprintf(stderr, "Initialization failed (setting baud rate): %s\n", errmsg);
exit(EXIT_FAILURE);
}
}
snprintf(cmd, sizeof(cmd), "sudo ip link set %s up", can_dev);
if (run_cmd(cmd, errmsg, sizeof(errmsg)) != 0) {
if (strstr(errmsg, "Device or resource busy") == NULL) {
fprintf(stderr, "Initialization failed (starting device): %s\n", errmsg);
exit(EXIT_FAILURE);
}
}
}
void can_send(const char *can_dev, const char *can_id, const char *data) {
char cmd[MAX_CMD_LEN];
char errmsg[MAX_ERR_LEN];
printf("Send frame: %s#%s (device %s)\n", can_id, data, can_dev);
snprintf(cmd, sizeof(cmd), "cansend %s %s#%s", can_dev, can_id, data);
if (run_cmd(cmd, errmsg, sizeof(errmsg)) != 0) {
fprintf(stderr, "Send failed: %s\n", errmsg);
exit(EXIT_FAILURE);
}
printf("Send succeeded\n");
}
void can_receive(const char *can_dev) {
char cmd[MAX_CMD_LEN];
snprintf(cmd, sizeof(cmd), "candump %s", can_dev);
printf("Monitor %s,Press Ctrl+C to exit\n", can_dev);
int ret = system(cmd);
if (ret == -1) {
perror("system");
exit(EXIT_FAILURE);
}
printf("\n Stopped receiving \n");
}
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage: %s [send|recv] [canb0|canb1] [ID] [DATA]\n", "can");
fprintf(stderr, "Example: %s send canb1 123 11223344\n", "can");
fprintf(stderr, "Example: %s recv canb0\n", "can");
return EXIT_FAILURE;
}
const char *mode = argv[1];
const char *can_dev = argv[2];
if (strcmp(can_dev, "canb0") != 0 && strcmp(can_dev, "canb1") != 0) {
fprintf(stderr, "Invalid device: %s,please use canb0 or canb1\n", can_dev);
return EXIT_FAILURE;
}
setup_can(can_dev);
if (strcmp(mode, "recv") == 0) {
if (argc != 3) {
fprintf(stderr, "Receive mode usage: %s recv [canb0|canb1]\n", argv[0]);
return EXIT_FAILURE;
}
can_receive(can_dev);
} else if (strcmp(mode, "send") == 0) {
if (argc != 5) {
fprintf(stderr, "Send mode usage: %s send [canb0|canb1] <ID> <DATA>\n", argv[0]);
return EXIT_FAILURE;
}
const char *can_id = argv[3];
const char *data = argv[4];
can_send(can_dev, can_id, data);
} else {
fprintf(stderr, "Unknown mode: %s, please use send or recv \n", mode);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
使用CAN-Python代码
import subprocess
import sys
BITRATE = 125000
def setup_can(can_dev):
for cmd in [
["sudo", "ip", "link", "set", can_dev, "type", "can", "bitrate", str(BITRATE)],
["sudo", "ip", "link", "set", can_dev, "up"]
]:
ret = subprocess.run(cmd, capture_output=True, text=True)
if ret.returncode != 0:
if "Device or resource busy" in ret.stderr:
continue
print(f"Initialization failed: {ret.stderr}")
sys.exit(1)
def can_send(can_dev, can_id, data):
frame = f"{can_id}#{data}"
print(f"Send frame: {frame} (Device {can_dev})")
ret = subprocess.run(["cansend", can_dev, frame], capture_output=True, text=True)
if ret.returncode != 0:
print(f"Send failed: {ret.stderr}")
sys.exit(1)
print("Send succeeded")
def can_receive(can_dev):
print(f"Monitor {can_dev}, Press Ctrl+C to exit")
try:
subprocess.run(["candump", can_dev], check=True)
except KeyboardInterrupt:
print("\n Stopped receiving")
def main():
if len(sys.argv) < 3:
print("Usage: python can.py [send|recv] [canb0|canb1] [ID] [DATA]")
print("Example: python can.py send canb1 123 11223344")
print("Example: python can.py recv canb0")
sys.exit(1)
mode = sys.argv[1]
can_dev = sys.argv[2]
# Validate device name
if can_dev not in ["canb0", "canb1"]:
print(f"Invalid device: {can_dev}, Please use canb0 or canb1")
sys.exit(1)
setup_can(can_dev)
if mode == "recv":
if len(sys.argv) != 3:
print("Receive mode usage: python can.py recv [canb0|canb1]")
sys.exit(1)
can_receive(can_dev)
elif mode == "send":
if len(sys.argv) != 5:
print("Send mode usage: python can.py send [canb0|canb1] <ID> <DATA>")
sys.exit(1)
can_id = sys.argv[3]
data = sys.argv[4]
can_send(can_dev, can_id, data)
else:
print(f"Unknown mode: {mode}, Please use send or recv")
sys.exit(1)
if __name__ == "__main__":
main()
使用ADC-C代码
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#define CONFIG "/boot/firmware/config.txt"
static const char *CHANNELS[] = {"cha", "chb", "chc", "chd"};
static const char *LABELS[] = {"V0", "V1", "A0", "A1"};
/* Backup configuration file (generate .bak_timestamp) */
static void backup(void) {
char ts[32], cmd[256];
time_t t = time(NULL);
strftime(ts, sizeof(ts), "%Y%m%d_%H%M%S", localtime(&t));
snprintf(cmd, sizeof(cmd), "cp %s %s.bak_%s", CONFIG, CONFIG, ts);
system(cmd);
}
/* Read file into line array, return line count */
static int read_file(const char *path, char ***lines) {
FILE *fp = fopen(path, "r");
if (!fp) return -1;
char **arr = NULL, *line = NULL;
size_t len = 0;
int cnt = 0;
while (getline(&line, &len, fp) != -1) {
arr = realloc(arr, (cnt + 1) * sizeof(char *));
arr[cnt++] = strdup(line);
}
free(line);
fclose(fp);
*lines = arr;
return cnt;
}
/* Write back to file */
static int write_file(const char *path, char **lines, int cnt) {
FILE *fp = fopen(path, "w");
if (!fp) return -1;
for (int i = 0; i < cnt; i++) fputs(lines[i], fp);
fclose(fp);
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <cha|chb|chc|chd> <0-6>\n", argv[0]);
return 1;
}
char *ch = argv[1];
int val = atoi(argv[2]);
if (val < 0 || val > 6) {
fprintf(stderr, "Value must be 0~6\n");
return 1;
}
int idx = -1;
for (int i = 0; i < 4; i++)
if (strcmp(ch, CHANNELS[i]) == 0) { idx = i; break; }
if (idx == -1) {
fprintf(stderr, "Unknown channel\n");
return 1;
}
backup();
char **lines = NULL;
int n = read_file(CONFIG, &lines);
if (n <= 0) {
fprintf(stderr, "Failed to read configuration\n");
return 1;
}
/* Locate [all] section */
int start = -1, end = n;
for (int i = 0; i < n; i++) {
char *p = lines[i];
while (*p == ' ' || *p == '\t') p++;
if (strncasecmp(p, "[all]", 5) == 0) { start = i; break; }
}
if (start == -1) {
fprintf(stderr, "[all] section not found \n");
goto cleanup;
}
for (int i = start + 1; i < n; i++) {
char *p = lines[i];
while (*p == ' ' || *p == '\t') p++;
if (*p == '[') {
char *e = p + strlen(p) - 1;
while (e > p && (*e == ' ' || *e == '\t' || *e == '\n')) e--;
if (*e == ']') { end = i; break; }
}
}
char pat[64];
snprintf(pat, sizeof(pat), "dtparam=%s_datarate=", ch);
int ptr = start + 1;
while (ptr < end) {
if (strncasecmp(lines[ptr], pat, strlen(pat)) == 0) {
// Free current line memory
free(lines[ptr]);
// Shift array forward to overwrite and delete line
for (int j = ptr; j < n - 1; j++) {
lines[j] = lines[j + 1];
}
n--;
end--;
} else {
ptr++;
}
}
if (val != 4) {
char new_line[256];
snprintf(new_line, sizeof(new_line), "dtparam=%s_datarate=%d\n", ch, val);
lines = realloc(lines, (n + 1) * sizeof(char *));
for (int i = n; i > end; i--) {
lines[i] = lines[i - 1];
}
lines[end] = strdup(new_line);
n++;
}
if (write_file(CONFIG, lines, n) != 0) {
fprintf(stderr, "Failed to write to file\n");
goto cleanup;
}
const char *val_str[] = {"0","1","2","3","Default(1600sps)","5","6"};
printf("Modified sampling rate of channel %s to %s\n", LABELS[idx], val_str[val]);
printf("Please run 'sudo reboot' to apply changes\n");
cleanup:
for (int i = 0; i < n; i++) free(lines[i]);
free(lines);
return 0;
}
使用ADC-Python代码
#!/usr/bin/env python3
import sys
import shutil
import re
from datetime import datetime
CONFIG = "/boot/firmware/config.txt"
CHANNELS = {"cha": "V0", "chb": "V1", "chc": "A0", "chd": "A1"}
def main():
if len(sys.argv) != 3:
print("Usage: sudo python3 adc.py <channel> <value>")
print("Channels: cha chb chc chd, value: 0~6 (4 is default, will delete the line)")
sys.exit(1)
ch, val_str = sys.argv[1], sys.argv[2]
ch = ch.lower()
if ch not in CHANNELS:
print(f"Error: unknown channel '{ch}'", file=sys.stderr)
sys.exit(1)
try:
val = int(val_str)
if val < 0 or val > 6:
raise ValueError
except ValueError:
print("Value must be an integer from 0 to 6", file=sys.stderr)
sys.exit(1)
# Backup configuration file
shutil.copy2(CONFIG, f"{CONFIG}.bak_{datetime.now():%Y%m%d_%H%M%S}")
with open(CONFIG, 'r') as f:
lines = f.readlines()
# Locate [all] section
all_start = None
for i, line in enumerate(lines):
if line.strip().lower() == '[all]':
all_start = i
break
if all_start is None:
print("[all] section not found", file=sys.stderr)
sys.exit(1)
# Determine end of [all] section (until next [xxx] or end of file)
all_end = len(lines)
for i in range(all_start + 1, len(lines)):
if lines[i].strip().startswith('[') and lines[i].strip().endswith(']'):
all_end = i
break
# Find and process the datarate line for this channel
found = False
for i in range(all_start + 1, all_end):
line = lines[i]
m = re.match(r'dtparam\s*=\s*' + ch + r'_datarate\s*=\s*(\d+)', line, re.IGNORECASE)
if m:
found = True
if val == 4:
del lines[i] # Delete line (restore default)
else:
lines[i] = re.sub(r'(\d+)', str(val), line, count=1) # Update value
break
if not found and val != 4:
# Not found and not default, insert new line at end of section
lines.insert(all_end, f"dtparam={ch}_datarate={val}\n")
# Write back to file
with open(CONFIG, 'w') as f:
f.writelines(lines)
print(f"Modified sampling rate of channel {CHANNELS[ch]} to {val if val != 4 else 'default (1600sps)'}")
print("Please run 'sudo reboot' to apply changes")
if __name__ == "__main__":
main()
