Here’s some code that will read a 12 digit UPC barcode. Align the barcode in the square so that there is some white space before and after the barcode. Tap the screen and there will be a red and green stripe where the program is trying to read the barcode. It will keep trying to read the barcode until it’s complete. Once complete, the digits of the barcode will be displayed. To stop reading or to read another barcode, tap the screen again. There is a parameter called “GreenRed” that’s adjustable. The purpose of this is to try and balance the size of the bars with the size of the spaces between the bars. The first bar, the white space, and the second bar should be the same size of red and green. The value I have as default seems to work well. Not every barcode will be read. The barcode should be well lighted and be very sharp.
displayMode(FULLSCREEN)
function setup()
parameter.integer("GreenRed",6000,13000,8800)
spriteMode(CORNER)
cameraSource(CAMERA_BACK)
digits={"3211","2221","2122","1411","1132","1231","1114","1312","1213","3112"}
ends={"111"}
middle={"11111"}
div=6
setup1()
end
function setup1()
upc=""
err=true
try=false
img=nil
end
function draw()
background(40, 40, 50)
fill(255)
if img~=nil then
sprite(img,WIDTH/2-250,HEIGHT/2-250)
else
sprite(CAMERA,0,0)
end
if upc~="" then
fontSize(30)
text(upc,WIDTH/2,100)
else
noFill()
stroke(255)
strokeWidth(4)
rect(WIDTH/2-250,HEIGHT/2-250,500,500)
end
if err and try then
getBar()
end
end
function getBar()
i=image(CAMERA)
img=i:copy(WIDTH/2-250,HEIGHT/2-250,500,500)
readBar()
decode()
for z=10,490 do
img:set(z,250,255,0,0)
end
end
function touched(t)
if t.state==BEGAN then
if try then
setup1()
return
end
try=true
end
end
function getDigit(d)
for z=1,10 do
if d==digits[z] then
upc=upc..z-1
return
end
end
err=true
end
function decode()
s=string.sub(str,2,4)--start
getDigit(string.sub(str,5,8))
getDigit(string.sub(str,9,12))
getDigit(string.sub(str,13,16))
getDigit(string.sub(str,17,20))
getDigit(string.sub(str,21,24))
getDigit(string.sub(str,25,28))
m=string.sub(str,29,33)--middle
getDigit(string.sub(str,34,37))
getDigit(string.sub(str,38,41))
getDigit(string.sub(str,42,45))
getDigit(string.sub(str,46,49))
getDigit(string.sub(str,50,53))
getDigit(string.sub(str,54,57))
e=string.sub(str,58,60)--end
end
function readBar()
err=false
upc=""
str=""
p=0
count=0
bar=0
for x=10,490 do
t=0
for z=1,20 do
r,g,b=img:get(x,250+z)
t=t+r+g+b
end
count = count + 1
for z=1,25 do
if t<GreenRed then
img:set(x,250+z,255,0,0)
c=1
else
img:set(x,250+z,0,255,0)
c=0
end
end
if c~=p then
bar = bar + 1
if bar==2 then
div=count
end
p=c
v=math.floor(count/div)
if v==0 then
v=1
end
str=str..v
count=0
end
end
end