『瀚思彼岸』» 智能家居技术论坛

 找回密码
 立即注册
查看: 10117|回复: 13

彩色灯带接入HA,使用nodeMCU LUA 固件

[复制链接]

2

主题

2

帖子

80

积分

论坛分享达人

积分
80
金钱
78
HASS币
0
发表于 2017-8-2 15:20:32 | 显示全部楼层 |阅读模式
本帖最后由 et5494 于 2017-8-2 18:20 编辑

最近折腾了下彩色灯带这东西,看大家比较感兴趣,就写下了这个教程(第一次写教程类的东西,比较乱,看不懂的话可以直接PM我,QQ群里也可以直接找我,328872308)
1.此方案需要以下工具
       1.1 nodeMCU 开发板
       1.2 WS2812灯带,5V,12V都可以,就是要改下电源构成,此教程中使用5V
       1.3 一个继电器
       1.4 5V 电源,需要足A(一个灯珠的功率为0.3W,自己算需要多少A的电源)
       1.6 一个继电器              1.7 面包板与杜邦线

2.接线
       请直接按截图接线(我没找到继电器的图片,所以图片中没有接)       继电器话,可以直接把D1口接在继电器的控制端
         QQ截图20170802144106.png


3.nodeMCU 刷Lua固件
       3.1 下载固件
              Lua固件为可以云编译,选择自己需要的模块后,留下邮箱地址可以,过一段时间可以直接下载
              地址:https://nodemcu-build.com/
              在这个方案中,需要 gpio, gpio, gpio,wifi, ws2812 这几个模块,其他模块可以按需加载               此固件的API可以在 http://nodemcu.readthedocs.io/en/master/ 中查看

               3379069-b19529ac73e0c7c3.png

       3.2 刷写固件      

              下载 nodemcu-flasher(下载的时候注意选择对应的系统位数)
             3379069-3474e8098ba8931d.png
            
                QQ图片20170802145307.png
              其他配置都不需要动,直接Flash就可以了(当然,你需要把mcu插到电脑中)

4.脚本的编写
     4.1 脚本编写工具
           我想你大概猜到第一个程序是什么了吧!在此之前,推荐这个ESPlorer          上电后,可以点击upload上传init.lua 脚本,然后重启脚本
          3379069-351053be0cdd60e9 (1).png
          如果你打开后,send左边的文本框是灰色的,可以按一下Chip ID。你会看到上面的文本框会有内容输出。上电后,会调用一个 init.lua的文件夹。这里我们让nodeMCU循环发送 Hello NodeMCU。
         
tmr.alarm(0, 1000, tmr.ALARM_AUTO, function()

print("Hello NodeMCU!\n")

end

)


         如果在右边屏幕一直在输出 Hello NodeMCU 则表示,你的nodemcu固件已经OK了

      4.2 刷入彩灯控制代码            这边请稍微看下代码,特别是注释部分
            


print('Wait link to wifi')
wifi.setmode(wifi.STATION)
--这边需要修改
wifi.sta.config('SSID', 'password')
wifi.sta.connect()

local openStage = false

--回调事件
function GetWiFiStage()

        if wifi.sta.getip() == nil then
                print('Waiting for IP ...')
        else
                print('IP is ' .. wifi.sta.getip())
                print('WIFI LINK OK')
                
                tmr.stop(1)
        
                Light_Init()
                MQTT_EVENT()
        end
        
end


--上电初始化灯带
function Light_Init()

        ws2812.init()
        --这边是30灯,RGB灯
        i, buffer = 0, ws2812.newBuffer(30,3)
        --绿色,红色,蓝色
        buffer:fill(0,0,0)
        ws2812.write(buffer)
        --g,r,b
        r = 255
        b = 0 
        g = 255
        speed = 30
        light_mode = 1
        if light_mode == 1 then
                openStage = true
                tmr.alarm(2,speed,1,Light_RUNING)
        elseif light_mode == 2 then
                openStage = true
                tmr.alarm(2,speed,1,Light_ALL)
        end
        
