Skip to content

Instantly share code, notes, and snippets.

@MinatsuT
Last active December 20, 2020 14:20
Show Gist options
  • Save MinatsuT/26a997fdaae498df21f6bcc94c5f9407 to your computer and use it in GitHub Desktop.
Save MinatsuT/26a997fdaae498df21f6bcc94c5f9407 to your computer and use it in GitHub Desktop.
IR reader for PiSTARTER
' Read signals of IR sensor (active low) via GPIO4.
option strict
acls
var sw,sh,sa:xscreen out sw,sh,sa
var cx,cy,cw,ch:console out cx,cy,cw,ch
gpiomode #GPIO4, #GPIOMODE_IN
backcolor rgb(0,0,128)
main
end
def main
var w=0.1,w1=1-w,thH=0.6,thL=1-thH
var s0=16,s1=s0-2
while 1
var cnt,dur
dim d%[0]
getIR1 out cnt,dur,d%
var msPerCnt=dur/cnt
'locate 0,ch-1
?format$("%d samples, %d ms, %.2f μsec/sample ", cnt,dur,msPerCnt*1000);
gcls:beep 9
var t,b%=0,raw=1,sig=1,last=1
var x=0,y=0,col
var hcnt=0,lcnt=0
for t=0 to cnt-1
raw=raw*w1 + (!d%[t])*w 'Since d% is active low, invert the value
if sig && raw<thL then sig=0
if !sig && raw>thH then sig=1
if !last && sig then
if lcnt then
var hms=hcnt*msPerCnt
var ratio=lcnt/hcnt,v=-1
if hms<1 then
if ratio<4 then v=1
if ratio<2 then v=0
endif
if v!=-1 then
b%=((b%>>1) and &h7fffffff) or (&h80000000)*v 'LSB first
var gxx=x*s0+(s0-8)/2
gputchr gxx,sh-16+1, str$(v)
endif
endif
hcnt=0:lcnt=0:y=0:inc x
endif
last=sig
if sig then inc hcnt:col=#green else inc lcnt:col=#red
var gx=(x+1)*s0-1,gy=sh-1-16-y
gline gx,gy,gx-s1*raw,gy, col
inc t:y=y+0.2
next
var cCode=b% and &hffff,dat=(b%>>16) and &hff,chk=(b%>>24) and &hff
var err=((dat xor chk)!=&hff)
?format$("CustomerCode=%04x Data=%02x Check=%02x ",cCode,dat,chk);
if err then color #red:?"Error" else color #cyan:?"OK"
color #white
wend
end
def getIR1 out cnt,dur,sig%
var t=millisec+200
cnt=0
while millisec<t:inc cnt:wend
dim s%[cnt]
var i,st,ed
'Wait until signal begins
repeat:until !gpioin(#GPIO4)
'Record signal
st=millisec
for i=0 to cnt-1:s%[i]=gpioin(#GPIO4):next
dur=millisec-st
sig%=s%
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment