Tuesday, October 4, 2016

Controlling BYJ48 Stepper Motor from NodeMCU LUA ESP8266

In case you want to control a 28BYJ48 stepper motor from a NodeMCU, here is the way I do it.

This of course is Lua code.

-- 28BYJ-48 Stepper Control
wifi.setmode(wifi.STATION)
wifi.sta.connect()

motor = {}
motor.pin1 = 5 -- this is GPIO14
motor.pin2 = 6 -- this is GPIO12
motor.pin3 = 7 -- this is GPIO13
motor.pin4 = 8 -- this is GPIO15

led = {}
led.pin = 4 -- this is GPIO2
led.isOn = false

server = {}
server.port = 8989

-- setup led as output and turn on
gpio.mode(led.pin,gpio.OUTPUT)
gpio.write(led.pin,gpio.LOW)
led.isOn = true

-- Setup motor pins as out
gpio.mode(motor.pin1, gpio.OUTPUT)
gpio.mode(motor.pin2, gpio.OUTPUT)
gpio.mode(motor.pin3, gpio.OUTPUT)
gpio.mode(motor.pin4, gpio.OUTPUT)
print("Setup all motors as output")

-- Step
loc = 1
function step(val)
loc = loc + val

if loc == 9 then 
loc = 1
elseif loc == 0 then 
loc = 9
end

--print("step " .. loc)
if loc == 1 then
gpio.write(motor.pin1, gpio.LOW)
gpio.write(motor.pin2, gpio.LOW)
gpio.write(motor.pin3, gpio.LOW)
gpio.write(motor.pin4, gpio.HIGH)
elseif loc == 2 then
gpio.write(motor.pin1, gpio.LOW)
gpio.write(motor.pin2, gpio.LOW)
gpio.write(motor.pin3, gpio.HIGH)
gpio.write(motor.pin4, gpio.HIGH)
elseif loc == 3 then
gpio.write(motor.pin1, gpio.LOW)
gpio.write(motor.pin2, gpio.LOW)
gpio.write(motor.pin3, gpio.HIGH)
gpio.write(motor.pin4, gpio.LOW)
elseif loc == 4 then
gpio.write(motor.pin1, gpio.LOW)
gpio.write(motor.pin2, gpio.HIGH)
gpio.write(motor.pin3, gpio.HIGH)
gpio.write(motor.pin4, gpio.LOW)
elseif loc == 5 then
gpio.write(motor.pin1, gpio.LOW)
gpio.write(motor.pin2, gpio.HIGH)
gpio.write(motor.pin3, gpio.LOW)
gpio.write(motor.pin4, gpio.LOW)
elseif loc == 6 then
gpio.write(motor.pin1, gpio.HIGH)
gpio.write(motor.pin2, gpio.HIGH)
gpio.write(motor.pin3, gpio.LOW)
gpio.write(motor.pin4, gpio.LOW)
elseif loc == 7 then
gpio.write(motor.pin1, gpio.HIGH)
gpio.write(motor.pin2, gpio.LOW)
gpio.write(motor.pin3, gpio.LOW)
gpio.write(motor.pin4, gpio.LOW)
elseif loc == 8 then
gpio.write(motor.pin1, gpio.HIGH)
gpio.write(motor.pin2, gpio.LOW)
gpio.write(motor.pin3, gpio.LOW)
gpio.write(motor.pin4, gpio.HIGH)
end
end

function fwd()
step(1)
end

function rev()
step(-1)
end

cmd = ""
function receiveData(conn, data)
    cmd = cmd .. data

    local a, b = string.find(cmd, "\n", 1, true)   
    while a do
        print("Cmd:" .. string.sub(cmd, 1, a-1) )
        cmd = string.sub(cmd, a+1, string.len(cmd))
        a, b = string.find(cmd, "\n", 1, true)
    end 
end

srv = net.createServer(net.TCP, 28800) 
srv:listen(server.port,function(conn)
    print("ChiliPeppr Stepper Connected")
    conn:send("connected ok\n")
     
    conn:on("receive",receiveData)  
    
    conn:on("disconnection",function(c) 
        print("ChiliPeppr Stepper Disconnected")
    end)
    
end)

print(wifi.sta.getip())

-- Setup timer for going forward
tmr.alarm(0, 2, 1, rev)

No comments:

Post a Comment