MikuDuino吸顶灯改造(三) - 炫Q香蕉派

MikuDuino吸顶灯改造(三)

草稿代码,达到预期效果,有时间优化吧

WiFiServer server(80);

int ioON = 12;
int ioOFF = 14; 
int ioW = 2;
int ioY = 15; 

void setup() {
  Serial.begin(115200);
  delay(10);

  // prepare GPIO2
  pinMode(ioON, OUTPUT);
  digitalWrite(ioON, 1);
  pinMode(ioOFF, OUTPUT);
  digitalWrite(ioOFF, 1);
  pinMode(ioW, INPUT);
  pinMode(ioY, INPUT);
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  
  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}
int getstate()
{
   delay(100);
   int w = digitalRead(ioW);
   int y = digitalRead(ioY);
   int s=(w>0)+(y>0)*2;
   Serial.println(s);
   return s;
}

void ka()
{
    digitalWrite(ioOFF, 0);
    delay(10);
    digitalWrite(ioOFF, 1);
    delay(100);
}

void kaka()
{
    digitalWrite(ioOFF, 0);
    delay(10);
    digitalWrite(ioOFF, 1);
    delay(100);
    digitalWrite(ioON, 0);
    delay(10);
    digitalWrite(ioON, 1);
    Serial.println("kaka");
}

void loop() {
  
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  
  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  
  // Match the request
  int val;
  if (req.indexOf("/gpio/1") != -1)
  {
    val = 1;
    while(getstate()!=val)
      kaka();
  }
  else if (req.indexOf("/gpio/0") != -1)
  {
    val = 0;
    while(getstate()!=val)
      ka();
  }
  else if (req.indexOf("/gpio/2") != -1)
  {
    val = 2;
    while(getstate()!=val)
      kaka();
  }
  else if (req.indexOf("/gpio/3") != -1)
  {
    val = 3;
    while(getstate()!=val)
      kaka();
  }
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  // Set GPIO2 according to the request
  //digitalWrite(12, val);
  
  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
  s += (val)?"off":"on";
  s += "</html>\n";

  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected 
  // when the function returns and 'client' object is detroyed
}

标签: none

添加新评论