// Определение команд и соответствующих функций
Command commands[] = {
{"whoami", whoami},
{"uname", uname},
{"help", help},
{"kill 0xff", panic}
};
const int numCommands = sizeof(commands) / sizeof(commands[0]);
void executeCommand(const String& command) {
for (int i = 0; i < numCommands; i++) {
if (command.equals(commands[i].command)) {
commands[i].function(); // Вызов соответствующей функции
return;
}
}
Serial.println("Unknown command. Type 'help' for a list of commands.\n#!/ ");
}
// Вывод логов с задержками
for (int i = 0; i < numLines; i++) {
Serial.println(bootlog[i]);
delay(dlclock); // Задержка между строками, параметр указан в kernel.h
}
Serial.println("\n#!/ ");
}
void loop() {
// Проверка, есть ли данные для чтения
if (Serial.available() > 0) {
// Чтение входящих данных
String incomingMessage = Serial.readStringUntil('\n');
incomingMessage.trim();
code
executeCommand(incomingMessage);
}
else {
Serial.print("");
}
}
сделай чтобы код использовал меньше оперативной памяти
Reducing the memory usage of your Arduino code involves optimizing data storage and computation. Here are a few suggestions to achieve this:
Flash Memory for Constant Data: Use PROGMEM to store constant data in flash memory rather than SRAM. This is ideal for the bootlog array, which doesn't change at runtime.
String Manipulation: Replace String usage with C-style string operations. Arduino String instances can lead to memory fragmentation.
Reduce Functionality: Remove unnecessary features or commands if they aren't needed.
Here's your code with a few optimizations:
cpp
#include <Arduino.h>
#include <src/kernel.h>
#include <src/Utils.h> // Ensure these files provide the correct functionality
#include <src/modules.h>
// Store the bootlog in program memory (flash)
const char bootlog[] PROGMEM = R"(
[ 0.000000] Booting Arduino...
[ 0.050000] Initializing system components...
[ 0.100000] CPU: ATmega328P @ 16 MHz
[ 0.150000] Memory: 2 KB SRAM, 32 KB Flash
[ 0.200000] I/O Ports: Initialized
[ 0.250000] UART: Serial communication started at 9600 baud
[ 0.300000] I2C: Bus initialized
[ 0.350000] SPI: Bus initialized
[ 0.400000] Timer: Configured for millis() and delay()
[ 0.450000] Watchdog: Disabled (default settings)
[ 0.500000] Analog pins: Initialized and ready
[ 0.550000] PWM: Pulse Width Modulation channels active
[ 0.600000] EEPROM: Read/Write initialized
[ 0.650000] LED: Blink test initiated
[ 0.700000] Sensors: Initialized (Analog/Digital)
[ 0.750000] External Interrupts: Enabled
[ 0.800000] External memory modules: Not detected
[ 0.850000] Configuration: Default settings loaded
[ 0.900000] Firmware Version: 1.0.0
[ 0.950000] Bootloader: Version 2.0.0
[ 1.000000] Setup complete. Entering user code...
[ 1.050000] [INFO] Main loop started. Waiting for events.
[ 1.100000] [INFO] System operational
[ 1.150000] [DEBUG] GPIO: Pin 13 set to HIGH
[ 1.200000] [DEBUG] Analog Read: A0 = 512
[ 1.250000] [DEBUG] Sensor Data: Temperature = 25°C
[ 1.300000] [DEBUG] Timer Status: Active
[ 1.350000] [DEBUG] PWM Output: 128
[ 1.400000] [DEBUG] EEPROM Status: No errors
[ 1.450000] [DEBUG] Watchdog Timer: Not active
[ 1.500000] [INFO] System running normally
[ 1.550000] [INFO] System uptime: 0 hours, 1 minutes, 30 seconds
[ 1.600000] [DEBUG] External Device Status: No errors
[ 1.650000] [INFO] Network: Not connected
[ 1.700000] [INFO] Power Supply: Voltage stable at 5V
[ 1.750000] [DEBUG] Boot sequence completed successfully
[ 1.800000] [INFO] Ready for user input or command execution
)";
typedef void (*CommandFunction)(); // Typedef for function pointer
struct Command {
const char* command;
CommandFunction function;
};
// Command array, functions assumed to exist
Command commands[] = {
{"whoami", whoami},
{"uname", uname},
{"help", help},
{"kill 0xff", panic}
};
const int numCommands = sizeof(commands) / sizeof(commands[0]);
void executeCommand(const char* command) {
for (int i = 0; i < numCommands; i++) {
if (strcmp(command, commands[i].command) == 0) {
commands[i].function();
return;
}
}
Serial.println(F("Unknown command. Type 'help' for a list of commands.\n#!/ "));
}
void setup() {
Serial.begin(SerialPort);
pinMode(DefaultLed, OUTPUT);
// Read from program memory and print lines
const char* ptr = bootlog;
char lineBuffer[80];
while (pgm_read_byte(ptr)) {
int len = strcspn_P(ptr, PSTR("\n"));
strncpy_P(lineBuffer, ptr, len);
lineBuffer[len] = '\0';
Serial.println(lineBuffer);
delay(dlclock);
ptr += len + 1;
}
Serial.println(F("\n#!/ "));
}
void loop() {
if (Serial.available() > 0) {
char incomingMessage[50];
Serial.readBytesUntil('\n', incomingMessage, sizeof(incomingMessage) - 1);
incomingMessage[strcspn(incomingMessage, "\r\n")] = 0; // Strip newline
executeCommand(incomingMessage);
}
}
Key Changes:
PROGMEM for Bootlog: Bootlog data is stored in flash, saving SRAM.
C-Style Strings: Use C-style strings and strcmp for command execution, reducing memory usage.
Fixed Buffers: Use fixed-size character arrays to handle input commands.
These changes should help reduce RAM usage considerably by relying more on program memory and efficient string handling.
To ensure that your Arduino code uses minimum memory while correctly printing to the serial port, you can make use of memory-efficient techniques like using PROGMEM for static data, and dealing with strings using fixed-size character arrays instead of the Arduino String class. Here is how you can modify your code:
cpp
#include <Arduino.h>
#include <src/kernel.h> // Assuming kernel.h defines dlclock and other needed parameters
#include <src/Utils.h> // Assuming this provides necessary functions
#include <src/modules.h> // Assuming this provides necessary functions
// Store the bootlog in program memory (flash)
const char bootlog[] PROGMEM =
"[ 0.000000] Booting Arduino...\n"
"[ 0.050000] Initializing system components...\n"
"[ 0.100000] CPU: ATmega328P @ 16 MHz\n"
"[ 0.150000] Memory: 2 KB SRAM, 32 KB Flash\n"
"[ 0.200000] I/O Ports: Initialized\n"
"[ 0.250000] UART: Serial communication started at 9600 baud\n"
"[ 0.300000] I2C: Bus initialized\n"
"[ 0.350000] SPI: Bus initialized\n"
"[ 0.400000] Timer: Configured for millis() and delay()\n"
"[ 0.450000] Watchdog: Disabled (default settings)\n"
"[ 0.500000] Analog pins: Initialized and ready\n"
"[ 0.550000] PWM: Pulse Width Modulation channels active\n"
"[ 0.600000] EEPROM: Read/Write initialized\n"
"[ 0.650000] LED: Blink test initiated\n"
"[ 0.700000] Sensors: Initialized (Analog/Digital)\n"
"[ 0.750000] External Interrupts: Enabled\n"
"[ 0.800000] External memory modules: Not detected\n"
"[ 0.850000] Configuration: Default settings loaded\n"
"[ 0.900000] Firmware Version: 1.0.0\n"
"[ 0.950000] Bootloader: Version 2.0.0\n"
"[ 1.000000] Setup complete. Entering user code...\n"
"[ 1.050000] [INFO] Main loop started. Waiting for events.\n"
"[ 1.100000] [INFO] System operational\n"
"[ 1.150000] [DEBUG] GPIO: Pin 13 set to HIGH\n"
"[ 1.200000] [DEBUG] Analog Read: A0 = 512\n"
"[ 1.250000] [DEBUG] Sensor Data: Temperature = 25°C\n"
"[ 1.300000] [DEBUG] Timer Status: Active\n"
"[ 1.350000] [DEBUG] PWM Output: 128\n"
"[ 1.400000] [DEBUG] EEPROM Status: No errors\n"
"[ 1.450000] [DEBUG] Watchdog Timer: Not active\n"
"[ 1.500000] [INFO] System running normally\n"
"[ 1.550000] [INFO] System uptime: 0 hours, 1 minutes, 30 seconds\n"
"[ 1.600000] [DEBUG] External Device Status: No errors\n"
"[ 1.650000] [INFO] Network: Not connected\n"
"[ 1.700000] [INFO] Power Supply: Voltage stable at 5V\n"
"[ 1.750000] [DEBUG] Boot sequence completed successfully\n"
"[ 1.800000] [INFO] Ready for user input or command execution\n";
typedef void (*CommandFunction)(); // Typedef for function pointer
struct Command {
const char* command;
CommandFunction function;
};
// Define your commands and their associated functions
Command commands[] = {
{"whoami", whoami},
{"uname", uname},
{"help", help},
{"kill 0xff", panic}
};
const int numCommands = sizeof(commands) / sizeof(commands[0]);
void executeCommand(const char* command) {
for (int i = 0; i < numCommands; i++) {
if (strcmp(command, commands[i].command) == 0) {
commands[i].function();
return;
}
}
Serial.println(F("Unknown command. Type 'help' for a list of commands.\n#!/ "));
}
void setup() {
Serial.begin(9600);
pinMode(DefaultLed, OUTPUT);
// Read and print lines from program memory
char lineBuffer[100]; // Buffer to hold each line from the bootlog
const char *ptr = bootlog; // Pointer to move through the bootlog
while (pgm_read_byte(ptr) != '\0') { // Until the end of the string
int len = strcspn_P(ptr, PSTR("\n")); // Find the length of the line
strncpy_P(lineBuffer, ptr, len); // Copy from program memory
lineBuffer[len] = '\0'; // Null-terminate the line
Serial.println(lineBuffer); // Print the line
delay(dlclock); // Delay defined in kernel.h
ptr += len + 1; // Move pointer to start of next line
}
Serial.println(F("\n#!/ "));
}
void loop() {
if (Serial.available() > 0) {
char incomingMessage[50];
Serial.readBytesUntil('\n', incomingMessage, sizeof(incomingMessage) - 1);
incomingMessage[strcspn(incomingMessage, "\r\n")] = 0; // Strip newline
executeCommand(incomingMessage);
}
}
Key Points:
PROGMEM: The entire bootlog is stored in flash memory to save RAM. The data is retrieved using functions such as strncpy_P() to copy strings from flash to a buffer in RAM.
String Handling: Use C strings for handling incoming messages. This avoids the overhead and potential memory fragmentation issues that can occur with the Arduino String class.
Efficiency in Command Handling: Use a direct strcmp comparison for command execution.
By using PROGMEM for the bootlog and handling incoming commands with small, fixed-size buffers, this setup minimizes RAM usage while maintaining correct serial communication.
// Определение команд и соответствующих функций
Command commands[] = {
{"whoami", whoami},
{"uname", uname},
{"help", help},
{"kill 0xff", panic}
};
const int numCommands = sizeof(commands) / sizeof(commands[0]);
void executeCommand(const String& command) {
for (int i = 0; i < numCommands; i++) {
if (command.equals(commands[i].command)) {
commands[i].function(); // Вызов соответствующей функции
return;
}
}
Serial.println("Unknown command. Type 'help' for a list of commands.");
Serial.print("#!/ ");
}
// Вывод логов с задержками
for (int i = 0; i < numLines; i++) {
Serial.println(bootlog[i]);
delay(dlclock); // Задержка между строками, параметр указан в kernel.h
}
Serial.println("");
Serial.print("#!/ ");
}
void loop() {
// Проверка, есть ли данные для чтения
if (Serial.available() > 0) {
// Чтение входящих данных
String incomingMessage = Serial.readStringUntil('\n');
incomingMessage.trim();
code
executeCommand(incomingMessage);
}
else {
Serial.print("");
}
}
To reduce memory consumption in your Arduino sketch while maintaining functionality, we should replace the String usage with C-style strings, and utilize PROGMEM to store constant data like bootlog in the flash memory instead of SRAM. These two changes will help make the most of the limited memory resources available on the microcontroller.
Here's how you can rewrite your code to achieve these improvements:
cpp
#include <Arduino.h>
#include <src/kernel.h> // Assumed to contain necessary macros like dlclock
#include <src/Utils.h>
#include <src/modules.h>
// Store bootlog messages in flash memory with PROGMEM
const char bootlog[] PROGMEM =
"[ 0.000000] Booting Arduino...\n"
"[ 0.050000] Initializing system components...\n"
"[ 0.100000] CPU: ATmega328P @ 16 MHz\n"
"[ 0.150000] Memory: 2 KB SRAM, 32 KB Flash\n"
"[ 0.200000] I/O Ports: Initialized\n"
"[ 0.250000] UART: Serial communication started at 9600 baud\n"
"[ 0.300000] I2C: Bus initialized\n"
"[ 0.350000] SPI: Bus initialized\n"
"[ 0.400000] Timer: Configured for millis() and delay()\n"
"[ 0.450000] Watchdog: Disabled (default settings)\n"
"[ 0.500000] Analog pins: Initialized and ready\n"
"[ 0.550000] PWM: Pulse Width Modulation channels active\n"
"[ 0.600000] EEPROM: Read/Write initialized\n"
"[ 0.650000] LED: Blink test initiated\n"
"[ 0.700000] Sensors: Initialized (Analog/Digital)\n"
"[ 0.750000] External Interrupts: Enabled\n"
"[ 0.800000] External memory modules: Not detected\n"
"[ 0.850000] Configuration: Default settings loaded\n"
"[ 0.900000] Firmware Version: 1.0.0\n"
"[ 0.950000] Bootloader: Version 2.0.0\n"
"[ 1.000000] Setup complete. Entering user code...\n"
"[ 1.050000] [INFO] Main loop started. Waiting for events.\n"
"[ 1.100000] [INFO] System operational\n"
"[ 1.150000] [DEBUG] GPIO: Pin 13 set to HIGH\n"
"[ 1.200000] [DEBUG] Analog Read: A0 = 512\n"
"[ 1.250000] [DEBUG] Sensor Data: Temperature = 25°C\n"
"[ 1.300000] [DEBUG] Timer Status: Active\n"
"[ 1.350000] [DEBUG] PWM Output: 128\n"
"[ 1.400000] [DEBUG] EEPROM Status: No errors\n"
"[ 1.450000] [DEBUG] Watchdog Timer: Not active\n"
"[ 1.500000] [INFO] System running normally\n"
"[ 1.550000] [INFO] System uptime: 0 hours, 1 minutes, 30 seconds\n"
"[ 1.600000] [DEBUG] External Device Status: No errors\n"
"[ 1.650000] [INFO] Network: Not connected\n"
"[ 1.700000] [INFO] Power Supply: Voltage stable at 5V\n"
"[ 1.750000] [DEBUG] Boot sequence completed successfully\n"
"[ 1.800000] [INFO] Ready for user input or command execution\n";
typedef void (*CommandFunction)(); // Define function pointer type
struct Command {
const char* command;
CommandFunction function;
};
// Define commands and their associated functions
Command commands[] = {
{"whoami", whoami},
{"uname", uname},
{"help", help},
{"kill 0xff", panic}
};
const int numCommands = sizeof(commands) / sizeof(commands[0]);
void executeCommand(const char* command) {
for (int i = 0; i < numCommands; i++) {
if (strcmp(command, commands[i].command) == 0) {
commands[i].function(); // Call the associated function
return;
}
}
Serial.println("Unknown command. Type 'help' for a list of commands.");
Serial.print("#!/ ");
}
void setup() {
// Initialize the serial port
Serial.begin(9600);
pinMode(DefaultLed, OUTPUT);
// Output bootlog with delays
char lineBuffer[100]; // Buffer to hold lines from flash memory
const char* ptr = bootlog;
while (pgm_read_byte(ptr) != '\0') {
int len = strcspn_P(ptr, PSTR("\n"));
strncpy_P(lineBuffer, ptr, len);
lineBuffer[len] = '\0';
Serial.println(lineBuffer);
delay(dlclock); // Delay between lines, defined in kernel.h
ptr += len + 1; // Move pointer to next line
}
Serial.println("");
Serial.print("#!/ ");
}
void loop() {
// Check if there is data to read
if (Serial.available() > 0) {
char incomingMessage[50];
Serial.readBytesUntil('\n', incomingMessage, sizeof(incomingMessage) - 1);
incomingMessage[strcspn(incomingMessage, "\r\n")] = '\0'; // Strip newline
executeCommand(incomingMessage);
}
}
Key Changes
Using PROGMEM: The bootlog array is stored in the flash memory. This reduces SRAM usage significantly.
Replacing String with C-Strings: Incoming commands are now processed using a fixed-size character array to prevent memory fragmentation.
Efficient Flash Access: Use functions like strncpy_P to copy strings out of flash into RAM efficiently.
This configuration should help you save memory and provide robust serial port functionality. Make sure that your actual command handling functions and system-specific details from the header files (kernel.h and others) are correctly implemented.