RFID scanner doesn't scan afterwards - python

I am very new to coding and I'm working on this project that I have no idea why is it not running as expected. I am sorry if I'm not posting this correctly because this is my first time posting on stackoverflow. Pardon my English if there's any point where I didn't explain it correctly.
This is a project supposed to be a security system one, where we work with RFID Scanner, Camera, LED, Servo and PIR Sensor.
The conditions are as, when the time is 7am to 11pm, the pir sensor would be off and when time is 11pm onwards to 7am in the morning, the PIR sensor and camera will be turned on. Where during anytime, as long as the number of people in the house is = 0 (determined by the RFID), the camera and PIR Sensor would turn on too.
I haven't got a chance to even test out my code's logic, because when I tried to run the code, an error occurs at the loop part. "Scan a registered card to skip registration" would print and "checkpoint" would print, but afterward the code just stops there. It is supposed to be listening to the RFID scanner to read for scans, but when I tapped my card on the RFID scanner there was no response. And my code just dies there. As I'm very new to coding and python, I don't know where the errors could be. Would appreciate the help given!!
import RPi.GPIO as GPIO
from time import sleep
import sys
import requests
from datetime import datetime
from mfrc522 import SimpleMFRC522 #RFID
import os
import pygame, sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from pygame.locals import *
import pygame.camera
width = 640
height = 480
#initialise pygame
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(width,height))
no=0
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(24,GPIO.OUT) #LED
GPIO.setup(26,GPIO.OUT) #Servo
GPIO.setup(17,GPIO.IN) #PIR Sensor
current_time =datetime.now() #Current time
sleep(5)
reader = SimpleMFRC522() #RFID reader
auth = []
in_house =[]
p = open("presentlist.txt","a+")
p = open("presentlist.txt","r+")
present = 0
PIR_state =0
PWM=GPIO.PWM(26,50) #Set 50hz PWM output at GPIO26
PWM.start(12) #To edit to actual 3oclock (Locked)
fromaddr = "pythonprogramtest123#gmail.com" # change the email address accordingly
toaddr = "pythonprogramtest123#gmail.com" # Same email
#password: abcdefgpython
mail = MIMEMultipart()
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "Attachment"
body = "Unusual movement detected"
print('Door Locked')
print("Hold card near the reader to register it in the database.")
print("Registration up to 10 cards")
print("Scan a registered card to skip registration")
for count in range (0,11):
print("checkpoint1")
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
print("checkpoint2")
if f.mode == "r+":
auth=f.read()
if id not in auth:
f.write(id)
f.write('\n')
f.close()
pos = auth.count('\n')
print("New card with UID", id, "detected: registered as entry #",pos)
count = count +1
else:
number = auth.split('\n')
pos = number.index(id)
print("Card with UID", id, "already registered as entry #", pos)
count = 11
break
while (True):
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
if current_time.hour >= 7 or current_time.hour <= 23 or present == 0: #awake or nobody in house
#RFID is on
if f.mode == "r+":
auth=f.read()
if id in auth and id not in in_house:
p.write(id)
p.write('\n')
p.close()
present = in_house.count('\n')
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
break
elif id in auth and id in in_house:
p.remove(id)
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
break
else:
print("Card not recognised \n Access Denied")
break
elif current_time.hour < 7 or current_time.hour > 23: #sleeping
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
#RFID is on
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
break
else:
print("Card not recognised \n Access Denied")
break
#Camera
if GPIO.input(17): #read a HIGH i.e. motion is detected
#LED Blink
GPIO.output(24,1)
sleep(1)
GPIO.output(24,0)
sleep(1)
GPIO.output(24,1)
sleep(1)
GPIO.output(24,0)
if PIR_state==0:
print('detected HIGH i.e. motion detected')
PIR_state=1
#Camera
cam.start() #start
image = cam.get_image() #take pic
cam.stop()
no = no + 1
saved_img=pygame.image.save(windowSurfaceObj,'picture' + "{:03d}".format(no) + '.jpg')
#Thingspeak
print("Updating Thingpseak")
resp = requests.get("GET https://api.thingspeak.com/update?api_key=PQ44ZG5JR49ABODY&field1=0")
#Email
def sendMail(data):
mail.attach(MIMEText(body, 'plain'))
print (data)
dat='%s.jpg'%data
print (dat)
attachment = open(dat, 'rb')
image=MIMEImage(attachment.read())
attachment.close()
mail.attach(image)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "abcdefgpython")
text = mail.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
else: #read a LOW i.e. no motion is detected
if PIR_state==1:
print('detected LOW i.e. no motion detected')
PIR_state=0
sleep(1)
print("...")
break
sleep(2)

