当前位置: 代码迷 >> 综合 >> nodemcu arduino固件库socket通信(服务端)
  详细解决方案

nodemcu arduino固件库socket通信(服务端)

热度:79   发布时间:2023-11-23 18:49:58.0

内含wifi连接,连接服务器,向服务器发送消息,接收服务器发过来的消息,以及引脚触发中断函数。

#include <ESP8266WiFi.h>#ifndef STASSID
#define STASSID "1212" //wifi的账号
#define STAPSK "1234567890" //wifi的密码
#endif
const char* ssid     = STASSID;
const char* password = STAPSK;
const char* host = "192.168.43.1";        //tcp连接的服务器地址
const uint16_t port = 9998;              //服务器端口号
WiFiClient client;
String str="";                            //tcp接收的字符串
void setup() {
    pinMode(5, INPUT);pinMode(16, OUTPUT); Serial.begin(115200);Serial.println();Serial.println();Serial.print("Connecting to ");Serial.println(ssid); WiFi.mode(WIFI_STA);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {
    delay(500);Serial.print(".");}Serial.println("");Serial.println("WiFi connected");Serial.println("IP address: ");Serial.println(WiFi.localIP());attachInterrupt(D1,FunctionName,RISING);
}
void loop() {
    /*if(Serial.read()=='1'){Serial.println("1111111111111");digitalWrite(16, HIGH);delay(500);digitalWrite(16, LOW); }*//*if(digitalRead(5)==HIGH){Serial.println("22222222222222222");}*/while (!client.connected())//若未连接到服务端,则客户端进行连接。{
    if (!client.connect(host, port))//实际上这一步就在连接服务端,如果连接上,该函数返回true{
    Serial.println("connection....");delay(500);}}str="";  while (client.available())//available()表示是否可以获取到数据{
        str+=char(client.read());if(str=="1"){
    Serial.println("1111111111111");digitalWrite(16, HIGH);delay(500);digitalWrite(16, LOW); }//Serial.print(str); }
}
ICACHE_RAM_ATTR void FunctionName()
{
    Serial.println("receive");client.println("2");
}
  相关解决方案