end


--流水灯,事件
function Light_RUNING()
        
        i = i + 1
        --这边这个淡出,参数可以自己调整,主要是淡出的快慢
        buffer:fade(5)
        buffer:set(i % buffer:size() + 1, g , r , b )
        r = r - 4
        b = b + 5
        g = g - 5
        
        if(r <= 0) then
                r = 255
        end
        if(b >= 255) then
                b = 0
        end
        if(g <= 0) then
                g = 255
        end
        if i > 4294967295 then 
                i = 0
        end

        ws2812.write(buffer)

end


function Light_ALL()
        
        buffer:fill(g, r, b)
        ws2812.write(buffer)

end


function hsl_to_rgb(h, s, L)
   h = h/360
   local m1, m2
   if L<=0.5 then 
      m2 = L*(s+1)
   else 
      m2 = L+s-L*s
   end
   m1 = L*2-m2

   local function _h2rgb(m1, m2, h)
      if h<0 then h = h+1 end
      if h>1 then h = h-1 end
      if h*6<1 then 
         return m1+(m2-m1)*h*6
      elseif h*2<1 then 
         return m2 
      elseif h*3<2 then 
         return m1+(m2-m1)*(2/3-h)*6
      else
         return m1
      end
   end

   return _h2rgb(m1, m2, h+1/3)*255, _h2rgb(m1, m2, h)*255, _h2rgb(m1, m2, h-1/3)*255
end

function rgb_to_hsl(r, g, b)
   --r, g, b = r/255, g/255, b/255
   local min = math.min(r, g, b)
   local max = math.max(r, g, b)
   local delta = max - min

   local h, s, l = 0, 0, ((min+max)/2)

   if l > 0 and l < 0.5 then s = delta/(max+min) end
   if l >= 0.5 and l < 1 then s = delta/(2-max-min) end

   if delta > 0 then
      if max == r and max ~= g then h = h + (g-b)/delta end
      if max == g and max ~= b then h = h + 2 + (b-r)/delta end
      if max == b and max ~= r then h = h + 4 + (r-g)/delta end
      h = h / 6;
   end

   if h < 0 then h = h + 1 end
   if h > 1 then h = h - 1 end

   return h * 360, s, l
end


function DHT_GET()

        pin = 5
        status, temp, humi, temp_dec, humi_dec = dht.read(pin)
        
        
end


