Introduction: Because I took an embedded development course last semester, the teacher asked me to design a topic with raspberry PI. Because I can use wechat small program so rich imagination has the following article using wechat small program to remote switch raspberry PI RGB seven color light PS: communication dog is very tired

start

Hardware: Introduce raspberry PI

  • The Raspberry Pi is a linux-based single-chip computer, also known as a pocket computer, developed by the Raspberry Pi Foundation. So basically what a computer can do is what the Raspberry PI can do, and so far the Raspberry PI has been released in generation 4 and I’m using a generation 3 3B+, which is enough for me
  • 1.2 Raspberry PI accessories and systems can be burned into the lookMiss Ruan: Raspberry PI beginner’s tutorial
  • 1.3 Electronic components: because I need to realize the seven-color light switch, the RGB electronic components needed need to be integrated first, so I can buy them online directly

Hair seven color light principle

By controlling the RASPberry PI GPIO, RGB color LED lights can be controlled. The LED lamp has three lights: red, green and blue. Control the three lights to emit different levels of light, and when combined, they produce a variety of colors.

LED and Raspberry PI GPIO pin connections

The four pins on the LED lamp are GND, R, G and B respectively. GND Requires grounding. R,G, and B are the positive ports of the red, green, and blue lamps respectively. We attach them to the GPIO port of the raspberry PI. On the LED lamp, R is connected to raspberry PI GPIO18, G to Raspberry PI GPIO15, AND B to raspberry PI GPIO14. The pin diagram is shown below

  • GPIO pins

  • The physical picture after the connection

Project flow architecture diagram

Let’s first understand the flow chart of our project architecture

The server

Because to connect and control raspberry PI remotely, we need a server. I use the online cloud platform server of the Internet of ThingsoneNet. Low cost, no need to buy servers

    1. After registering an account, click the console, select All Products and services, select Multi-protocol Access, select HTTP, and select Add Products

    1. Product information can be filled in freely, for example

    1. Click the created product to enter the detailed page to obtainMaster-APIkey 和 access-key.

    1. Click to enter device List -> Add Device

    1. Go to the Data Flow template -> Add a data flow with an arbitrary name like ‘led_pi’. After completing these steps, our cloud platform interface is created

Code section

For details about how to use cloud platform interfaces, see the documentation.

Wechat applet end

//index.js
// Get the application instance
const app = getApp()
const API_URL = 'https://api.heclouds.com/devices/655618681/datapoints' // 655618681 is the device number, replace the device number you add yourself
const API_KEY =  'wkXV2upi=614H4U=HpeRiQ=OLU=' // Use your own api_key
Page({
  data: {
    rgb: 'rgb(0,154,97)'./ / initial value
    pick: false
  },

postData: function(value) {
    var that=this;
    wx.request({
      url: API_URL,
      header: {'api-key': API_KEY
      },
      method:"POST".data: {"datastreams": [{
        "id": "led_pi"."datapoints": [{
          "at": "2020-03-13T19:20:43"."value": value
        },
        ]
      }]
      },
      success: function (res) {
        console.log(res.statusCode)
        if(res.statusCode==200)
          that.setData({ motto: "led on" })
        else
          that.setData({ motto: "404 not found"}}}})),// Switch to red
clickRed: function(){
  this.postData('red')},// Toggle green
clickGreen: function(){
  this.postData('green')},clickWhite: function(){
  this.postData('white')},clickBlue: function() {
  this.postData('blue')},ClickOn:function() {
  this.postData('1')},ClickOff: function () {
    var that=this;
    this.setData({ motto: "wait..." })
    wx.request({
        url: `${API_URL}? type=3'`.header: {
        'api-key': API_KEY
        },
        method: "POST".data: {
        'led_pi': '0'
        },
        success: function (res) {
        if (res.statusCode == 200)
            that.setData({ motto: "led off" })
        else
            that.setData({ motto: "404 not found"}}}})),ClickGet: function () {
    this.setData({ motto: "wait" })
    wx.request({
        url: `${API_URL}? datastream_id=led_pi`.header: {
        'api-key': API_KEY
        },
        method: "GET".success(res) {
        console.log(res.data)
        }
    })
},

// display the color picker
toPick: function () {
    this.setData({
        pick: true})},// Get color result callback
pickColor(e) {
    let rgb = e.detail.color
    console.log(rgb)
    var a = rgb.split('rgb')
    // var b = a[1].split(')')
    console.log(a[1])
    // console.log(b)
    this.postData(a[1])}})Copy the code
  • Applets interface

