学习Arduino:初探 Ethernet Shield (以太网盾板)

以太网盾板的使用说明:

配合Arduino网络扩展板,使用这个库可以让Arduino板连接到互联网。它既可以作为一个接受传入信息的服务器也可以作为客户端传出信息。库最多可支持四个并发连接(传入或传出或组合)。 Arduino板与网络扩展板的使用SPI总线通信。在Arduino UNO上使用数字引脚11,12和13。在Arduino Mega上使用引脚50,51和52。这两个板上,10引脚都是SS信号口。在Mega上硬件SS端口53号引脚将不能用于W5100网络板控制。但是其必须保持输出状态,否则SPI总线将无法工作。

Ethernet类

Ethernet类初始化Ethernet库和网络设置。

IP地址类

IPAddress类设置本地和远程的IP地址。

服务器类

服务器类用于创建一个网络服务器,专用于与客户端进行通信,接收发送数据。

客户端类

客户端类用于创建一个网络客户端,可以连接到服务器,发送和接收数据。

UDP协议类

EthernetUDP类可以用来发送和接收UDP消息。

 应用举例

作为服务端(Server)的例子

[cc lang=”c”]
#include
#include

//配置网络。网关和子网掩码是可选的。

// 以太扩展板的MAC地址:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//以太扩展板的IP地址
byte ip[] = { 10, 0, 0, 177 };
//路由器的网关地址:
byte gateway[] = { 10, 0, 0, 1 };
//子网掩码:
byte subnet[] = { 255, 255, 0, 0 };

// telnet默认23号端口
EthernetServer server = EthernetServer(23);

void setup()
{
//初始化以太网设备{
Ethernet.begin(mac, ip, gateway, subnet);

//开始侦听客户端
server.begin();
}

void loop()
{
//如果侦听到客户端连接,则可以读取字节:
EthernetClient client = server.available();
if (client == true) {
//从接收端读取字节并写入到所有连接到服务器的客户端

server.write(client.read());
}
}

[/cc]

作为客户端(Client)的例子

[cc lang=”c”]

#include
#include

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 10, 0, 0, 177 };
byte server[] = { 64, 233, 187, 99 }; // Google 的服务器地址
EthernetClient client;

void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println(“connecting…”);
if (client.connect(server, 80)) {
Serial.println(“connected”);
client.println(“GET /search?q=arduino HTTP/1.0”);
client.println();
}
else {
Serial.println(“connection failed”);
}
}

void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println(“disconnecting.”);
client.stop();
for(;;)
;
}
}

[/cc]

自己修改的例子

插上盾板后,使用了 Arduino 中的自带例子,自己修改了部分内容。

这个例子中我在A0端口读入电位计数值,从串口中输出,用该盾板作为服务端(Server)使用,然后在浏览器中输入IP+端口(我使用的默认端口80)访问,就能得到A0端口的读数了。

例子代码如下:

[cc lang=”c”]

/*
Yeelink sensor client example
*/

#include
#include
#include
#include

int BH1750address = 0x23;
byte buff[2];

// for yeelink api
#define APIKEY “eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee” // replace your yeelink api key here
#define DEVICEID 8888 // replace your device ID
#define SENSORID 5555 // replace your sensor ID

// assign a MAC address for the ethernet controller.
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//IPAddress ip(192,168,0,111);
//EthernetServer server(80);

// initialize the library instance:
EthernetClient client;
char server[] = “192.168.0.111”; // name address for yeelink API

unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 30*1000; // delay between 2 datapoints, 30s

void setup() {
Wire.begin();
// start serial port:
Serial.begin(57600);
// start the Ethernet connection with DHCP:
if (Ethernet.begin(mac) == 0) {
Serial.println(“Failed to configure Ethernet using DHCP”);
for(;;)
;
}
else {
//Ethernet.begin(mac, ip);
//server.begin();
Serial.println(“Ethernet configuration OK”);
}
}

void loop() {
// if there’s incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}

// if there’s no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println(“disconnecting.”);
client.stop();
}

// if you’re not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() – lastConnectionTime > postingInterval)) {
// read sensor data, replace with your code
int sensorReading = readLightSensor();
//send data to server
sendData(sensorReading);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}

// this method makes a HTTP connection to the server:
void sendData(int thisData) {
// if there’s a successful connection:
if (client.connect(server, 80)) {
Serial.println(“connecting…”);
// send the HTTP PUT request:
client.print(“POST /v1.0/device/”);
client.print(DEVICEID);
client.print(“/sensor/”);
client.print(SENSORID);
client.print(“/datapoints”);
client.println(” HTTP/1.1″);
client.println(“Host: api.yeelink.net”);
client.print(“Accept: *”);
client.print(“/”);
client.println(“*”);
client.print(“U-ApiKey: “);
client.println(APIKEY);
client.print(“Content-Length: “);

// calculate the length of the sensor reading in bytes:
// 8 bytes for {“value”:} + number of digits of the data:
int thisLength = 10 + getLength(thisData);
client.println(thisLength);

client.println(“Content-Type: application/x-www-form-urlencoded”);
client.println(“Connection: close”);
client.println();

// here’s the actual content of the PUT request:
client.print(“{“value”:”);
client.print(thisData);
client.println(“}”);
}
else {
// if you couldn’t make a connection:
Serial.println(“connection failed”);
Serial.println();
Serial.println(“disconnecting.”);
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}

// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
int getLength(int someValue) {
// there’s at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you’re at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}

///////////////////////////////////////////////////////////////////////////
// get data from light sensor
// you can replace this code for your sensor
int readLightSensor()
{
uint16_t val=0;
BH1750_Init(BH1750address);
delay(200);
if(2==BH1750_Read(BH1750address))
{
val=((buff[0]<<8)|buff[1])/1.2; } Serial.print("Sensor value is: "); Serial.println((int)val); return val; } int BH1750_Read(int address) // { int i=0; Wire.beginTransmission(address); Wire.requestFrom(address, 2); while(Wire.available()) // { buff[i] = Wire.read(); // receive one byte i++; } Wire.endTransmission(); return i; } void BH1750_Init(int address) { Wire.beginTransmission(address); Wire.write(0x10);//1lx reolution 120ms Wire.endTransmission(); } [/cc] 其中的MAC地址让我有些挠头,原来MAC地址是我们自己人为给的。“mac:MAC(媒体访问控制)设备地址(6字节数组)。这是你的模块的以太网硬件地址。新的Arduino以太网模块包括一个设备的MAC地址的贴纸。对于较老的模块,可以设定自己的MAC地址。” http://wiki.geek-workshop.com/doku.php?id=arduino:libraries:ethernet

Comments

No comments yet. Why don’t you start the discussion?

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注