资源描述
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页,也就是建立一个新的文件,
2011-12-19 02:10 上传
下载附件 (7.17 KB)
arduino IDE
单击它之后,便会出现一个提示你键入文件名的对话框,在这里写入文件名。我们先建立类的头文件Color.h,因此敲入Color.h,注意,一定不要忘了文件的扩展名.h,不然IDE会自动加上arduino的扩展名.pde的。
2011-12-19 02:15 上传
下载附件 (2.3 KB)
file name
接着我们在Color.h页中编写Color类的头文件,代码如下
1. /*
2. 颜色类,可以分别设置色彩的RGB分量
3.
4. */
5. #ifndef COLOR_H //预编译指令,防止重复定义类
6. #define COLOR_H
7.
8. class Color
9. {
10. private: //私有成员,用来保存色彩的RGB分量
11. unsigned int rValue;
12. unsigned int gValue;
13. unsigned int bValue;
14.
15. public:
16. Color(unsigned int r=255, unsigned int g=0, unsigned int b=0); //类的构造函数,与类名相同
17. void setRed(unsigned int value); //类的方法,设置或者读取色彩的RGB分量值
18. unsigned int getRed();
19. void setGreen(unsigned int value);
20. unsigned int getGreen();
21. void setBlue(unsigned int value);
22. unsigned int getBlue();
23.
24. };
25.
26. #endif // COLOR_H
27.
28.
复制代码
接着就可以建立一个新tab页,编写类的实现代码Color.cpp,步骤跟上面一样,就不啰嗦了。
大家在使用arduino的串口时,经常会用到Serial,其实它是串口类的实例,在某个地方创建之后,我们便可以直接使用。那我们也可以创建一些Color类的实例,比方讲,色彩中的白色、黑色、红色、绿色、蓝色,这几种颜色的RGB分量是固定,因此我们可以仿照Serial的使用方式来创建这几种颜色对象。
依照前面方式,我们新建一个tab页,起名为CommonColors.h,并引用Color.h,写入下面几行代码
1. #include "Color.h"
2.
3. //定义一些常见颜色
4. Color clRed(255,0,0);
5. Color clGreen(0,255,0);
6. Color clBlue(0,0,255);
7. Color clWhite(255,255,255);
8. Color clBlack(0,0,0);
复制代码
于是,我们在其它直接或间接引用了CommonColors.h的地方,就可以使用clRed、clGreen了。
写完之后,我们打开文件夹,便可以看到类的所有文件跟主程序文件在一起。这点跟库不一样,库文件是必须存放在libraries下面的与库名相同的文件夹下面。
2011-12-19 02:34 上传
下载附件 (14.41 KB)
下面我们举个小例子来测试一下
1. #include "CommonColors.h"
2. #include "Color.h"
3.
4. Color cl;
5. void setup()
6. {
7. Serial.begin(9600);
8. Serial.println(clRed.getRed());
9. Serial.println(cl.getRed()); //测试构造函数的默认值
10. }
11.
12. void loop()
13. {}
14.
复制代码
2011-12-19 02:31 上传
下载附件 (12.24 KB)
这种方式的好处就是可以在同一个平台下立即编译,当然使用VS等IDE配上适当插件之后比在Arduino下面会更方便。本文只是起到抛砖引玉的作用,希望对大家理解Arduino有点帮助。
贴上类的实现代码Color.cpp
1. #include "Color.h"
2.
3. Color::Color(unsigned int r, unsigned int g, unsigned int b)
4. {
5. rValue = r;
6. gValue = g;
7. bValue = b;
8. }
9.
10. void Color::setRed(unsigned int value)
11. {
12. rValue = value;
13. }
14.
15. unsigned int Color::getRed()
16. {
17. return rValue;
18. }
19.
20. void Color::setGreen(unsigned int value)
21. {
22. gValue = value;
23. }
24.
25. unsigned int Color::getGreen()
26. {
27. return gValue;
28. }
29.
30. void Color::setBlue(unsigned int value)
31. {
32. bValue = value;
33. }
34.
35. unsigned int Color::getBlue()
36. {
37. return bValue;
38. }
展开阅读全文