The applets color palette component is downloaded from NPM

Raspberry PI side script

The raspberry PI script files use Python. I split it into two PY files. PS: Because Python was learned temporarily to solve this problem, the code is not written well

  • The applets send instruction RGB values or color strings.
  • Run the following wxmain. py file on the Raspberry PI terminal./wxMain.py
# -*- coding: utf-8 -*-
from iot10086 import Iot10086
import time
import RPi.GPIO as GPIO

# One breath lamp effect
def sleep(mytime) :
    time.sleep(mytime)

# set pin
rpin = 18
gpin = 15
bpin = 14

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(rpin, GPIO.OUT)
GPIO.setup(gpin, GPIO.OUT)
GPIO.setup(bpin, GPIO.OUT)

Call PWM module to adjust duty cycle
pwmR = GPIO.PWM(rpin, 70)
pwmG = GPIO.PWM(gpin, 70)
pwmB = GPIO.PWM(bpin, 70)

pwmR.start(1)
pwmG.start(1)
pwmB.start(1)

apikey='wkXV2upi=614H4U=HpeRiQ=OLeU='
apiurl='http://api.heclouds.com/devices/65561868/datastreams/'

iot = Iot10086(apikey, apiurl)

# Periodic refresh interface receives data sent by the small program side, the default light is white
for x in range(10000):
    iot_post_status = iot.get_data('led_pi')
    colors = iot_post_status['data']
    print('colors',colors)
    value = iot_post_status['data'] ['current_value']
    boolen = (len(value) >= 7)
    if(value == '1' or value == 'white'):
       GPIO.output(rpin, GPIO.HIGH)
       GPIO.output(gpin, GPIO.HIGH)
       GPIO.output(bpin, GPIO.HIGH)
    elif value == '0':
        GPIO.output(rpin, GPIO.LOW)
        GPIO.output(gpin, GPIO.LOW)
        GPIO.output(bpin, GPIO.LOW)
    elif value == 'red':
        GPIO.output(rpin, GPIO.HIGH)
        GPIO.output(gpin, GPIO.LOW)
        GPIO.output(bpin, GPIO.LOW)
    elif value == 'green':
        GPIO.output(gpin, GPIO.HIGH)
        GPIO.output(rpin, GPIO.LOW)
        GPIO.output(bpin, GPIO.LOW)
    elif value == 'blue':
        GPIO.output(bpin, GPIO.HIGH)
        GPIO.output(rpin, GPIO.LOW)
        GPIO.output(gpin, GPIO.LOW)
    elif boolen:
        RGB = value.split('(') [1].split(') ') [0].split(', ')
        r = int(RGB[0) /2.55001
        g = int(RGB[1) /2.55001
        b = int(RGB[2) /2.55001
        print('RGB', RGB)
        pwmR.ChangeDutyCycle(r)
        pwmG.ChangeDutyCycle(g)
        pwmB.ChangeDutyCycle(b)
        # Adjust the brightness of each color of red, green and blue LED to combine various colors
pwmR.stop()
pwmG.stop()
pwmB.stop()
GPIO.cleanup()
Copy the code
  • Import the access class iOT10086.py provided by the cloud platform.
# -*- coding: utf-8 -*-
import requests
import json
class Iot10086(object) :
    apikey='wkXV2upi=614H4U=HpeRiQ=OLeU='
    apiurl='http://api.heclouds.com/devices/65561868/datastreams/'

    def __init__(self, apikey, apiurl) :
        self.apikey = apikey
        self.apiurl = apiurl
        self.apiheaders={'api-key':apikey}

    def set_data(self,datastream,value) :
        apiurl_set = self.apiurl + '? type=3'
        payload={datastream:str(value)}
        r=requests.post(apiurl_set, headers=self.apiheaders, data=json.dumps(payload), timeout=30)
        return r.status_code

    def get_data(self,datastream) :
        apiurl_get = self.apiurl + datastream
        r=requests.get(apiurl_get, headers=self.apiheaders, timeout=20)
        if r.status_code == 200:
            return json.loads(r.text)
        else:
            return r.status_code
Copy the code

Implementation effect


PS: Since the operation video of the button was not recorded in school at that time, it will not be shown here

  • Data flow will be generated after each invocation of data, which can be viewed by logging in oneNet cloud platform

reference

“Wechat applet controls raspberry PI via wifi and Bluetooth”

The end of the

Thank you for meeting me. I’m Lin Yiyi. See you next time