---
title: "Arduino+W5100+Sina Cloud SAE+WeChat(to achieve LED control)"
url: "https://maker.wiznet.io/gemma/projects/arduino-w5100-sina-cloud-sae-wechat-to-achieve-led-control/"
markdown_url: "https://maker.wiznet.io/gemma/projects/arduino-w5100-sina-cloud-sae-wechat-to-achieve-led-control/md"
type: "UCC: User Created Content"
author: "gemma"
original_url: "https://www.programmersought.com/article/69496275687/"
published: "2022-08-30"
language: "en"
hardware: ["Arduino UNO", "Arduino Ethernet Shield 2"]
likes: 3
views: 1222
comments: 0
source: "WIZnet Makers (https://maker.wiznet.io/)"
---

# Arduino+W5100+Sina Cloud SAE+WeChat(to achieve LED control)

> Arduino+W5100+ Sina Cloud SAE (development language: Python) + WeChat public platform (to achieve LED control)

Original source: https://www.programmersought.com/article/69496275687/

## Components

- **Arduino UNO** x 1 ([docs](https://www.farnell.com/datasheets/1682209.pdf))
- **Arduino Ethernet Shield 2** x 1 ([docs](https://docs.arduino.cc/hardware/ethernet-shield-rev2))
- Software: **Arduino IDE** ([docs](https://www.arduino.cc/en/software))

## Article

Before reading this blog, it is recommended to refer to the blog:WeChat client + WeChat public platform + Sina Cloud SAE+Arduino+WS100 (control LED)
Difference: Mainly the language used by the server, this blog uses Python
1. Hardware part
1） Arduino、W5100
The connection diagram is as follows:
![](https://www.programmersought.com/images/231/3114f8e1f5f728e2ab73922a88d46d87.JPEG)
The hardware side is the pit I encountered, record it
a. Control the pin of the LED light:
Pin 13 is selected in many tutorials, but in the board I purchased, Pin13 is a multiplexed pin. When the Arduino and W5100 board are connected, pin13 is occupied and cannot be passed pin13 to control the LED switch. So I changed pin9
An external LED light, the reference picture is as follows:
![](https://www.programmersought.com/images/557/b90d501935cfce7b7086adc9522be3ad.JPEG)
b. The method of Ethernet.begin() to connect to the network:
According to the library data, there are five connection methods:<https://www.arduino.cc/en/Reference/EthernetBegin>

```plaintext
Ethernet.begin(mac); 
Ethernet.begin(mac, ip); 
Ethernet.begin(mac, ip, dns); 
Ethernet.begin(mac, ip, dns, gateway); 
Ethernet.begin(mac, ip, dns, gateway, subnet);
```

- 1

- 2

- 3

- 4

- 5

I overlooked a problem at the time. After arduino library 1.0, DHCP mode is supported, so when I test again, I don’t need to manually set the IP. The direct connection method is as follows: Ethernet.begin(mac);
2) Arduino device program burning
Arduino IDE
<https://www.arduino.cc/en/Main/Software>
Arduino code

```plaintext
#include "Arduino.h"  
#include <SPI.h>  
#include <Ethernet.h>  


char state = '0';  
char c;  
byte mac[] = {  
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; 

EthernetClient client;  
// arduino1.applinzi.com is my own server, you need to replace it with your own  
char server[] = "arduino1.applinzi.com";  
int sensrdata = 50;  

unsigned long lastConnectionTime = 0;  
boolean lastConnected = false;
// Set a time interval, request once every 10 seconds  
const unsigned long postingInterval = 10*1000;  

void setup()  
{  
// Add your initialization code here  
      Serial.begin(9600);  
      delay(1000);  
      Ethernet.begin(mac);  
      Serial.print("My IP address: ");  
      Serial.println(Ethernet.localIP());  
      pinMode(9, OUTPUT);  
}  

// The loop function is called in an endless loop  
void loop()  
{  
//Add your repeated code here  
      while(client.available()) {  
          state = client.read();  
        if(state == '{'){               //Turn off the lights 0  
            Serial.println(state);  
            digitalWrite(9, LOW);  
            delay(3000);  
          }else if(state == '}'){       //Turn on the light 1  
            Serial.println(state);  
            digitalWrite(9, HIGH);   
            delay(3000);  
          }  
      }  

      if (!client.connected() && lastConnected) {  
        Serial.println("disconnecting 2.");  
        client.stop();  
      }  

      if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {  
        if (client.connect(server, 80)) {  

            Serial.println("connecting");  
          // send the HTTP PUT request:  
          client.println("GET / HTTP/1.1");  
          client.println("Host: arduino1.applinzi.com");  
//          client.println("User-Agent: arduino-ethernet");  
          client.println("Connection: close");  
          client.println();  

          lastConnectionTime = millis();  
        }else {  
          Serial.println("connection failed");  
          Serial.println("disconnecting 1.");  
          client.stop();  
        }  
      }  
      lastConnected = client.connected();  
}
```

- 1

- 2

- 3

- 4

- 5

- 6

- 7

- 8

- 9

- 10

- 11

- 12

- 13

- 14

- 15

- 16

- 17

- 18

- 19

- 20

- 21

- 22

- 23

- 24

- 25

- 26

- 27

- 28

- 29

- 30

- 31

- 32

- 33

- 34

- 35

- 36

- 37

- 38

- 39

- 40

- 41

- 42

- 43

- 44

- 45

- 46

- 47

- 48

- 49

- 50

- 51

- 52

- 53

- 54

- 55

- 56

- 57

- 58

- 59

- 60

- 61

- 62

- 63

- 64

- 65

- 66

- 67

- 68

- 69

- 70

- 71

- 72

- 73

Second, the server part
Server application:
![](https://www.programmersought.com/images/601/30835c17c18cfd3356d8dd84d13405a9.JPEG)
Database design:
![](https://www.programmersought.com/images/492/c29c99b887563e6492729f71df60e32c.JPEG)
![](https://www.programmersought.com/images/374/606cef3f62f4b1e43f0f1b59fc2c4476.JPEG)

**List part of the code, see Github for detailed code**：<https://github.com/shfscut/Arduino>

index.wsgi code

```plaintext
import os

import sae
import web
from handle import Handle

urls = (
    '/', 'Handle'
)

app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root, 'templates')
render = web.template.render(templates_root)


app = web.application(urls, globals()).wsgifunc()

application = sae.create_wsgi_app(app)
```

- 1

- 2

- 3

- 4

- 5

- 6

- 7

- 8

- 9

- 10

- 11

- 12

- 13

- 14

- 15

- 16

- 17

- 18

handle.py code

```plaintext
# -*- coding: utf-8 -*-
# filename: handle.py

import hashlib
import web
import reply
import receive
import sae.const
import MySQLdb


class Handle(object):
    def GET(self):
        try:
            data = web.input()
            if len(data) == 0:
                db=MySQLdb.connect(host=sae.const.MYSQL_HOST,port=int(sae.const.MYSQL_PORT), user=sae.const.MYSQL_USER, passwd=sae.const.MYSQL_PASS, db=sae.const.MYSQL_DB)
                cursor = db.cursor()
                sql_query = "SELECT * FROM switch where id=1"
                content=""
                try:
                    cursor.execute(sql_query)
                    results = cursor.fetchall()
                    for row in results:
                        arduino_id = row[0]
                        arduino_state = row[1]
                        content = arduino_state
                except:
                    content = "Error: unable to fetch data"
                if content==1:
                    return "}"
                elif content==0:
                    return "{"
                return None
            signature = data.signature
            timestamp = data.timestamp
            nonce = data.nonce
            echostr = data.echostr
            token = "xxxxxxx" #Change into your own prestige token

            list = [token, timestamp, nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update, list)
            hashcode = sha1.hexdigest()
            print "handle/GET func: hashcode, signature: ", hashcode, signature
            if hashcode == signature:
                return echostr
            else:
                return ""
        except Exception, Argument:
            return Argument

    def POST(self):
        try:
            webData = web.data()
            print "Handle Post webdata is ", webData
            recMsg = receive.parse_xml(webData)
            if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                content =sae.const.MYSQL_USER
                db=MySQLdb.connect(host=sae.const.MYSQL_HOST,port=int(sae.const.MYSQL_PORT), user=sae.const.MYSQL_USER, passwd=sae.const.MYSQL_PASS, db=sae.const.MYSQL_DB)
                cursor = db.cursor()
                sql_query = "SELECT * FROM switch where id=1"
                sql_update_1 = "UPDATE switch set state=1 where id=1"
                sql_update_0 = "UPDATE switch set state=0 where id=1"
                arduino_id, arduino_state = None, None
                try:
                    cursor.execute(sql_query)
                    results = cursor.fetchall()
                    for row in results:
                        arduino_id = row[0]
                        arduino_state = row[1]
                except:
                    content = "Error: unable to fetch data"
                if recMsg.Content == "open":
                    if arduino_state != 1:

                        try:
                            cursor.execute(sql_update_1)
                            db.commit()
                        except:
                            db.rollback()
                elif recMsg.Content == "close":
                    if arduino_state != 0:

                        try:
                            cursor.execute(sql_update_0)
                            db.commit()
                        except:
                            db.rollback()
                else:
                    content = recMsg.Content
                try:
                    cursor.execute(sql_query)
                    results = cursor.fetchall()
                    for row in results:
                        arduino_id = row[0]
                        arduino_state = row[1]
                    content = "arduino_state:" + str(arduino_state)
                except:
                    content = "Error: unable to fetch data"
                db.close()
                replyMsg = reply.TextMsg(toUser, fromUser, content)
                return replyMsg.send()
            else:
                print "Will not deal with it temporarily"
                return "success"
        except Exception, Argment:
            return Argment
```

- 1

- 2

- 3

- 4

- 5

- 6

- 7

- 8

- 9

- 10

- 11

- 12

- 13

- 14

- 15

- 16

- 17

- 18

- 19

- 20

- 21

- 22

- 23

- 24

- 25

- 26

- 27

- 28

- 29

- 30

- 31

- 32

- 33

- 34

- 35

- 36

- 37

- 38

- 39

- 40

- 41

- 42

- 43

- 44

- 45

- 46

- 47

- 48

- 49

- 50

- 51

- 52

- 53

- 54

- 55

- 56

- 57

- 58

- 59

- 60

- 61

- 62

- 63

- 64

- 65

- 66

- 67

- 68

- 69

- 70

- 71

- 72

- 73

- 74

- 75

- 76

- 77

- 78

- 79

- 80

- 81

- 82

- 83

- 84

- 85

- 86

- 87

- 88

- 89

- 90

- 91

- 92

- 93

- 94

- 95

- 96

- 97

- 98

- 99

- 100

- 101

- 102

- 103

- 104

- 105

- 106

- 107

- 108

- 109

- 110

- 111

3. WeChat public platform
1) Register WeChat official account
2) Start server configuration
Settings -> Official Account Settings -> Server Settings
![](https://www.programmersought.com/images/40/cdb05a8c46b0a4d229576b3ed1756398.JPEG)
Note: The Sina cloud server needs to be set up, and the WeChat server submission can be successful

---

Source: https://maker.wiznet.io/gemma/projects/arduino-w5100-sina-cloud-sae-wechat-to-achieve-led-control/
