ProgrammingArduino物联网
programming_arduino_ed2
IO
延时闪灯
void setup()
{pinMode(13, OUTPUT);
}void loop()
{digitalWrite(13, HIGH);delay(500);digitalWrite(13, LOW);delay(500);
}// sketch 03-02 加入变量====
int ledPin = 13;
int delayPeriod = 500;void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{digitalWrite(ledPin, HIGH);delay(delayPeriod);digitalWrite(ledPin, LOW);delay(delayPeriod);
}// sketch 03-03 快闪--->满闪=====
int ledPin = 13;
int delayPeriod = 100;void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{digitalWrite(ledPin, HIGH);delay(delayPeriod);digitalWrite(ledPin, LOW);delay(delayPeriod);delayPeriod = delayPeriod + 100;
}// sketch 03-06 快闪--->满闪-->快闪--->满闪---循环
int ledPin = 13;
int delayPeriod = 100;void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{digitalWrite(ledPin, HIGH);delay(delayPeriod);digitalWrite(ledPin, LOW);delay(delayPeriod);delayPeriod = delayPeriod + 100; // 闪烁变慢if (delayPeriod > 1000) // 循环===回到初始状态{delayPeriod = 100; }
}// sketch 03-08 ===== for循环 闪灯
int ledPin = 13;
int delayPeriod = 250;void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{for (int i = 0; i < 20; i ++){digitalWrite(ledPin, HIGH);delay(delayPeriod);digitalWrite(ledPin, LOW);delay(delayPeriod);}delay(3000);
}// sketch 03-09 带有休息时段的 常数闪灯=====
int ledPin = 13;
int delayPeriod = 100;
int count = 0;void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{digitalWrite(ledPin, HIGH);delay(delayPeriod);digitalWrite(ledPin, LOW);delay(delayPeriod);count ++;if (count == 20){count = 0;delay(3000); // 闪烁20次,定时休息}
}// sketch 04-04==========带有休息时段的 常数闪灯 const static变量=====
const int ledPin = 13;
const int delayPeriod = 250;void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{static int count = 0;digitalWrite(ledPin, HIGH);delay(delayPeriod);digitalWrite(ledPin, LOW);delay(delayPeriod);count ++;if (count == 20){count = 0;delay(3000);}
}// sketch 04-01 for 循环实现闪灯 闪灯程序打包成函数====
const int ledPin = 13;
const int delayPeriod = 250;void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{for (int i = 0; i < 20; i ++){// for 循环实现闪灯flash();}delay(3000);
}// 闪灯程序打包成函数
void flash()
{digitalWrite(ledPin, HIGH);delay(delayPeriod);digitalWrite(ledPin, LOW);delay(delayPeriod);
}// sketch 04-02=============进一步包装闪灯程序
const int ledPin = 13;
const int delayPeriod = 250;void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{flash(20, delayPeriod);delay(3000);
}void flash(int numFlashes, int d)
{for (int i = 0; i < numFlashes; i ++){digitalWrite(ledPin, HIGH);delay(d);digitalWrite(ledPin, LOW);delay(d);}
}// sketch 05-02 闪灯延时指定 时间 数组=====================
const int ledPin = 13;
int durations[] = {200, 200, 200, 500, 500, 500, 200, 200, 200};void setup()
{pinMode(ledPin, OUTPUT);
}void loop()
{for (int i = 0; i < 9; i++){flash(durations[i]);}delay(1000);
}void flash(int duration)
{digitalWrite(ledPin, HIGH);delay(duration);digitalWrite(ledPin, LOW);delay(duration);
}//sketch 06-04 ======= io 口 控制 灯开关 ==========
const int inputPin = 5;
const int ledPin = 13;void setup()
{pinMode(ledPin, OUTPUT);pinMode(inputPin, INPUT_PULLUP);
}void loop()
{int switchOpen = digitalRead(inputPin);digitalWrite(ledPin, !switchOpen);
}//sketch 06-05 =====低电平触发 闪灯===============
const int inputPin = 5;
const int ledPin = 13;
int ledValue = LOW;
void setup()
{pinMode(inputPin, INPUT_PULLUP);// 上拉pinMode(ledPin, OUTPUT);
}
void loop()
{if (digitalRead(inputPin) == LOW) //低电平触发 闪灯 {ledValue = !ledValue;digitalWrite(ledPin, ledValue);delay(500);}
}//sketch 06-07 ===== 按键消抖 控制灯闪烁======
#include <Bounce2.h> // 按键消抖 库
const int inputPin = 5;
const int ledPin = 13;
int ledValue = LOW;
Bounce bouncer = Bounce(); void setup()
{pinMode(inputPin, INPUT_PULLUP);pinMode(ledPin, OUTPUT);bouncer.attach(inputPin);// bouncer.interval(50); // interval in ms
}void loop()
{if (bouncer.update() && bouncer.read() == LOW) // 按键消抖{ledValue = ! ledValue;digitalWrite(ledPin, ledValue);// delay(500);}
}//sketch 07-04 ===端口中断===改变闪灯节奏===const int interruptPin = 2;
const int ledPin = 13;
int period = 500;void setup()
{pinMode(ledPin, OUTPUT);pinMode(interruptPin, INPUT_PULLUP);attachInterrupt(0, goFast, FALLING);// 端口中断 下降沿中断
}void loop()
{digitalWrite(ledPin, HIGH);delay(period);digitalWrite(ledPin, LOW);delay(period);
}// 端口中断函数 改变闪灯节奏
void goFast()
{period = 100;
}
模拟量测量
//sketch 06-08const int analogPin = 0;void setup()
{Serial.begin(9600);
}
void loop()
{int reading = analogRead(analogPin); // 模拟量测量float voltage = reading / 204.6;// 转换成电压Serial.print("Reading=");Serial.print(reading);Serial.print("\t\tVolts=");Serial.println(voltage);delay(500);
}
Arduino音乐键盘tone函数
//sketch 07-03
void setup()
{tone(4, 500);
}
void loop() {}
串口
// sketch 03-04
void setup()
{Serial.begin(9600);int a = 2;int b = 2;int c = a + b;Serial.println(c); Serial.println("Hello");
}
void loop()
{}// sketch 5-04 ===============打印字符串数组========
char message[] = "Hello";void setup()
{Serial.begin(9600);
}void loop()
{Serial.println(message);delay(1000);
}// sketch 03-05 串口 华氏度 摄氏度 转换=====
void setup()
{Serial.begin(9600);int degC = 20;int degF;degF = degC * 9 / 5 + 32;Serial.println(degF);
}
void loop()
{}// sketch 05-01 串口打印数组================
int durations[] = {200, 200, 200, 500, 500, 500, 200, 200, 200};void setup()
{Serial.begin(9600); for (int i = 0; i < 9; i++){Serial.println(durations[i]);}
}void loop() {}// sketch 5-05 ======= 串口和闪灯混合,串口字符控制闪灯节奏=======const int ledPin = 13;
const int dotDelay = 200;char* letters[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", // A-I".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", // J-R"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." // S-Z
};char* numbers[] = {"-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."};void setup()
{pinMode(ledPin, OUTPUT);Serial.begin(9600);
}void loop()
{char ch;if (Serial.available() > 0){ch = Serial.read();if (ch >= 'a' && ch <= 'z'){flashSequence(letters[ch - 'a']);}else if (ch >= 'A' && ch <= 'Z'){flashSequence(letters[ch - 'A']);}else if (ch >= '0' && ch <= '9'){flashSequence(numbers[ch - '0']);}else if (ch == ' '){delay(dotDelay * 4); // gap between words }}
}void flashSequence(char* sequence)
{int i = 0;while (sequence[i] != NULL){flashDotOrDash(sequence[i]);i++;}delay(dotDelay * 3); // gap between letters
}void flashDotOrDash(char dotOrDash)
{digitalWrite(ledPin, HIGH);if (dotOrDash == '.'){delay(dotDelay); }else // must be a dash{delay(dotDelay * 3); }digitalWrite(ledPin, LOW); delay(dotDelay); // gap between flashes
}// sketch 8-01 ====内存拷贝=====串口控制=====const int ledPin = 13;
const int dotDelay = 200;const int maxLen = 6; // including null on the endPROGMEM const char letters[26][maxLen] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", // A-I".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", // J-R"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." // S-Z
};PROGMEM const char numbers[10][maxLen] = {"-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."
};void setup()
{pinMode(ledPin, OUTPUT);Serial.begin(9600);
}void loop()
{char ch;char sequence[maxLen];if (Serial.available() > 0){ch = Serial.read();if (ch >= 'a' && ch <= 'z'){memcpy_P(&sequence, letters[ch - 'a'], maxLen);// 内存拷贝flashSequence(sequence);}else if (ch >= 'A' && ch <= 'Z'){memcpy_P(&sequence, letters[ch - 'A'], maxLen);flashSequence(sequence);}else if (ch >= '0' && ch <= '9'){memcpy_P(&sequence, numbers[ch - '0'], maxLen);flashSequence(sequence);}else if (ch == ' '){delay(dotDelay * 4); // gap between words }}
}void flashSequence(char* sequence)
{int i = 0;while (sequence[i] != NULL){flashDotOrDash(sequence[i]);i++;}delay(dotDelay * 3); // gap between letters
}void flashDotOrDash(char dotOrDash)
{digitalWrite(ledPin, HIGH);if (dotOrDash == '.'){delay(dotDelay); }else // must be a dash{delay(dotDelay * 3); }digitalWrite(ledPin, LOW); delay(dotDelay); // gap between flashes
}//sketch 6-01 =======串口控制 灯 开关====
const int outPin = 3;void setup()
{pinMode(outPin, OUTPUT);Serial.begin(9600);Serial.println("Enter 1 or 0");
}void loop()
{if (Serial.available() > 0){char ch = Serial.read();if (ch == '1'){digitalWrite(outPin, HIGH);}else if (ch == '0'){digitalWrite(outPin, LOW);}}
}//sketch 06-02 ===== =====读取io状态,并串口打印=========
const int inputPin = 5;
void setup()
{pinMode(inputPin, INPUT);Serial.begin(9600);
}void loop()
{int reading = digitalRead(inputPin); // 普通输入,默认 低电平Serial.println(reading);delay(1000);
}//sketch 06-03 =====上拉输入,默认为 高电平 打印 io口状态=========
const int inputPin = 5;void setup()
{pinMode(inputPin, INPUT_PULLUP); // 上拉输入,默认为 高电平Serial.begin(9600);
}void loop()
{int reading = digitalRead(inputPin);Serial.println(reading);delay(1000);
}//sketch 07-01 === 打印随机数==========
void setup()
{Serial.begin(9600);randomSeed(analogRead(0)); // 随机数种子
}void loop()
{int number = random(1, 7);Serial.println(number);delay(500);
}
flash 闪存 内存 rom 内存读写
// sketch 08-02 ==== 串口读数据 写入内存=======
#include <EEPROM.h>
int addr = 0;
char ch;
void setup()
{Serial.begin(9600);ch = EEPROM.read(addr);
}
void loop()
{if (Serial.available() > 0){ch = Serial.read(); // 串口读数据EEPROM.write(0, ch); // 写入内存 单个字节数据Serial.println(ch);}Serial.println(ch);delay(1000);
}// sketch 08-06 ========清空内存数据=================
#include <EEPROM.h>
void setup()
{Serial.begin(9600);Serial.println("Clearing EEPROM");for (int i = 0; i < 1024; i++){EEPROM.write(i, 0);}Serial.println("EEPROM Cleared");
}
void loop() {}// sketch 08-03 ====== 向内存 读写 多字节数据
#include <avr/eeprom.h>
void setup()
{Serial.begin(9600);int i1 = 123;eeprom_write_block(&i1, 0, 2); // 写2个字节长度的数据int i2 = 0;eeprom_read_block(&i2, 0, 2);Serial.println(i2);
}
void loop() {}// sketch 08-04 ======== 写 浮点数===========
#include <avr/eeprom.h>
void setup()
{Serial.begin(9600);float f1 = 1.23;eeprom_write_block(&f1, 0, 4);// 4字节float f2 = 0;eeprom_read_block(&f2, 0, 4);Serial.println(f2);
}
void loop() {}//sketch 08-07 =========浮点数扩大后(量化) 以一个字节数据 进行存储
#include <EEPROM.h>
void setup()
{float tempFloat = 20.75;byte tempByte = (int)(tempFloat * 4); // 浮点数扩大后(量化)EEPROM.write(0, tempByte); // 以一个字节数据 进行存储byte tempByte2 = EEPROM.read(0); // 以一个字节数据 进行读取float temp2 = (float)(tempByte2) / 4; // 反量化Serial.begin(9600);Serial.println("\n\n\n");Serial.println(temp2);
}
void loop(){}// sketch 08-05 =============内存存储 字符串 密码数组
#include <avr/eeprom.h>
const int maxPasswordSize = 20; // 数组长度
char password[maxPasswordSize]; // 字符串 密码数组void setup()
{eeprom_read_block(&password, 0, maxPasswordSize);Serial.begin(9600);
}void loop()
{Serial.print("Your password is:");Serial.println(password);Serial.println("Enter a NEW password"); while (!Serial.available()) {};int n = Serial.readBytesUntil('\n', password, maxPasswordSize);password[n] = '\0';eeprom_write_block(password, 0, maxPasswordSize); // 写 字符串 密码数组Serial.print("Saved Password: ");Serial.println(password);
}
显示屏
// sketch 09-01 USB Message Board LCD==============================
#include <LiquidCrystal.h>
// lcd(RS E D4 D5 D6 D7) // 各端口=====
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
/*
其他接口形式LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)
*/
int numRows = 2;
int numCols = 16;
/*
begin()——定义LCD的长宽(n列×n行),格式lcd.begin(cols, rows)clear()——清空LCD,格式lcd.clear()home()——把光标移回左上角,即从头开始输出,格式lcd.home()setCursor()——移动光标到特定位置,格式lcd.setCursor(col, row)write()——在屏幕上显示内容(必须是一个变量,如”Serial.read()”),格式lcd.write(data)print()——在屏幕上显示内容(字母、字符串,等等),格式lcd.print(data)lcd.print(data, BASE)cursor()——显示光标(一条下划线),格式lcd.cursor()noCursor()——隐藏光标,格式lcd.noCursor()blink()——闪烁光标,格式lcd.blink()noBlink()——光标停止闪烁,格式lcd.noBlink()display()——(在使用noDisplay()函数关闭显示后)打开显示(并恢复原来内容),格式lcd.display()noDisplay()——关闭显示,但不会丢失原来显示的内容,格式为lcd.noDisplay()scrollDisplayLeft()——把显示的内容向左滚动一格,格式lcd.scrollDisplayLeft()scrollDisplayRight()——把显示的内容向右滚动一格,格式为lcd.scrollDisplayRight()autoscroll()——打开自动滚动,这使每个新的字符出现后,原有的字符都移动一格:如果字符一开始从左到右(默认),那么就往左移动一格,否则就向右移动,格式lcd.autoscroll()noAutoscroll()——关闭自动滚动,格式lcd.noAutoscroll()leftToRight()——从左往右显示,也就是说显示的字符会从左往右排列(默认),但屏幕上已经有的字符不受影响,格式lcd.leftToRight()rightToLeft()——从右往左显示,格式lcd.rightToLeft()createChar()——自造字符,最多5×8像素,编号0-7,字符的每个像素显示与否由数组里的数(0-不显示,1-显示)决定,格式lcd.createChar(num, data),有点难理解,可以看一个例子
*/
void setup()
{Serial.begin(9600);lcd.begin(numRows, numCols);lcd.clear();lcd.setCursor(0,0);lcd.print("Arduino");lcd.setCursor(0,1);lcd.print("Rules");
}void loop()
{if (Serial.available() > 0) {char ch = Serial.read();if (ch == '#'){lcd.clear();}else if (ch == '/'){// new linelcd.setCursor(0, 1);}else{lcd.write(ch);}}
}// sketch 09_02 ====I2C(SSD1306)驱动0.96寸12864 OLED========#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>Adafruit_SSD1306 display(4); // pick an unused pinvoid setup()
{ display.begin(SSD1306_SWITCHCAPVCC, 0x3c); // may need to change thisdisplay.setTextSize(4);display.setTextColor(WHITE);
}void loop()
{static int count = 0;display.clearDisplay();display.drawRoundRect(0, 0, 127, 63, 8, WHITE);display.setCursor(20,20);display.print(count);display.display();count ++;if (count > 9999){count = 0;}delay(1000);
}
物联网专题 Ethernet(以太网)
// sketch 10-01 DHCP ==================动态ip访问======
#include <SPI.h>
#include <Ethernet.h>
// MAC address just has to be unique. This should work
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };EthernetServer server(80);void setup()
{Serial.begin(9600);Ethernet.begin(mac);server.begin();Serial.print("Server started on: ");Serial.println(Ethernet.localIP());
}void loop()
{// listen for incoming clientsEthernetClient client = server.available();if (client) {while (client.connected()) {// send a standard http response headerclient.println("HTTP/1.1 200 OK");client.println("Content-Type: text/html");client.println();// send the bodyclient.println("<html><body>");client.println("<h1>Arduino Server</h1>");client.print("<p>A0="); client.print(analogRead(0)); client.println("</p>"); client.print("<p>millis="); client.print(millis()); client.println("</p>"); client.println("</body></html>");client.stop();}delay(1);}
}// sketch 10-01 Static IP ====== 静态ip访问=================================
#include <SPI.h>
#include <Ethernet.h>
// MAC address just has to be unique. This should work
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// The IP address will be dependent on your local network:
byte ip[] = { 192, 168, 1, 30 };EthernetServer server(80);void setup()
{Ethernet.begin(mac, ip);server.begin();Serial.begin(9600);
}void loop()
{// listen for incoming clientsEthernetClient client = server.available();if (client) {while (client.connected()) {// send a standard http response headerclient.println("HTTP/1.1 200 OK");client.println("Content-Type: text/html");client.println();// send the bodyclient.println("<html><body>");client.println("<h1>Arduino Server</h1>");client.print("<p>A0="); client.print(analogRead(0)); client.println("</p>"); client.print("<p>millis="); client.print(millis()); client.println("</p>"); client.println("</body></html>");client.stop();}delay(1);}
}// sketch 10-02 Web Controlled Arduino 动态IP WEB远程控制 终端arduino#include <SPI.h>
#include <Ethernet.h>// MAC address just has to be unique. This should work
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };EthernetServer server(80);int numPins = 5;
int pins[] = {3, 4, 5, 6, 7};
int pinState[] = {0, 0, 0, 0, 0};
char line1[100];void setup()
{for (int i = 0; i < numPins; i++){pinMode(pins[i], OUTPUT);}Serial.begin(9600);Ethernet.begin(mac);server.begin();Serial.print("Server started on: ");Serial.println(Ethernet.localIP());
}void loop()
{EthernetClient client = server.available();if (client) {while (client.connected()) {readHeader(client);if (! pageNameIs("/")){client.stop(); return;}client.println("HTTP/1.1 200 OK");client.println("Content-Type: text/html");client.println();// send the bodyclient.println("<html><body>");client.println("<h1>Output Pins</h1>");client.println("<form method='GET'>"); setValuesFromParams();setPinStates();for (int i = 0; i < numPins; i++){writeHTMLforPin(client, i);}client.println("<input type='submit' value='Update'/>");client.println("</form>");client.println("</body></html>");client.stop(); }}
}void writeHTMLforPin(EthernetClient client, int i)
{client.print("<p>D");client.print(pins[i]); client.print(" <select name='");client.print(i);client.println("'>");client.print("<option value='0'");if (pinState[i] == 0){client.print(" selected");}client.println(">Off</option>");client.print("<option value='1'");if (pinState[i] == 1){client.print(" selected");}client.println(">On</option>");client.println("</select></p>");
}void setPinStates()
{for (int i = 0; i < numPins; i++){digitalWrite(pins[i], pinState[i]);}
}void setValuesFromParams()
{for (int i = 0; i < numPins; i++){pinState[i] = valueOfParam(i + '0');}
}void readHeader(EthernetClient client)
{// read first line of headerchar ch;int i = 0;while (ch != '\n'){if (client.available()){ch = client.read();line1[i] = ch;i ++;}}line1[i] = '\0'; Serial.println(line1);
}boolean pageNameIs(char* name)
{// page name starts at char pos 4// ends with spaceint i = 4;char ch = line1[i];while (ch != ' ' && ch != '\n' && ch != '?'){if (name[i-4] != line1[i]){return false;}i++;ch = line1[i];}return true;
}int valueOfParam(char param)
{for (int i = 0; i < strlen(line1); i++){if (line1[i] == param && line1[i+1] == '='){return (line1[i+2] - '0');}}return 0;
}// sketch 10-02 Internet Pins ====== 静态ip web远程控制 终端 arduino==============#include <SPI.h>
#include <Ethernet.h>// MAC address just has to be unique. This should work
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// The IP address will be dependent on your local network:
byte ip[] = { 192, 168, 1, 30 };
EthernetServer server(80);int numPins = 5;
int pins[] = {3, 4, 5, 6, 7};
int pinState[] = {0, 0, 0, 0, 0};
char line1[100];void setup()
{for (int i = 0; i < numPins; i++){pinMode(pins[i], OUTPUT);}Serial.begin(9600);Ethernet.begin(mac, ip);server.begin();
}void loop()
{EthernetClient client = server.available();if (client) {while (client.connected()) {readHeader(client);if (! pageNameIs("/")){client.stop(); return;}client.println("HTTP/1.1 200 OK");client.println("Content-Type: text/html");client.println();// send the bodyclient.println("<html><body>");client.println("<h1>Output Pins</h1>");client.println("<form method='GET'>"); setValuesFromParams();setPinStates();for (int i = 0; i < numPins; i++){writeHTMLforPin(client, i);}client.println("<input type='submit' value='Update'/>");client.println("</form>");client.println("</body></html>");client.stop(); }}
}void writeHTMLforPin(EthernetClient client, int i)
{client.print("<p>D");client.print(pins[i]); client.print(" <select name='");client.print(i);client.println("'>");client.print("<option value='0'");if (pinState[i] == 0){client.print(" selected");}client.println(">Off</option>");client.print("<option value='1'");if (pinState[i] == 1){client.print(" selected");}client.println(">On</option>");client.println("</select></p>");
}void setPinStates()
{for (int i = 0; i < numPins; i++){digitalWrite(pins[i], pinState[i]);}
}void setValuesFromParams()
{for (int i = 0; i < numPins; i++){pinState[i] = valueOfParam(i + '0');}
}void readHeader(EthernetClient client)
{// read first line of headerchar ch;int i = 0;while (ch != '\n'){if (client.available()){ch = client.read();line1[i] = ch;i ++;}}line1[i] = '\0'; Serial.println(line1);
}boolean pageNameIs(char* name)
{// page name starts at char pos 4// ends with spaceint i = 4;char ch = line1[i];while (ch != ' ' && ch != '\n' && ch != '?'){if (name[i-4] != line1[i]){return false;}i++;ch = line1[i];}return true;
}int valueOfParam(char param)
{for (int i = 0; i < strlen(line1); i++){if (line1[i] == param && line1[i+1] == '='){return (line1[i+2] - '0');}}return 0;
}
无线网模块
// sketch 10-03. Node MCU Basic Web Server#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>const char* ssid = "my-network-name"; // 无线网名称
const char* password = "my_password"; // 无线网密码ESP8266WebServer server(80);void handleRoot()
{String message = "<html><body>\n";message += "<h1>Arduino Server</h1>\n";message += "<p>A0="; message += analogRead(A0); message += "</p>"; message += "<p>millis="; message += millis(); message += "</p>"; message += "</html></body>\n";server.send(200, "text/html", message);
}void connectToWiFi()
{Serial.print("\n\nConnecting to ");Serial.println(ssid);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(".");}Serial.println("\nWiFi connected"); Serial.print("IP address: ");Serial.println(WiFi.localIP());
}void setup()
{Serial.begin(115200);connectToWiFi();server.on("/", handleRoot);server.begin();Serial.println("HTTP server started");
}void loop()
{server.handleClient();
}// sketch 10-04 Web Controlled Node MCU ==== 无线网 控制终端 arduino==========#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>const char* ssid = "my-network-name";
const char* password = "my_password";int numPins = 5;
char* pinNames[] = {"D5", "D6", "D7", "D8", "D9"};
int pins[] = {D5, D6, D7, D8, D9};
int pinState[] = {0, 0, 0, 0, 0};ESP8266WebServer server(80);void setPinStates()
{for (int i = 0; i < numPins; i++){digitalWrite(pins[i], pinState[i]);}
}void setValuesFromParams()
{for (int i = 0; i < numPins; i++){pinState[i] = server.arg(i).toInt();}
}void connectToWiFi()
{Serial.print("\n\nConnecting to ");Serial.println(ssid);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(".");}Serial.println("\nWiFi connected"); Serial.print("IP address: ");Serial.println(WiFi.localIP());
}void handleRoot()
{char buff[1000];Serial.println("Got a Request");setValuesFromParams();setPinStates();strcat(buff, "<html><body>\n");strcat(buff, "<h1>Output Pins</h1>\n");strcat(buff, "<form method='GET'>\n"); for (int i = 0; i < numPins; i++){strcat(buff, "<p>");strcat(buff, pinNames[i]);strcat(buff, " <select name='");char indexStr[10];sprintf(indexStr, "%d", i);strcat(buff, indexStr);strcat(buff, "'><option value='0'");if (pinState[i] == 0){strcat(buff, " selected");}strcat(buff, ">Off</option>");strcat(buff, "<option value='1'");if (pinState[i] == 1){strcat(buff, " selected");}strcat(buff, ">On</option></select></p>\n");}strcat(buff, "<input type='submit' value='Update'/>");strcat(buff, "</form></html></body>\n");server.send(200, "text/html", buff);
}void setup()
{for (int i = 0; i < numPins; i++){pinMode(pins[i], OUTPUT);}Serial.begin(115200);connectToWiFi();server.on("/", handleRoot);server.begin();Serial.println("HTTP server started");
}void loop()
{server.handleClient();
}
IFTTT 表示如果在“this”上发生了某些事情,那么我们需要在“that”上做一些事情。
// sketch 10-05 IFTTT
#include <SPI.h>
#include <Ethernet.h>// MAC address just has to be unique. This should work
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };const char* key = "c1AsQq_qsQVTSO5-6NASqg";
const char* host = "maker.ifttt.com";
const int httpPort = 80;
const long sendPeriod = 60000L; // 1 minuteEthernetClient client;void setup()
{Serial.begin(9600);Ethernet.begin(mac);
}void sendToIFTTT(int reading)
{client.stop(); // for second time around the loopSerial.print("connecting to ");Serial.println(host);if (!client.connect(host, httpPort)) {Serial.println("connection failed");return;}String url = "/trigger/arduino_spoke/with/key/";url += key;url += "?value1=" + String(reading);String req = String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" +"Connection: close\r\n\r\n";Serial.println(req);client.print(req);
}void loop()
{static long lastReadingTime = 0;long now = millis();if (now > lastReadingTime + sendPeriod){int reading = analogRead(A0);sendToIFTTT(reading);lastReadingTime = now;}if (client.available()){Serial.write(client.read());}
}// sketch 10_06=======wifi连接IFTTT=================#include <ESP8266WiFi.h>const char* ssid = "my-network-name";
const char* password = "my_password";
const char* key = "c1AsQq_qsQVTSO5-6NASqg";
const char* host = "maker.ifttt.com";
const int httpPort = 80;
const long sendPeriod = 10000L; // 1 minuteWiFiClient client;void connectToWiFi()
{Serial.print("\n\nConnecting to ");Serial.println(ssid);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(".");}Serial.println("\nWiFi connected"); Serial.print("IP address: ");Serial.println(WiFi.localIP());
}void sendToIFTTT(int reading)
{Serial.print("connecting to ");Serial.println(host);if (!client.connect(host, httpPort)) {Serial.println("connection failed");return;}String url = "/trigger/arduino_spoke/with/key/";url += key;url += "?value1=" + String(reading);String req = String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" +"Connection: close\r\n\r\n";Serial.println(req);client.print(req);
}void setup()
{Serial.begin(115200);connectToWiFi();
}void loop()
{static long lastReadingTime = 0;long now = millis();if (now > lastReadingTime + sendPeriod){int reading = analogRead(A0);sendToIFTTT(reading);lastReadingTime = now;}if (client.available()){Serial.write(client.read());}
}
相关文章:
ProgrammingArduino物联网
programming_arduino_ed2 IO 延时闪灯 void setup() {pinMode(13, OUTPUT); }void loop() {digitalWrite(13, HIGH);delay(500);digitalWrite(13, LOW);delay(500); }// sketch 03-02 加入变量 int ledPin 13; int delayPeriod 500;void setup() {pinMode(ledPin, OUTPUT)…...
SSM框架的学习与应用(Spring + Spring MVC + MyBatis)-Java EE企业级应用开发学习记录(第一天)Mybatis的学习
SSM框架的学习与应用(Spring Spring MVC MyBatis)-Java EE企业级应用开发学习记录(第一天)Mybatis的学习 一、当前的主流框架介绍(这就是后期我会发出来的框架学习) Spring框架 Spring是一个开源框架,是为了解决企业应用程序开发复杂…...
Programming abstractions in C阅读笔记: p118-p122
《Programming Abstractions In C》学习第49天,p118-p122,总结如下: 一、技术总结 1.随机数 (1)seed p119,“The initial value–the value that is used to get the entire process start–is call a seed for the random ge…...
2023国赛数学建模思路 - 案例:ID3-决策树分类算法
文章目录 0 赛题思路1 算法介绍2 FP树表示法3 构建FP树4 实现代码 建模资料 0 赛题思路 (赛题出来以后第一时间在CSDN分享) https://blog.csdn.net/dc_sinor?typeblog 1 算法介绍 FP-Tree算法全称是FrequentPattern Tree算法,就是频繁模…...
selenium 选定ul-li下拉选项中某个指定选项
场景:selenium的下拉选项是ul-li模式,选定某个指定的选项。 from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 显示等待def select_li(self, text, *ul_locator):"…...
回归预测 | MATLAB实现FA-SVM萤火虫算法优化支持向量机多输入单输出回归预测(多指标,多图)
回归预测 | MATLAB实现FA-SVM萤火虫算法优化支持向量机多输入单输出回归预测(多指标,多图) 目录 回归预测 | MATLAB实现FA-SVM萤火虫算法优化支持向量机多输入单输出回归预测(多指标,多图)效果一览基本介绍…...
使用pytorch 的Transformer进行中英文翻译训练
下面是一个使用torch.nn.Transformer进行序列到序列(Sequence-to-Sequence)的机器翻译任务的示例代码,包括数据加载、模型搭建和训练过程。 import torch import torch.nn as nn from torch.nn import Transformer from torch.utils.data im…...
解决element的select组件创建新的选项可多选且opitions数据源中有数据的情况下,回车不能自动选中创建的问题
前言 最近开发项目使用element-plus库内的select组件,其中有提供一个创建新的选项的用法,但是发现一些小问题,在此记录 版本 “element-plus”: “^2.3.9”, “vue”: “^3.3.4”, 问题 1、在options数据源中无数据的时候,在输入框…...
人工智能大模型加速数据库存储模型发展 行列混合存储下的破局
数据存储模型 专栏内容: postgresql内核源码分析手写数据库toadb并发编程toadb开源库 个人主页:我的主页 座右铭:天行健,君子以自强不息;地势坤,君子以厚德载物. 概述 在数据库的发展过程中,关…...
K8S用户管理体系介绍
1 K8S账户体系介绍 在k8s中,有两类用户,service account和user,我们可以通过创建role或clusterrole,再将账户和role或clusterrole进行绑定来给账号赋予权限,实现权限控制,两类账户的作用如下。 server acc…...
实现chatGPT 聊天样式
效果图 代码: <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Chat Example</title&g…...
day9 STM32 I2C总线通信
I2C总线简介 I2C总线介绍 I2C(Inter-Integrated Circuit)总线(也称IIC或I2C)是由PHILIPS公司开发的两线式串行总线,用于连接微控制器及其外围设备,是微电子通信控制领域广泛采用的一种总线标准。 它是同步通…...
终极Shell:Zsh(CentOS7 安装 zsh 及 配置 Oh my zsh)
CentOS7 安装 zsh 及 配置 Oh my zsh 我们在通过Shell操作linux终端时,配置、颜色区分、命令提示大都达不到我们预期的效果或者操作较为繁琐。 今天就来介绍一款终极一个及其好用的类Linux系统中的终端软件,江湖称之为马车中的跑车,跑车中的飞行车,史称『终极 Shell…...
Redis的数据持久化
前言 本文主要介绍Redis的三种持久化方式、AOF持久化策略等 什么是持久化 持久化是指将数据在内存中的状态保存到非易失性介质(如硬盘、固态硬盘等)上的过程。在计算机中,内存中的数据属于易失性数据,一旦断电或重启系统&#…...
CSS 选择器
前言 基础选择器 以下是几种常见的基础选择器。 标签选择器:通过HTML标签名称选择元素。 例如: p {color: red; } 上述样式规则将选择所有<p>标签 ,并将其文字颜色设置为红色。 类选择器:通过类名选择元素。使用类选择…...
上位机工作总结(2023.03-2023.08)
1.工作总结 不知不觉,已经从C#转为Qt开发快半年了。这半年内,也是学习了很多C相关的开发技能,同时自己的技术栈也是进一步丰富,以后跑路就更容易啦,哈哈!自己之前就有Winform和一些简单的Qt项目实践&#…...
APSIM模型参数优化 批量模拟丨气象数据准备、物候发育和光合生产、物质分配与产量模拟、土壤水分平衡算法、土壤碳氮平衡模块、农田管理模块等
随着数字农业和智慧农业的发展,基于过程的农业生产系统模型在模拟作物对气候变化的响应与适应、农田管理优化、作物品种和株型筛选、农田固碳和温室气体排放等领域扮演着越来越重要的作用。APSIM (Agricultural Production Systems sIMulator)模型是世界知名的作物生…...
Azure防火墙
文章目录 什么是Azure防火墙如何部署和配置创建虚拟网络创建虚拟机创建防火墙创建路由表,关联子网、路由配置防火墙策略配置应用程序规则配置网络规则配置 DNAT 规则 更改 Srv-Work 网络接口的主要和辅助 DNS 地址测试防火墙 什么是Azure防火墙 Azure防火墙是一种用…...
【LeetCode】剑指 Offer Ⅱ 第4章:链表(9道题) -- Java Version
题库链接:https://leetcode.cn/problem-list/e8X3pBZi/ 类型题目解决方案双指针剑指 Offer II 021. 删除链表的倒数第 N 个结点双指针 哨兵 ⭐剑指 Offer II 022. 链表中环的入口节点(环形链表)双指针:二次相遇 ⭐剑指 Offer I…...
Android SDK 上手指南|| 第三章 IDE:Android Studio速览
第三章 IDE:Android Studio速览 Android Studio是Google官方提供的IDE,它是基于IntelliJ IDEA开发而来,用来替代Eclipse。不过目前它还属于早期版本,目前的版本是0.4.2,每个3个月发布一个版本,最近的版本…...
Vue--》打造个性化医疗服务的医院预约系统(七)完结篇
今天开始使用 vue3 + ts 搭建一个医院预约系统的前台页面,因为文章会将项目的每一个地方代码的书写都会讲解到,所以本项目会分成好几篇文章进行讲解,我会在最后一篇文章中会将项目代码开源到我的GithHub上,大家可以自行去进行下载运行,希望本文章对有帮助的朋友们能多多关…...
点亮一颗LED灯
TOC LED0 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);//使能APB2的外设时钟GPIO_InitTypeDef GPIO_Initstructure;GPIO_Initstructure.GPIO_Mode GPIO_Mode_Out_PP;//通用推挽输出GPIO_Initstructure.GPIO_Pin GPIO_Pin_5;GPIO_Initstructure.GPIO_Speed GPIO_S…...
SSH远程直连--------------Docker容器
文章目录 1. 下载docker镜像2. 安装ssh服务3. 本地局域网测试4. 安装cpolar5. 配置公网访问地址6. SSH公网远程连接测试7.固定连接公网地址8. SSH固定地址连接测试 在某些特殊需求下,我们想ssh直接远程连接docker 容器,下面我们介绍结合cpolar工具实现ssh远程直接连接docker容器…...
Python/Spring Cloud Alibaba开发--前端复习笔记(1)———— html5和css3.html基础
Python/Spring Cloud Alibaba开发–前端复习笔记(1)———— html5和css3.html基础 1)概述和基本结构 超文本标记语言。超文本指超链接,标记指的是标签。 基本结构: <!DOCTYPE html> 文档声明 <html lang”en”>…...
open cv学习 (十一)视频处理
视频处理 demo1 import cv2 # 打开笔记本内置摄像头 capture cv2.VideoCapture(0) # 笔记本内置摄像头被打开 while capture.isOpened():# 从摄像头中实时读取视频retval, image capture.read()# 在窗口中实时显示读取到的视频cv2.imshow("Video", image)# 等到用…...
函数栈帧理解
本文是从汇编角度来展示的函数调用,而且是在vs2013下根据调试展开的探究,其它平台在一些指令上会有点不同,指令不多,简单记忆一下即可,在我前些年的学习中,学的这几句汇编指令对我调试找错误起了不小的作用…...
【SA8295P 源码分析】70 - QAM8295P 原理图参考设计 之 DP、eDP 接口硬件原理分析
【SA8295P 源码分析】70 - QAM8295P 原理图参考设计 之 DP、eDP 接口硬件原理分析 一、DP 接口(Display Port)介绍二、高通参考硬件原理图分析2.1 高通 Display 接口框图介绍2.2 DP接口 Pin 定义介绍2.3 高通参考设计:DP2、DP3 硬件原理图2.4 高通参考设计:eDP0、eDP1 硬件…...
【CSS动画02--卡片旋转3D】
CSS动画02--卡片旋转3D 介绍代码HTMLCSS css动画02--旋转卡片3D 介绍 当鼠标移动到中间的卡片上会有随着中间的Y轴进行360的旋转,以下是几张图片的介绍,上面是鄙人自己录得一个供大家参考的小视频🤭 代码 HTML <!DOCTYPE html>…...
数据结构<树和二叉树>顺序表存储二叉树实现堆排
✨Blog:🥰不会敲代码的小张:)🥰 🉑推荐专栏:C语言🤪、Cpp😶🌫️、数据结构初阶💀 💽座右铭:“記住,每一天都是一個新的開始…...
理解docker命令
基础命令 帮助命令 docker --help(帮助命令) 用于获取某个命令的帮助信息 #命令帮助 docker 命令 --help 小技巧 换行符 \ 使用命令换符,可以让繁杂命令变得有条理 #命令换行,使用换行符 \ docker ... \... \ 镜像命令 d…...
wordpress 动态主题下载/百度推广开户多少钱一个月
算法: 题目: 计算: end...
容桂网站制作信息/北京做的好的seo公司
1、多长时间将业务上线当使用独立服务器时,要将业务部署上线所需的时间最低在1-3天左右。因为涉及服务器硬件配置、上架通电、环境设置、调试等,这系列工作完成后才能交付予您正常使用。但通过2、CPU、内存或磁盘升级云服务器和独立服务器都允许硬件升级…...
长沙市做网站/百度竞价推广一个月多少钱
今天在写线性表的链式存储过程中,遇到了一个比较奇葩的问题,就是同一段程序,用for循环可以顺利执行,然而用while循环就提醒我“结点空间申请失败!!!”,考虑了一上午都没有头绪。记录…...
开发公司采购招聘/seo关键词分析
最近有个概念吵得很火,网络爬虫,但是基本都是用什么python或者JAVA写,貌似很少看到用c写的,我在网上找了一个,看到其实还是很简单的算法。 算法讲解:1.遍历资源网站 2.获取html信息 3.然后解析网址和图片…...
海尔网站建设目标/长沙seo网站排名
Mosquitto库依赖libuuid和openssl库,所以我们在交叉编译Mosquitto之前需要先交叉编译他所需要的依赖库,这里作者已经把需要的源码都下载好了,大家可以在这个文档的目录下找到。不建议大家下载和我不一致的版本,可能会出问题。 mq…...
鸿鹄网站建设/各大网站排名
本文目标是充当使用Selenium Docker镜像以及CodeceptJS和Express服务器的“操作方法”指南。其中,我们将涵盖:什么是E2E验收测试?为什么要使用Docker?松耦合的测试工具测试工具层创建测试项目E2E验收测试验收测试是典型软件开发过…...