How to concatenate bytes in custom protocol for bluetooth serial

Viewed 145

I want to create a custom protocol to send some data across a Bluetooth connection. The idea is to have a start byte and to end the frame with a checksum. The data consists of both signed and unsigned 8, 16 and 32 bits integers.

From various pieces of code found across this site and the rest of the internet I have put together the following with some dummy data to verify the result:

local function checksum(val)
    c = 0
    for i = 0, string.len(val), 1 do
        c = bit32.bxor(c, string.byte(val, i))
    end
    return string.char(c)
end

local function i32(val)
    local b32HH = bit32.band(bit32.rshift(val, 24), 0xff);
    local b32HL = bit32.band(bit32.rshift(val, 16), 0xff);
    local b32LH = bit32.band(bit32.rshift(val, 8), 0xff);
    local b32LL = bit32.band(val, 0xff);
    return string.char(b32HH, b32HL, b32LH, b32LL)
end

local function i16(val)
    local b16H = bit32.band(bit32.rshift(val, 8), 0xff);
    local b16L = bit32.band(val, 0xff);
    return string.char(b16H, b16L)
end

local function i8(val)
    local b8 = bit32.band(val, 0xff);
    return string.char(b8)
end

local function sendFrame()
    local a = 2059368940    -- int32    4 bytes
    local b = -1201540427   -- int32    4 bytes
    local c = 682519180     -- int32    4 bytes
    local d = 38331         -- uint16   2 bytes
    local e = 1643          -- uint16   2 bytes
    local f = 177           -- uint8    1 byte

    local frame = string.char(0x17) -- start byte, just a random value
    frame = frame .. i32(a)
    frame = frame .. i32(b)
    frame = frame .. i32(c)
    frame = frame .. i16(d)
    frame = frame .. i16(e)
    frame = frame .. i8(f)
    frame = frame .. checksum(frame)
    println(frame)
end

sendFrame()

When I run this in Lua 5.2 I get this error:

$lua main.lua
lua: main.lua:45: attempt to call a nil value (global 'println')
stack traceback:
    main.lua:45: in local 'sendFrame'
    main.lua:48: in main chunk
    [C]: in ?

Apparently my concatenation of strings to make the frame results in a nil value, but I cannot find out why.

1 Answers

It is because you are using println() on line 45. println() is not a command in Lua, you just want to be using the good old fashion print(). If you do not want a newline character at the end do an io.write() instead.

Related