Related

Telegram bot doorbell - Raspberry Pi

I'm new to python and raspberry, I would like to make a smart doorbell controlled by a bot on telegram. The doorbell in question has a pir sensor that sends a video over telegram every time its triggered. I would like to have the messages I send to the bot read through the speakers.
But I have a problem with the while true loop of the sensor and the handle (msg) function of telepot, I need to take the chat_id variable out of the handle function to use it in the other functions but I can't. I am attaching the complete code:
import telepot
from picamera import PiCamera
import RPi.GPIO as GPIO
import time
from time import sleep
import datetime
from telepot.loop import MessageLoop
from subprocess import call
import sys
import random
import pyttsx3
# setup sensori
PIR = 4
camera = PiCamera()
camera.resolution = (680, 480)
camera.framerate = 25
camera.rotation = 180
# setup pin
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR, GPIO.IN)
# variabili movimento
motion = 0
motionNew = 0
# telegram bot
def handle(msg):
global telegramText
global chat_id
chat_id = msg['chat']['id']
telegramText = msg['text']
print('Messaggio ricevuto! ' + str(chat_id) + telegramText)
# start engine per leggere i messaggi
engine = pyttsx3.init()
rate = engine.getProperty('rate') # variabile per cambiare velocita
engine.setProperty('rate', rate-50) # velocita voce
voice_id = 'italian'
engine.setProperty('voice', voice_id)
engine.say(telegramText)
engine.runAndWait()
if telegramText == '/start':
bot.sendMessage(chat_id, 'Sicurezza del perimetro attiva, sei protetto!')
# connessione bot telegram
bot = telepot.Bot('####')
bot.message_loop(handle)
# definizione funzione principale movimento
def main():
global chat_id
global motion
global motionNew
if GPIO.input(PIR) == 1:
print("Movimento rilevato!")
motion = 1
if motionNew != motion:
motionNew = motion
sendNotification()
elif GPIO.input(PIR) == 0:
motion = 0
if motionNew != motion:
motionNew = motion
def sendNotification():
global chat_id
bot.sendMessage(chat_id, 'ATTENZIONE! Qualcuno è alla porta!')
filename = "./video_" + (time.strftime("%y%b%d_%H%M%S"))
camera.start_recording(filename + ".h264")
sleep(10)
camera.stop_recording()
command = "MP4Box -add " + filename + '.h264' + " " + filename + '.mp4'
print(command)
call([command], shell=True)
bot.sendVideo(chat_id, video=open(filename + '.mp4', 'rb'))
print('Attendo 20 secondi')
time.sleep(20)
# definizione interrupt
def end_security():
print('End')
# check continuo sensore pir
try:
while True:
main()
except KeyboardInterrupt:
end_security()
I get an error in this line:
bot.sendMessage(chat_id, 'ATTENZIONE! Qualcuno è alla porta!')
error:
NameError: name 'chat_id' is not defined
How can I manage it? Thank you
I think the problem is that when you call sendNotification() before handle() has been called then chat_id has not been set by anything so is undefined.
If you change your main loop code to the following, then you shouldn't get the error, since chat_id will be defined to a value at the beginning of the program.
try:
chat_id=999999999
while True:
main()
However, I'm not sure what you want chat_id to be set to when you call sendNotification() from the main() function since you don't have a message to take it from? Do you really need chat_id to be a global. It may be better to pass the chat id into sendNotification() as a parameter.

Why does my function not execute when the condition is met?