function lua_string_split(str, split_char)--?
        local sub_str_tab = {};
        while (true) do
                local pos = string.find(str, split_char);
                if (not pos) then
                        sub_str_tab[#sub_str_tab + 1] = str;
                        break;
                end
                local sub_str = string.sub(str, 1, pos - 1);
                sub_str_tab[#sub_str_tab + 1] = sub_str;
                str = string.sub(str, pos + 1, #str);
        end
        return sub_str_tab;
end


function MQTT_EVENT()
        
        nowStage = "E1"
        
        --创建一个mqtt连接
        --参数为 传感器名字,timeout时间,MQTT的账号密码
        m = mqtt.Client("sensor3", 60, "pi", "raspberry")
        
        m:lwt("/lwt", "offline", 0, 0)

        m:on("connect", function(client) print ("connected") end)
        m:on("offline", function(client) print ("offline") end)

        -- 接收到消息事件
        m:on("message", function(conn, topic, data) 
          print(topic .. ":" ) 
          if data ~= nil then
                print(data)
                
                if topic == "bruh/mqttstrip/setcolor" then
                        --这边是设置颜色
                        --由HA发送过来
                        local aa = lua_string_split(data,",")
                        r = aa[1]
                        g = aa[2]
                        b = aa[3]
                        
                elseif topic == "bruh/mqttstrip/seteffect" then
                        --设置特效
                        --由HA发送,E1,E2 为 HA的CONFIG中定义的名字
                        --这边效果,我只写的2个,你们已经按自己的需求,自己写,也可以把需求PM给我,我给你写
                        
                        tmr.stop(2)
                        if data == "E1" then
                                nowStage = "E1"
                                tmr.alarm(2,speed,1,Light_RUNING)
                                
                        elseif data == "E2" then
                                nowStage = "E2"
                                tmr.alarm(2,speed,1,Light_ALL)
                        end
                elseif topic == "bruh/mqttstrip/setanimationspeed" then
                        --设置效果的动态时间
                        tmr.stop(2)
                        speed = data
                        if nowStage == "E1" then
                                
                                tmr.alarm(2,speed,1,Light_RUNING)
                                
                        elseif nowStage == "E2" then
                                
                                tmr.alarm(2,speed,1,Light_ALL)
                        end
                
                elseif topic == "bruh/mqttstrip/setbrightnesspub" then
                    --设置亮度
                        --这边我使用的方式是将RGB颜色转为HSL,修改L,在转回RGB的方式来修改
                        local h,s,l = rgb_to_hsl(r,g,b)
                        
                        l = tonumber(data) / 100
                        
                        r,g,b = hsl_to_rgb(h,s,l)
                
                        
                elseif topic == "bruh/mqttstrip/setbrightness" then
                        
                        if nowStage == "E2" then
                        
                                local h,s,l = rgb_to_hsl(r,g,b)
                        
                                l = tonumber(data) / 255
                        
                                r,g,b = hsl_to_rgb(h,s,l)
                                
                        
                        end
                        
                elseif topic == "bruh/mqttstrip/setpower" then
                        --这边是继电器的控制代码
                        
                        if data == "OFF" then
                                if openStage then
                                        tmr.stop(2)
                                        gpio.write(1, gpio.LOW)
                                        openStage = false
                                end
                                
                        elseif data == "ON" then 
                                if not openStage then 
                                        gpio.write(1, gpio.HIGH)
                                        tmr.alarm(2,30,1,Light_ALL)
                                        nowStage = "E2"
                                        openStage = true
                                
                                end
                        end
                
                end

          end
        end)

        --这点填写你的MQTT服务器的IP和端口,如果成功的话,会调用下面的函数
        m:connect("10.0.0.214", 1883, 0, function(client)
          print("connected")
          --下面这5个可以理解为订阅指定topic的消息,收到的消息将在
          --mqtt:on(event, function(client[, topic[, message]]))
          --event为"message"的事件中,就是在上面。。。。
          client:subscribe("bruh/mqttstrip/setpower",0, function(conn) print("subscribe success") end)
          client:subscribe("bruh/mqttstrip/setcolor",0, function(conn) print("subscribe success") end)
          client:subscribe("bruh/mqttstrip/setbrightness",0, function(conn) print("subscribe success") end)
          client:subscribe("bruh/mqttstrip/setanimationspeed",0, function(conn) print("subscribe success") end)
          client:subscribe("bruh/mqttstrip/setbrightnesspub",0, function(conn) print("subscribe success") end)
          client:subscribe("bruh/mqttstrip/seteffect",0, function(conn) print("subscribe success") end)
          
         
        end,
        function(client, reason)
          print("failed reason: " .. reason)
        end)
        
        --m:close();
end

-- --定时器,检查WIFI 状态,这边是启动
tmr.alarm(1, 1000, 1, GetWiFiStage)



        4.3 HA的配置部分,
      
homeassistant:
  # Name of the location where Home Assistant is running
  name: Home
  # Location required to calculate the time the sun rises and sets
  latitude: 0000000
  longitude: 00000000000000
  # Impacts weather/sunrise data (altitude above sea level in meters)
  elevation: 10
  # metric for Metric, imperial for Imperial
  unit_system: imperial
  # Pick yours from here: [url=http://en.wikipedia.org/wiki/List_of_tz_database_time_zones]http://en.wikipedia.org/wiki/List_of_tz_database_time_zones[/url]
  time_zone: Asia/Shanghai
  
  customize:
    sensor.temperature:
      friendly_name: 温度-室内
    binary_sensor.light1:
      friendly_name: 环境光
    sensor.temperature_out:
      friendly_name: 温度-室外
    light.porch_leds:
      friendly_name: '彩色灯带'
      homebridge_hidden: false
      homebridge_name: '彩色灯带'
      emulated_hue: false
      emulated_hue_name: 'porch leds'
# Show links to resources in log and frontend
introduction:

# Enables the frontend
frontend:

# Enables configuration UI
config:

http:
  # Uncomment this to add a password (recommended!)
  # api_password: PASSWORD
  # Uncomment this if you are using SSL or running in Docker etc
  # base_url: example.duckdns.org:8123

# Checks for available updates
# Note: This component will send some information about your system to
# the developers to assist with development of Home Assistant.
# For more information, please see:
# [url=https://home-assistant.io/blog/2016/10/25/explaining-the-updater/]https://home-assistant.io/blog/2016/10/25/explaining-the-updater/[/url]
updater:
  # Optional, allows Home Assistant developers to focus on popular components.
  # include_used_components: true

# Discover some devices automatically
discovery:

# Allows you to issue voice commands from the frontend in enabled browsers
conversation:

# Enables support for tracking state changes over time.
history:

# View all events in a logbook
logbook:

# Track the sun
sun:

# Text to speech
tts:
  platform: google

mqtt:
  broker: 10.0.0.214
  port: 1883
  client_id: home-assistant-1
  keepalive: 60
  username: pi
  password: raspberry
  protocol: 3.1.1

sensor:
  - platform: mqtt
    state_topic: 'office/sensor1'
    name: 'Temperature'
    unit_of_measurement: '°C'
    value_template: '{{ value_json.temperature }}'
  - platform: mqtt
    state_topic: 'office/sensor3'
    name: 'Temperature_out'
    unit_of_measurement: '°C'
    value_template: '{{ value_json.temperature }}'
    
    
binary_sensor:
  - platform: mqtt
    state_topic: "office/sensor2"
    name: "light-1"
    qos: 0
    payload_on: "1"
    payload_off: "0"
    device_class: opening
    value_template: '{{ value_json.light }}' 
    
switch:
  - platform: mqtt
    name: "Bedroom Switch"
    state_topic: "home/bedroom/switch1"
    command_topic: "home/bedroom/switch1/set"
    availability_topic: "home/bedroom/switch1/available"
    payload_on: "ON"
    payload_off: "OFF"
    value_template: '{{ value_json.stage }}' 
    optimistic: false
    qos: 0
    retain: true

light:
  - platform: mqtt
    name: "porch leds"
    command_topic: "bruh/mqttstrip/setpower"
    state_topic: "bruh/mqttstrip/setpowerpub"
    rgb_state_topic: "bruh/mqttstrip/setcolorpub"
    rgb_command_topic: "bruh/mqttstrip/setcolor"
    brightness_state_topic: "bruh/mqttstrip/setbrightnesspub"
    brightness_command_topic: "bruh/mqttstrip/setbrightness"
    optimistic: true
    
input_select:
  porch_led_effect:
    name: '变色效果'
    options:
     - 'E1'
     - 'E2'
    initial: 'E2'

input_slider:
  porch_animation_speed:
    name: "动画速度"
    initial: 30
    min: 15
    max: 200
    step: 10

  w2812_strip_brightness:
    name: '灯光亮度'
    initial: 50
    min: 0
    max: 100
    step: 1
    icon: mdi:brightness-6

automation: 
  - alias: "Porch Input Effect"
    initial_state: true
    hide_entity: false
    trigger:
      - platform: state
        entity_id: input_select.porch_led_effect
    action:
      - service: mqtt.publish
        data_template:
          topic: "bruh/mqttstrip/seteffect"
          payload: '{{ trigger.to_state.state | string }}'

  - alias: "Porch Animation Speed"
    initial_state: true
    hide_entity: false
    trigger:
      - platform: state
        entity_id: input_slider.porch_animation_speed
    action:
      - service: mqtt.publish
        data_template:
          topic: "bruh/mqttstrip/setanimationspeed"
          payload: '{{ trigger.to_state.state | int }}'

  - alias: "w2812_strip_brightness"
    initial_state: true
    hide_entity: false
    trigger:
      - platform: state
        entity_id: input_slider.w2812_strip_brightness
    action:
      - service: mqtt.publish
        data_template:
          topic: "bruh/mqttstrip/setbrightnesspub"
          payload: '{{ trigger.to_state.state | int }}'
#彩色灯带面板分组
group:
  w2812_light:
    view: no
    name: '彩色灯带'
    control: hidden
    entities:
      - light.porch_leds
      - input_select.porch_led_effect
      - input_slider.porch_animation_speed
      - input_slider.w2812_strip_brightness
 
    
      

      









评分

参与人数 2金钱 +15 收起 理由
lidicn + 7 666!能来段视频更好
+ 8 牛了,有没有arduino版本的?

查看全部评分

回复

使用道具 举报

8

主题

657

帖子

4191

积分

论坛元老

Rank: 8Rank: 8

积分
4191
金钱
3529
HASS币
0
QQ
发表于 2017-8-2 15:23:00 来自手机 | 显示全部楼层
前排支持
回复

使用道具 举报

123

主题

4626

帖子

1万

积分

管理员

囧死

Rank: 9Rank: 9Rank: 9

积分
16017
金钱
11306
HASS币
45
发表于 2017-8-2 19:41:35 | 显示全部楼层
经鉴定为好贴,直接30权限
回复

使用道具 举报

30

主题

999

帖子

4119

积分

论坛元老

Rank: 8Rank: 8

积分
4119
金钱
3115
HASS币
0

活跃会员

发表于 2017-8-3 11:51:56 | 显示全部楼层
谢谢分享!!
回复

使用道具 举报

31

主题

188

帖子

1798

积分

论坛技术达人

积分
1798
金钱
1590
HASS币
20

教程狂人论坛风云人物

发表于 2017-8-4 19:32:27 | 显示全部楼层
感谢!!!
回复

使用道具 举报

3

主题

62

帖子

239

积分

中级会员

Rank: 3Rank: 3

积分
239
金钱
177
HASS币
0
发表于 2017-8-22 13:38:03 | 显示全部楼层
谢谢分享, 好东西
回复

使用道具 举报

3

主题

62

帖子

239

积分

中级会员

Rank: 3Rank: 3

积分
239
金钱
177
HASS币
0
发表于 2017-8-22 15:04:28 | 显示全部楼层
WS2812如果12V的还用加电压转换吗?
回复

使用道具 举报

7

主题

157

帖子

803

积分

论坛积极会员

积分
803
金钱
646
HASS币
0
发表于 2017-8-23 12:42:19 来自手机 | 显示全部楼层
现在某宝的nodeMCU貌似都V3的了,一样用吗?
回复

使用道具 举报

3

主题

114

帖子

881

积分

高级会员

Rank: 4

积分
881
金钱
767
HASS币
0
发表于 2018-1-12 20:42:17 | 显示全部楼层
按照楼主的方法配置了一下,wifi 的 api 更新了。wifi.sta.config配置不再有效。
但是还是有一个大 bug,就是只能开不能关,不能识别 MQTT 发送过去的 OFF 指令。
回复

使用道具 举报

39

主题

311

帖子

2905

积分

金牌会员

Rank: 6Rank: 6

积分
2905
金钱
2594
HASS币
0
发表于 2018-4-15 17:04:08 | 显示全部楼层
为什么我的一直提示
Component not found: input_slider

找不到 input_slider是啥原因啊?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Hassbian

GMT+8, 2024-5-3 00:35 , Processed in 0.159964 second(s), 37 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表