2023年12月29日金曜日

ATpedia,esp01/01sでAT

---------arduino send-client--------
#include <ESP8266.h>
#define SSID ""
#define PASSWORD ""
#define HOST_NAME "192...." // 自分のPCでパイソンサーバがうごくので、そのIPを入れる
#define HOST_PORT (9999)

SoftwareSerial mySerial(3,2);//rx,tx
ESP8266 wifi(mySerial);

void setup(void){
    Serial.begin(9600); // arduinoUNOのソフトシリアルは9600が上限なので
    mySerial.begin(115200); //理由不分明だがesp01もボーレートを落とす
    mySerial.println("AT+UART_CUR=9600,8,1,0,0");
    delay(10);
    mySerial.begin(9600);
    delay(10);
    if (wifi.setOprToStation()){ // set to station mode
        Serial.println("ok:setup");
    } else {
        Serial.println("error:setup");
    }
    if (wifi.joinAP(SSID,PASSWORD)){ // join local net
        Serial.println(wifi.getLocalIP().c_str());
    } else {
        Serial.println("failed:AP connect");
    }
    delay(10);
    if (wifi.disableMUX()){ // for client mode
        Serial.println("ok:single");
    } else {
        Serial.println("error:single");
    }
    delay(100);
}
void loop(void){ // send to PC python receive_server
    char msg[128] = {0};
    strcat(msg,"hello from Arduino to pc");
    if (wifi.createTCP(HOST_NAME,HOST_PORT)){
        Serial.println("ok:tcp connect.");
        wifi.send(msg,strlen(msg));
        wifi.releaseTCP();
    } else {
        Serial.println("failed:tcp connect");
    }
    while(1){
        delay(10000);
    }
}
----------------python receive_server ----------------------------------------------
import socket
host = "192.168...." # check by ipconfig/ifconfig
port = 9999
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind((host,port))
sock.listen(10)
cs,caddr=sock.accept() # caddrr not used as below
while True:
    msg = cs.recv(1024)
    print(msg.decode('ascii'))
    break
sock.close()

0 件のコメント:

コメントを投稿