2011年12月22日星期四

在Arduino IDE里直接编写类

Arduino支持C/C++,因此理所当然的支持C++的class,如果是经常要用到的类,可以把它们封装成类库,便于日后调用,关于类库的编写,请参见坛子里其它帖子。有时候,有些class不一定是经常要用到的,直接跟主程序搁一起就可以。

编写的方式有很多种,可以用C++的IDE来写,比如VS Studio、Eclipse、Code::Blocks等等,也可以用像Notepad、Notepad2、Source Insight等文本工具,下面要介绍的方法是直接采用arduino的IDE,目的是帮助大家更加熟悉它。

Arduino的IDE支持多文件管理,因此我们可以利用它来编写类。下面我们以建立一个Color类的例子来描述创建经过。

打开IDE,在菜单栏下面有一排button,最右边那个箭头样式的就是用来创建新的tab页,也就是建立一个新的文件,
arduino IDE

单击它之后,便会出现一个提示你键入文件名的对话框,在这里写入文件名。我们先建立类的头文件Color.h,因此敲入Color.h,注意,一定不要忘了文件的扩展名.h,不然IDE会自动加上arduino的扩展名.pde的。
file name


接着我们在Color.h页中编写Color类的头文件,代码如下
/*
  颜色类,可以分别设置色彩的RGB分量

 */
#ifndef COLOR_H  //预编译指令,防止重复定义类
#define COLOR_H
class Color
{
private:    //私有成员,用来保存色彩的RGB分量
  unsigned int rValue;
  unsigned int gValue;
  unsigned int bValue;
public:
  Color(unsigned int r=255, unsigned int g=0, unsigned int b=0); //类的构造函数,与类名相同
  void setRed(unsigned int value); //类的方法,设置或者读取色彩的RGB分量值
  unsigned int getRed();
  void setGreen(unsigned int value);
  unsigned int getGreen();
  void setBlue(unsigned int value);
  unsigned int getBlue();
};
#endif // COLOR_H

接着就可以建立一个新tab页,编写类的实现代码Color.cpp,步骤跟上面一样,就不啰嗦了。

大家在使用arduino的串口时,经常会用到Serial,其实它是串口类的实例,在某个地方创建之后,我们便可以直接使用。那我们也可以创建一些Color类的实例,比方讲,色彩中的白色、黑色、红色、绿色、蓝色,这几种颜色的RGB分量是固定,因此我们可以仿照Serial的使用方式来创建这几种颜色对象。

依照前面方式,我们新建一个tab页,起名为CommonColors.h,并引用Color.h,写入下面几行代码
#include "Color.h"
//定义一些常见颜色
Color clRed(255,0,0);
Color clGreen(0,255,0);
Color clBlue(0,0,255);
Color clWhite(255,255,255);
Color clBlack(0,0,0);

于是,我们在其它直接或间接引用了CommonColors.h的地方,就可以使用clRed、clGreen了。

写完之后,我们打开文件夹,便可以看到类的所有文件跟主程序文件在一起。这点跟库不一样,库文件是必须存放在libraries下面的与库名相同的文件夹下面。
dir.png


下面我们举个小例子来测试一下
#include "CommonColors.h"
#include "Color.h"
Color cl;
void setup()
{
  Serial.begin(9600);
  Serial.println(clRed.getRed());
  Serial.println(cl.getRed());  //测试构造函数的默认值
}
void loop()
{}




这种方式的好处就是可以在同一个平台下立即编译,当然使用VS等IDE配上适当插件之后比在Arduino下面会更方便。本文只是起到抛砖引玉的作用,希望对大家理解Arduino有点帮助。

贴上类的实现代码Color.cpp
#include "Color.h"
Color::Color(unsigned int r, unsigned int g, unsigned int b)
{
  rValue = r;
  gValue = g;
  bValue = b;
}
void Color::setRed(unsigned int value)
{
  rValue = value;
}
unsigned int Color::getRed()
{
  return rValue;
}
void Color::setGreen(unsigned int value)
{
  gValue = value;
}
unsigned int Color::getGreen()
{
  return gValue;
}
void Color::setBlue(unsigned int value)
{
  bValue = value;
}
unsigned int Color::getBlue()
{
  return bValue;
}

1 条评论:

  1. 这个方法只是示例,里面还需要注意添加宏,防止重复定义,或者将全局变量改在cpp中定义。

    回复删除