I'm trying to make a login form for my server application and have stumbled onto an invisible error (the worst kind). I have a tries variable that increments by 1 every time the user enters the username incorrectly. When the tries variable reaches 3, the program should then execute the block() function. My issue is that it doesn't.
All my .txt files are blank so there's not an error there and everything seems fine. Please help because I'm pulling my hair out!
Here's the code:
import socket
import time
import sys
import os
tries = 0
def server():
def block():
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
#create black list
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#disable account for 60 seconds
if ipBlock in isBlocked:
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print('Your account has been temporarily disabled. Please
try again in '+timer, end=" seconds.\r")
time.sleep(1)
t -= 1
os.remove('ipBlackList.txt')
print('\nYour account has been re-enabled. You may log in
now.')
time.sleep(2)
t = 60
countdown(int(t))
block()
print("Enter administrator login details: ")
def usernameLogin():
#global vars
global tries
if tries == 3:
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
if ipBlock not in isBlocked:
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.write(ipBlock)
ipBlackList.close()
block()
username = input("\nUsername: ")
#check if username exists
usernames = open("usernames.txt", "r")
checkUser = usernames.readlines()
usernames.close()
if username not in checkUser:
print("That username doesn't exist. Please try again.")
tries += 1
print(tries)
time.sleep(2)
usernameLogin()
print("im in")
time.sleep(3)
usernameLogin()
server()
In fact, your code do execute the block() function when tries==3, but in the begining of the block() you recreate the black list file, then you read the empty file and as a result the condition if ipBlock in isBlocked: is always false.
So, I've placed the commands that create the file out of the block(). Also, I've changed the remove of the black list file in the countdown() function and recreate but not delete it, because your code try to read it again when restarts to ask the username. Also I've set tries == 0 when block() ends. Also, the indentation at the end of countdown() was incorrect.
import socket
import time
import sys
import os
tries = 0
def server():
def block():
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#disable account for 60 seconds
if ipBlock in isBlocked:
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print('Your account has been temporarily disabled. Please \
try again in '+timer, end=" seconds.\r")
time.sleep(1)
t -= 1
#os.remove('ipBlackList.txt')
# Recreate an empty black list file
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
print('\nYour account has been re-enabled. You may log in \
now.')
time.sleep(2)
t = 6
countdown(int(t))
#create black list file (empty)
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
block()
print("Enter administrator login details: ")
def usernameLogin():
#global vars
global tries
if tries == 3:
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
if ipBlock not in isBlocked:
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.write(ipBlock)
ipBlackList.close()
block()
tries = 0
username = input("\nUsername: ")
#check if username exists
usernames = open("/test/usernames.txt", "r")
checkUser = usernames.readlines()
usernames.close()
if username not in checkUser:
print("That username doesn't exist. Please try again.")
tries += 1
print(tries)
time.sleep(2)
usernameLogin()
print("im in")
time.sleep(3)
usernameLogin()
server()

GPIO random input, Difference between scripts?

So I am currently working on a Raspberry Pi Project.
My Raspi is connected to my letterbox, so everytime someone opens it, a button is pushed. When the button is pushed, a script should detect this and send me an EMail, and write the current Time and Date in a .txt file.
My script that I made a little bit by my self and with the help of the internet, works, but it randomly detects a GPIO input every 10-20 Minutes (the Wires that are connected to the button are very long and my Raspi is connected in a room that is full with cabels, this might be the Problem). But, I tried to do it with a script that I just found on the internet. Just copy it (well, at least the GPIO part). So this script works, but mine detects a random input.
Another Problem (you'll see it in the script) that I had with an old script was, that I used a while loop, and it used 97% of my CPU. So I did another script that would work differently. It doesnt use 97% of my CPU, but it detects random Inputs. In the script that I copied from the internet also uses a while loop, but it doesnt take that much CPU. But why? I dont understand that either.
This is my Script, that detects random Inputs:
import RPi.GPIO as GPIO
import smtplib
import pytz
from pytz import timezone
import datetime
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(7,GPIO.IN,)
def writeanemail():
smtpUser = ''
smtpPass = ''
toAdd = ''
fromAdd = smtpUser
subject = 'Du hast etwas in deinem Postfach'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
print ("\n" + header)
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser, smtpPass)
s.sendmail(fromAdd, toAdd, header)
s.quit()
def timelog():
now = datetime.datetime.now(timezone('Europe/Berlin'))
file = open("/home/pi/ps/gpio.log","a")
file.write("\n" + now.strftime("%Y-%m-%d--%a %H:%M:%S"))
file.close()
print ("\n" + now.strftime("%Y-%m-%d--%a %H:%M") + "\n" + "\n" + "Log wurde geschrieben")
def main():
GPIO.wait_for_edge(7, GPIO.FALLING, bouncetime = 150)
print ("Knopf wurde gedrueckt, E-Mail wird geschickt.")
sleep(1)
writeanemail()
timelog()
sleep(10)
main()
main()
And this is the copied one, that works fine:
import RPi.GPIO as GPIO
from pytz import timezone
import datetime
# SET GPIO Button-Pin
gpio = 7
def writeanemail():
smtpUser = ''
smtpPass = ''
toAdd = ''
fromAdd = smtpUser
subject = 'Du hast etwas in deinem Postfach'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
print ("\n" + header)
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser, smtpPass)
s.sendmail(fromAdd, toAdd, header)
s.quit()
# Main Function
def main():
value = 0
while True:
if not GPIO.input(gpio):
value += 0.01
if value > 0:
if GPIO.input(gpio):
print "gedrueckt"
now = datetime.datetime.now(timezone('Europe/Berlin'))
file = open("/home/pi/ps/gpio.log","a")
file.write("\n" + now.strftime("%Y-%m-%d--%a %H:%M:%S"))
file.close()
writeanemail()
main()
time.sleep(0.03)
return 0
if __name__ == '__main__':
GPIO.setmode(GPIO.BCM)
GPIO.setup(gpio, GPIO.IN)
main()
Here I copied only the main function, the Email part is the same.
I am thankful for any help and advice.

My python script doesn't work completely to send emails when a button is pressed

Howdy and good afternoon. I am pretty much a NOOB on with programming. I had a friend help me with a python script that when the button is pressed it will turn an led on and send an email message. When the button is pressed and held for more than 2 seconds and released it is supposed to turn the led of and send a separate email. The first "normal" email sends everytime even when the button is pressed and held, but the "Important" email doesn't send, however the led does turn off.
I am running Ubuntu Mate on a Raspberry PI 3
Here is part of the script.
import RPi.GPIO as GPIO
import time
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import datetime
body = "Email message"
sender = "Room 202 Help"
subject = "Room 202 Help Button"
to = ""
stmpAddress = "smtp.gmail.com"
username = ""
password = ""
normalBody = "Help needed in room 202"
importantBody = "Request Canceled Room 202"
ledPin = 23
buttonPin = 18
importantPress = 2 #seconds
GPIO.setmode(GPIO.BCM)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #makes the pin stay high another words it is set to about 3 volts
GPIO.setup(ledPin, GPIO.OUT) #makes the pin be an output
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = to
msg['Subject'] = subject
GPIO.output(ledPin,GPIO.LOW)
while True:
buttonPress = GPIO.input(buttonPin)
if buttonPress == False: #is the pin low?
GPIO.output(ledPin,GPIO.HIGH)#turn on the led
print('Button Pressed')#Yes it is low meaning it was shorted to ground
buttonPressStart = datetime.datetime.now() #Time the button got pressed
while GPIO.input(buttonPin) == False: # while it is still low
time.sleep(0.1)#stay here till they let go of the button
buttonPressEnd = datetime.datetime.now() # time the button was let go
diff = buttonPressEnd - buttonPressStart#the differnce of when the button got pressed and let go, duration on button press
if diff > datetime.timedelta(seconds = importantPress):
msg.attach(MIMEText(importantBody, 'plain'))
GPIO.output(ledPin,GPIO.LOW)#turn off the led if it's on
print("Canceling")
else:
msg.attach(MIMEText(normalBody, 'plain'))
server = smtplib.SMTP(stmpAddress, 587)
server.starttls()
server.login(username, password)
server.sendmail(username, to, msg.as_string())
server.quit()#email sent
time.sleep(0.01)#sleep a short time so to not eat all resources
Going off an answer posted on the Raspberry Pi forum, you can see how long a button was pressed as such:
while True:
GPIO.wait_for_edge(PIN, GPIO.FALLING)
print "Pressed"
start = time.time()
time.sleep(0.2)
while GPIO.input(PIN) == GPIO.LOW:
time.sleep(0.01)
length = time.time() - start
print length

Why does AT86RF231 not send my data?

I've been searching the web for days now and neither the web nor the manual helped me.
In fact I want a simple send and receive routine in Python for the AT86RF231. Both radios are plugged on a raspberry pi.
I think all the registers are set up properly but when trying to send a packet, there is nothing received on the receiver side and the IRQ TRX_END is not raised as well.
The implemented "test mode" does not work for me as well and I can't figure out why.
The datasheet is available here.
# -*- coding: utf-8 -*-
import spidev
import time
import RPi.GPIO as GPIO
import binascii
import string
import random
#Definitions
dont_care = 0
nRST = 27
#Abkürzung
spi=spidev.SpiDev()
#make sure /RST is high
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#GPIO 27 als Output konfigurieren
GPIO.setup(nRST, GPIO.OUT)
GPIO.output(nRST,GPIO.HIGH)
#Reset
def reset():
GPIO.output(nRST,GPIO.LOW)
time.sleep(0.001)
GPIO.output(nRST,GPIO.HIGH)
while (read(0x01,0)[1]!= 0 | read(0x01,0)[1]!= 8):
time.sleep(0.001)
print "Reset complete"
# get Device ID
def DevID():
ID = spi.xfer2([0x9C,0])
print "ID:"
print ID
#write data
def write(addr, value):
spi.xfer2([addr | 0xC0, value])
#read data
def read(addr, value):
data = spi.xfer2([addr | 0x80, value])
return data
#read framebuffer
def frameread():
output = spi.xfer2([0x20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
return output
#read transmissionstatus
def transstatus():
status = read(0x01,0)[1]
print status
if (status == 0):
print "P_ON"
elif (status == 1):
print "Busy_RX"
elif (status== 2):
print "Busy_TX"
elif (status == 6):
print "RX_ON"
elif (status==8):
print "TRX_Off"
else :
print "Kontrolle des Status nötwendig"
#?
def status():
status = spi.xfer2([0x81, 0])
if (status[1]==0):
print "Status: default"
elif (status[1]==1):
print "Status: monitor TRX_Status"
elif (status[1]==2):
print "Status: monitor PHY_RSSI"
elif (status[1]==3):
print "Status: monitor IRQ_Statis"
return status[1]
#Continuous Transmission Test Mode
#Register werden in der Anleitung beschrieben
def testmode():
reset()
DevID()
write(0x0E, 0x01)
write(0x04, 0x00)
write(0x02, 0x03)
write(0x03, 0x01)
write(0x08, 0x33)
write(0x05, 0x00)
status()
while(read(0x01, 0x00) == 8):
time.sleep(0.1)
print "Transmission in progress - waiting"
write(0x036, 0x0F)
# hier muss der Inhalt beschrieben werden
#0x60 Frame write Acess,10 Frames, Inhalt
spi.xfer2([0x60,0x0A,1,2,6,4,5,6,7,8,9,10])
write(0x1C, 0x54)
write(0x1C, 0x46)
write(0x02, 0x09)
print read(0x0F, 0x01)
while(read(0x0F, 0x01)[1]!=0):
time.sleep(0.1)
print "Waiting for PLL_Lock"
write(0x02, 0x02)
#Messung
transstatus()
print "Messung durchführen"
time.sleep(10)
write(0x1C, 0x00)
#Reset machen
reset()
#enable receiver
def receiver_enable():
write(0x02,0x08)
write(0x02,0x06)
# make randomisierte Pakete
def id_generator(size,chars=string.digits):
return ''.join(random.choice(chars) for _ in range(size))
#generate Frame
def make_frame(length, power, transmission_type):
data = id_generator(length)
dataframe = []
dataframe.append(length + 2)
dataframe.append(power)
dataframe.append(transmission_type)
for i in range(0,len(data),1):
dataframe.append(data[i])
return dataframe
# send frame
def send_frame(frame):
write(0x0E, 0x01)
write(0x04, 0x00)
write(0x02, 0x03)
write(0x08, 0x33)
write(0x05, 0x00)
write_frame(frame)
while (read(0x01,0)[1] != 8):
time.sleep(0.1)
print "Waiting for TRX_OFF"
write(0x02, 0x09)
time.sleep(.1)
while(read(0x01,0)[1] != 9):
time.sleep(0.1)
print "Waiting for PLL_Lock"
#TX start
write(0x02, 0x02)
while(read(0x01, 0)[1] == 2):
time.sleep(0.1)
print "Busy TX"
#set transmit power 1-16
def set_power(power):
write(0x05, power)
# Framebuffer write
def write_frame(data):
if isinstance(data, basestring):
spi.xfer2([0x60,len(data)] + [int(ord(i)) for i in list(data)])
else:
print "bin heir"
dataframe = []
dataframe.append(0x60)
dataframe.append(len(data))
for i in range(0,len(data),1):
dataframe.append(int(data[i]))
print dataframe
spi.xfer2(dataframe)
sender routine
spi.open(0,0)
reset()
while(1):
testmode()
time.sleep(1)
spi.close()
receiver routine
spi.open(0,0)
reset()
receiver_enable()
while(1):
print frameread()
spi.close()
Found a solution by myself. The selected Channel was actually wrong. 0x33 was in the manual given but this Channel does not exist. Change this in transmitter and receiver register and everything will work like charm.

Categories