【问题标题】:Does Arduino Uno/OSEPP Uno have enough memory to create a servo array?Arduino Uno/OSEPP Uno 是否有足够的内存来创建伺服阵列?
【发布时间】:2017-01-05 04:32:26
【问题描述】:

我很不擅长编码(我知道基础知识),我正在尝试在 Arduino 中创建一个伺服器阵列,以通过带有处理的串行进行控制。我隐约记得 Arduino 微控制器的内存非常有限,所以我不确定创建一个伺服对象数组是否可行。这是我到目前为止的代码:

#include <Servo.h>

Servo[] servos = new Servo[6]; //holds the servo objects

int[] servoPos = {90,112,149,45,75,8}; //holds the current position of each servo

char serialVal; //store the serialValue received from serial

void setup()
{
  for(int i = 0; i < servos.length; i++) //attach servos to pins
  {
    servos[i].attach(i+8);
  }

  Serial.begin(115200); //initialize serial
}

Arduino Uno 板是否能够支持该阵列并像在 Java 中一样使用它?在此之前,我一直在单独创建每个对象,这样打字和阅读效率非常低且耗时。

另外,如果有任何事情会阻止此代码执行,请告诉我。感谢您的帮助。

【问题讨论】:

  • Servo 数组应为:Servo servos[6];。这将创建 6 个元素的数组并调用默认构造函数,因为底层语言是 C++。

标签: arrays arduino arduino-uno servo


【解决方案1】:

我的建议是启动您的 Arduino IDE 并尝试一下。首先你会发现你的代码有一些问题:

您的数组语法不正确。例如:

int[] servoPos = {90,112,149,45,75,8}; //holds the current position of each servo

应该写成:

int servoPos[] = {90,112,149,45,75,8}; //holds the current position of each servo

我猜这个servos.length 是Java 的东西?相反,您应该通过以下方式确定该值:

sizeof(servos) / sizeof(servos[0])

编译完成后,您会在 Arduino IDE 窗口底部的黑色控制台窗口中看到一条消息:

Sketch 使用 2408 字节 (7%) 的程序存储空间。最大值为 32256 字节。 全局变量使用 242 字节 (11%) 的动态内存,为局部变量留下 1806 字节。最大为 2048 字节。

这样您就可以了解内存使用情况。要在运行时检查可用内存,我使用这个库: https://github.com/McNeight/MemoryFree

【讨论】:

  • 那么长度是 sizeof(servos) 还是 sizeof(servos[0])?
  • 伺服阵列的语法是否也必须更改?
  • @JasonChen sizeof(servos)servos 数组的大小(以字节为单位),sizeof(servos[0]) 是一个元素的大小(以字节为单位)。所以你必须将数组的大小除以元素的大小来获得元素的数量。但是有可能获得the number of elements by template function。伺服数组的语法也必须改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
  • 2013-10-22
  • 2013-06-05
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多