My goal is to use dual RFID RC522 readers with Orange PI.
So far, I have managed to make only one working. (reading google, armbian and orange pi forums). Here is what I have done so far:
Hardware connection:
single RC 522
MOSI ——————————> pin 19
MISO ——————————-> pin 21
SCLK ——————————-> pin 23
SDA ——————————–> pin 24
RST ———————————> pin 22
IRQ ———————————-> NONE
Second reader uses shared pins, except SDA, it goes to pin 26 on orange PI
software:
Install python dev
apt-get install python-dev
Install orangepi_PC_gpio_pyH3 Library
git clone https://github.com/duxingkei33/orangepi_PC_gpio_pyH3.git
cd orangepi_PC_gpio_pyH3
python setup.py install
Install SPI-Py Library
git clone https://github.com/lthiery/SPI-Py.git
cd SPI-Py
python setup.py install
Install MFRC522-python
git clone https://github.com/rasplay/MFRC522-python.git
The tricky part is, MFRC522-python is made to work with RASPBERRY PI on orange pi, one guy offered a solution by modifying MFRC522.py
#import RPi.GPIO as GPIO
import pyA20.gpio as GPIO
import spi
import signal
class MFRC522:
NRSTPD = 22
MAX_LEN = 16
PCD_IDLE = 0x00
PCD_AUTHENT = 0x0E
PCD_RECEIVE = 0x08
PCD_TRANSMIT = 0x04
PCD_TRANSCEIVE = 0x0C
PCD_RESETPHASE = 0x0F
PCD_CALCCRC = 0x03
PICC_REQIDL = 0x26
PICC_REQALL = 0x52
PICC_ANTICOLL = 0x93
PICC_SElECTTAG = 0x93
PICC_AUTHENT1A = 0x60
PICC_AUTHENT1B = 0x61
PICC_READ = 0x30
PICC_WRITE = 0xA0
PICC_DECREMENT = 0xC0
PICC_INCREMENT = 0xC1
PICC_RESTORE = 0xC2
PICC_TRANSFER = 0xB0
PICC_HALT = 0x50
MI_OK = 0
MI_NOTAGERR = 1
MI_ERR = 2
Reserved00 = 0x00
CommandReg = 0x01
CommIEnReg = 0x02
DivlEnReg = 0x03
CommIrqReg = 0x04
DivIrqReg = 0x05
ErrorReg = 0x06
Status1Reg = 0x07
Status2Reg = 0x08
FIFODataReg = 0x09
FIFOLevelReg = 0x0A
WaterLevelReg = 0x0B
ControlReg = 0x0C
BitFramingReg = 0x0D
CollReg = 0x0E
Reserved01 = 0x0F
Reserved10 = 0x10
ModeReg = 0x11
TxModeReg = 0x12
RxModeReg = 0x13
TxControlReg = 0x14
TxAutoReg = 0x15
TxSelReg = 0x16
RxSelReg = 0x17
RxThresholdReg = 0x18
DemodReg = 0x19
Reserved11 = 0x1A
Reserved12 = 0x1B
MifareReg = 0x1C
Reserved13 = 0x1D
Reserved14 = 0x1E
SerialSpeedReg = 0x1F
Reserved20 = 0x20
CRCResultRegM = 0x21
CRCResultRegL = 0x22
Reserved21 = 0x23
ModWidthReg = 0x24
Reserved22 = 0x25
RFCfgReg = 0x26
GsNReg = 0x27
CWGsPReg = 0x28
ModGsPReg = 0x29
TModeReg = 0x2A
TPrescalerReg = 0x2B
TReloadRegH = 0x2C
TReloadRegL = 0x2D
TCounterValueRegH = 0x2E
TCounterValueRegL = 0x2F
Reserved30 = 0x30
TestSel1Reg = 0x31
TestSel2Reg = 0x32
TestPinEnReg = 0x33
TestPinValueReg = 0x34
TestBusReg = 0x35
AutoTestReg = 0x36
VersionReg = 0x37
AnalogTestReg = 0x38
TestDAC1Reg = 0x39
TestDAC2Reg = 0x3A
TestADCReg = 0x3B
Reserved31 = 0x3C
Reserved32 = 0x3D
Reserved33 = 0x3E
Reserved34 = 0x3F
serNum = []
def __init__(self,spd=1000000):
spi.openSPI(speed=spd)
# GPIO.setmode(GPIO.BOARD)
# GPIO.setup(22, GPIO.OUT)
# GPIO.output(self.NRSTPD, 1)
self.MFRC522_Init()
def MFRC522_Reset(self):
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)
def Write_MFRC522(self,addr,val):
spi.transfer(((addr<<1)&0x7E,val))
def Read_MFRC522(self,addr):
val = spi.transfer((((addr<<1)&0x7E) | 0x80,0))
return val[1]
def SetBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg)
self.Write_MFRC522(reg, tmp | mask)
def ClearBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg);
self.Write_MFRC522(reg, tmp & (~mask))
def AntennaOn(self):
temp = self.Read_MFRC522(self.TxControlReg)
if(~(temp & 0x03)):
self.SetBitMask(self.TxControlReg, 0x03)
def AntennaOff(self):
self.ClearBitMask(self.TxControlReg, 0x03)
def MFRC522_ToCard(self,command,sendData):
backData = []
backLen = 0
status = self.MI_ERR
irqEn = 0x00
waitIRq = 0x00
lastBits = None
n = 0
i = 0
if command == self.PCD_AUTHENT:
irqEn = 0x12
waitIRq = 0x10
if command == self.PCD_TRANSCEIVE:
irqEn = 0x77
waitIRq = 0x30
self.Write_MFRC522(self.CommIEnReg, irqEn|0x80)
self.ClearBitMask(self.CommIrqReg, 0x80)
self.SetBitMask(self.FIFOLevelReg, 0x80)
self.Write_MFRC522(self.CommandReg, self.PCD_IDLE);
while(i<len(sendData)):
self.Write_MFRC522(self.FIFODataReg, sendData[i])
i = i+1
self.Write_MFRC522(self.CommandReg, command)
if command == self.PCD_TRANSCEIVE:
self.SetBitMask(self.BitFramingReg, 0x80)
i = 2000
while True:
n = self.Read_MFRC522(self.CommIrqReg)
i = i - 1
if ~((i!=0) and ~(n&0x01) and ~(n&waitIRq)):
break
self.ClearBitMask(self.BitFramingReg, 0x80)
if i != 0:
if (self.Read_MFRC522(self.ErrorReg) & 0x1B)==0x00:
status = self.MI_OK
if n & irqEn & 0x01:
status = self.MI_NOTAGERR
if command == self.PCD_TRANSCEIVE:
n = self.Read_MFRC522(self.FIFOLevelReg)
lastBits = self.Read_MFRC522(self.ControlReg) & 0x07
if lastBits != 0:
backLen = (n-1)*8 + lastBits
else:
backLen = n*8
if n == 0:
n = 1
if n > self.MAX_LEN:
n = self.MAX_LEN
i = 0
while i<n:
backData.append(self.Read_MFRC522(self.FIFODataReg))
i = i + 1;
else:
status = self.MI_ERR
return (status,backData,backLen)
def MFRC522_Request(self, reqMode):
status = None
backBits = None
TagType = []
self.Write_MFRC522(self.BitFramingReg, 0x07)
TagType.append(reqMode);
(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)
if ((status != self.MI_OK) | (backBits != 0x10)):
status = self.MI_ERR
return (status,backBits)
def MFRC522_Anticoll(self):
backData = []
serNumCheck = 0
serNum = []
self.Write_MFRC522(self.BitFramingReg, 0x00)
serNum.append(self.PICC_ANTICOLL)
serNum.append(0x20)
(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,serNum)
if(status == self.MI_OK):
i = 0
if len(backData)==5:
while i<4:
serNumCheck = serNumCheck ^ backData[i]
i = i + 1
if serNumCheck != backData[i]:
status = self.MI_ERR
else:
status = self.MI_ERR
return (status,backData)
def CalulateCRC(self, pIndata):
self.ClearBitMask(self.DivIrqReg, 0x04)
self.SetBitMask(self.FIFOLevelReg, 0x80);
i = 0
while i<len(pIndata):
self.Write_MFRC522(self.FIFODataReg, pIndata[i])
i = i + 1
self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
i = 0xFF
while True:
n = self.Read_MFRC522(self.DivIrqReg)
i = i - 1
if not ((i != 0) and not (n&0x04)):
break
pOutData = []
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
return pOutData
def MFRC522_SelectTag(self, serNum):
backData = []
buf = []
buf.append(self.PICC_SElECTTAG)
buf.append(0x70)
i = 0
while i<5:
buf.append(serNum[i])
i = i + 1
pOut = self.CalulateCRC(buf)
buf.append(pOut[0])
buf.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
if (status == self.MI_OK) and (backLen == 0x18):
print "Size: " + str(backData[0])
return backData[0]
else:
return 0
def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
buff = []
buff.append(authMode)
buff.append(BlockAddr)
i = 0
while(i < len(Sectorkey)):
buff.append(Sectorkey[i])
i = i + 1
i = 0
while(i < len(serNum)):
buff.append(serNum[i])
i = i +1
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT,buff)
if not(status == self.MI_OK):
print "AUTH ERROR!!"
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
print "AUTH ERROR(status2reg & 0x08) != 0"
return status
def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not(status == self.MI_OK):
print "Error while reading!"
print "Got data size: "+str(backLen)
i = 0
if len(backData) == 16:
print "Sector "+str(blockAddr)+" "+str(backData)
def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR
print str(backLen)+" backdata &0x0F == 0x0A "+str(backData[0]&0x0F)
if status == self.MI_OK:
i = 0
buf = []
while i < 16:
buf.append(writeData[i])
i = i + 1
crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,buf)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
print "Error while writing"
if status == self.MI_OK:
print "Data writen"
def MFRC522_Init(self):
# GPIO.output(self.NRSTPD, 1)
self.MFRC522_Reset();
self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)
self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()
def GPIO_CLEEN(self):
GPIO.cleanup()
4 lines are commented (109 - 111, 357) and first line is replaced to use pyA20.gpio instead of RPi.GPIO.
After that, I run read.py and it works like a charm.
import MFRC522
import signal
continue_reading = True
MIFAREReader = MFRC522.MFRC522()
cardA = [5,74,28,185,234]
cardB = [83,164,247,164,164]
cardC = [20,38,121,207,132]
def end_read(signal, frame):
global continue_reading
continue_reading = False
print "Ctrl+C captured, ending read."
MIFAREReader.GPIO_CLEEN()
signal.signal(signal.SIGINT, end_read)
while continue_reading:
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
if status == MIFAREReader.MI_OK:
print "Card detected"
(status,backData) = MIFAREReader.MFRC522_Anticoll()
if status == MIFAREReader.MI_OK:
print "Card read UID: "+str(backData[0])+","+str(backData[1])+","+str(backData[2])+","+str(backData[3])+","+str(backData[4])
if backData == cardA:
print "is Card A"
elif backData == cardB:
print "is Card B"
elif backData == cardC:
print "is Card C"
else:
print "wrong Card"
That is the way to use the reader on ORANGE PI PC. I googled and read further, in order to use second reader I need to modify exact same lines that I commented in order it to work. It controls RC522 with that SDA PIN, chooses from which reader to read the data. I try to uncomment any of them, but errors appear. Looks like those use specific RPi.GPIO functions. My python knowledge is very basic. I try to find where exactly are described pins that are used, and failed. Tried just to replace that pin 24 with 26 in order to read data from second readed. So far no success.
I have very similar setup and have had similar problems.
It seems I managed to solve them, just last night! :)
My project involves:
Orange pi zero
12-13 RFID-RC522 modules (for now only 2)
SPI communication
since I will need lots of digital output pins I will use 12-13 shift register ICs (74HC595)
Approaches and problems:
connect together SCK, MISO and MOSI pins, pull RST high, control each SS line separately by modifying MFRC522 class. Didn't work, maybe my timings were off, should connect logic analyzer and see.
connect together SCK, MISO, MOSI AND SS pins, pull RST high, switch on/off Vcc or GND pins (power down all readers but one, read from that one, switch to next). Didn't work and presented very interesting situation. In some cases RFID module can read cards even with Vcc, or GND, or both pins DISCONNECTED!!! There is some significant leakage current from the signal pins. Here I tried demuxes, shift registers, line driver ICs, nothing worked.
Finally, approach that DOES work. Connect together SCK, MISO, MOSI AND SS pins, control RST pin. RST when pulled low powers down module. Pull it up to power-on. So, initially all RST pins are pulled low, then one-by-one are pulled high, small delay to allow module to boot up (I use 200ms), call MFRC522_Init() (not sure if necessary in each cycle, doesn't hurt I guess), perform read, pull RST low, switch to next module. Nice side effect of this approach is low power consumption: 2 powered-down modules draw 3.6mA, 1 on - 1 off draw 18mA.
Hope this helps! :)
It was been a while, i had learn a little, made two RC522 readers to work on ESP8266, but same scenario can be used on ORANCE PI, in my previous attempt I was trying to make them work in separate SPI interface, now I use one interface and control them with SS (SDA) signal, when is send LOW on it, reader is active for communication. That way can be used more than one and control them that way. Hope that help to someone who seek an answers here :)
Related
Im trying to establish my own Raspy-Installation with a light-control.
I am trying to get a script-code working, to enable the light-control-service.
I am getting a really simple error message, but i cant fix it on my own:
Traceback (most recent call last):
File "test.py", line 13, in <module>
bus.write_byte_data(0x39, 0x00 | 0x80, 0x03)
IOError: [Errno 5] Input/output error
I just want to show you the complete code. Is anyone able to help me? :)
from os import system
system("sudo killall pigpiod")
system("sudo pigpiod")
import RPi.GPIO as GPIO
import time
import pigpio
import smbus
bus = smbus.SMBus(1)
#Lichtsensor (Adresse 0x39) initialisieren
#Power On Mode
bus.write_byte_data(0x39, 0x00 | 0x80, 0x03)
bus.write_byte_data(0x39, 0x01 | 0x80, 0x02)
#kurze Pause
time.sleep(0.5)
#Lichtsensor auslesen
data = bus.read_i2c_block_data(0x39, 0x0c | 0x80, 2)
data1 = bus.read_i2c_block_data(0x39, 0x0e | 0x80, 2)
#Lichtdaten aufbereiten
ch0 = data[1] * 256 + data[0]
ch1 = data1[1] * 256 + data1[0]
#Lichtdaten ausgeben
print "Volles Spektrum (Infrarot+sichtbar) : %d lux" %ch0
print "Infrarot-Wert: %d lux" %ch1
print "sichtbares Licht-Wert : %d lux" %(ch0 - ch1)
#GPIO ports setzen und zuweisen
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
red = 17
green = 27
blue = 22
PIR = 5
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)
GPIO.setup(PIR, GPIO.IN)
pi = pigpio.pi()
#Variablen definieren
pi.set_PWM_dutycycle(red, 0)
pi.set_PWM_dutycycle(green, 0)
pi.set_PWM_dutycycle(blue, 0)
fade_in_delay = .1
fade_out_delay = .1
delay_time = 5
mycolor = blue
brightness = 200
min_light = 9
moment = 0
RUNNING = True
#Script starten
try:
while RUNNING:
data = bus.read_i2c_block_data(0x39, 0x0c | 0x80, 2)
data1 = bus.read_i2c_block_data(0x39, 0x0e | 0x80, 2)
ch0 = data[1] * 256 + data[0]
ch1 = data1[1] * 256 + data1[0]
light = ch0 - ch1
print "sichtbares Licht-Wert : %d lux" %(light)
if pi.read(PIR):
print "PIR = ON"
else:
print "PIR = OFF"
if moment > 1:
start = moment
else:
start = 0
if (pi.read(PIR) & (light < min_light)):
for x in range(start,brightness):
pi.set_PWM_dutycycle(mycolor, x)
time.sleep(fade_in_delay)
moment = x
while (pi.read(PIR) & (light < min_light)):
time.sleep(delay_time)
if not (pi.read(PIR) & (moment > 0)):
for x in range(brightness, 0, -1):
pi.set_PWM_dutycycle(mycolor, x)
time.sleep(fade_out_delay)
moment = 0
except KeyboardInterrupt:
RUNNING = False
I couldnt transform the usual tools to fix the problem i got by using google. Im also just a beginner in writing own python-scripts. Normally I´m looking for existing codes (like this) and get it done for my own use case.
I'm getting a little desperate, I'm trying to display the current time via a Raspberry pi with an HD44780 and an I2C chip. This works quite well, but now I want that the backlight remains off. The corresponding code snippet that my script sends is interpreted correctly, but every time the time is updated (and the LCD is supposed to write a new text) the backlight flashes briefly. I need this functionality programmatically, since, as soon as the problem is solved, still further functionality is to be added to the Script, in which the backlight is to be switched on again temporarily.
Running Script:
#!/usr/bin/env python3.2.3
#Date And Time Script
from time import sleep, strftime
from subprocess import *
import lcddriver
lcd = lcddriver.lcd()
def run_cmd(cmd):
p = Popen(cmd, shell = True, stdout = PIPE)
output = p.communicate()[0]
return output
lcd.lcd_clear()
while True:
lcd.lcd_display_string(strftime('%d.%m.%Y %H:%M'), 1)
lcd.lcd_device.write_cmd( 0x03 | 1 )
sleep(1)
Imported Script
import i2c_lib
from time import *
# LCD Address
ADDRESS = 0x27 #Update Address For LCD Here
# commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80
# flags for display entry mode
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00
# flags for display on/off control
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00
# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00
# flags for function set
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_5x8DOTS = 0x00
# flags for backlight control
LCD_BACKLIGHT = 0x08
LCD_NOBACKLIGHT = 0x00
En = 0b00000100 # Enable bit
Rw = 0b00000010 # Read/Write bit
Rs = 0b00000001 # Register select bit
class lcd:
#initializes objects and lcd
def __init__(self):
self.lcd_device = i2c_lib.i2c_device(ADDRESS)
self.lcd_write(0x03)
self.lcd_write(0x03)
self.lcd_write(0x03)
self.lcd_write(0x02)
self.lcd_write(LCD_FUNCTIONSET | LCD_2LINE | LCD_5x8DOTS | LCD_4BITMODE)
self.lcd_write(LCD_DISPLAYCONTROL | LCD_DISPLAYON)
self.lcd_write(LCD_CLEARDISPLAY)
self.lcd_write(LCD_ENTRYMODESET | LCD_ENTRYLEFT)
sleep(0.2)
# clocks EN to latch command
def lcd_strobe(self, data):
self.lcd_device.write_cmd(data | En | LCD_BACKLIGHT)
sleep(.0005)
self.lcd_device.write_cmd(((data & ~En) | LCD_BACKLIGHT))
sleep(.0001)
def lcd_write_four_bits(self, data):
self.lcd_device.write_cmd(data | LCD_BACKLIGHT)
self.lcd_strobe(data)
# write a command to lcd
def lcd_write(self, cmd, mode=0):
self.lcd_write_four_bits(mode | (cmd & 0xF0))
self.lcd_write_four_bits(mode | ((cmd << 4) & 0xF0))
# put string function
def lcd_display_string(self, string, line):
if line == 1:
self.lcd_write(0x80)
if line == 2:
self.lcd_write(0xC0)
if line == 3:
self.lcd_write(0x94)
if line == 4:
self.lcd_write(0xD4)
for char in string:
self.lcd_write(ord(char), Rs)
# clear lcd and set to home
def lcd_clear(self):
self.lcd_write(LCD_CLEARDISPLAY)
self.lcd_write(LCD_RETURNHOME)
Firstly this questions is inferred from this answer answer .In that answer provides us a splitting a mp3 file with Python . That code is usefull , but for splitting two pieces . For instance if I want to split 30.00 th second to end of the audio , it is cool , but if I want to split from 30.00 to 35.00 it is useless for it . Below of that answer there is a comment about how to trim audio, like I said ,specific piece. When I imply that instructions to code it looked like that :
import struct
import sys
#MP3 frames are not independent because of the byte reservoir. This script does not account for
#that in determining where to do the split.
def SplitMp3(fi, firstSplit_sec,secondSplit_sec, out):
#Constants for MP3
bitrates = {0x0: "free", 0x1: 32, 0x2: 40, 0x3: 48, 0x4: 56, 0x5: 64, 0x6: 80, 0x7: 96, 0x8: 112,
0x9: 128, 0xa: 160, 0xb: 192, 0xc: 224, 0xd: 256, 0xe: 320, 0xf: "bad"}
freqrates = {0x0: 44100, 0x1: 48000, 0x2: 32000, 0x3: "reserved"}
countMpegFrames = 0
frameDuration = 0.026
unrecognizedBytes = 0
firstSplitFrame = int(round(firstSplit_sec / frameDuration))
secondSplitFrame = int(round(secondSplit_sec / frameDuration))
while True:
startPos = fi.tell()
#Check for 3 byte headers
id3Start = fi.read(3)
if len(id3Start) == 3:
if id3Start == b'TAG':
#print ("Found ID3 v1/1.1 header")
fi.seek(startPos + 256)
continue
if id3Start == b'ID3':
#Possibly a ID3v2 header
majorVer, minorVer, flags, encSize = struct.unpack(">BBBI", fi.read(7))
if majorVer != 0xFF and minorVer != 0xFF:
encSize1 = (encSize & 0x7f000000) >> 24
encSize2 = (encSize & 0x7f0000) >> 16
encSize3 = (encSize & 0x7f00) >> 8
encSize4 = (encSize & 0x7f)
if encSize1 < 0x80 and encSize2 < 0x80 and encSize3 < 0x80 and encSize4 < 0x80:
size = ((encSize & 0x7f000000) >> 3) + ((encSize & 0x7f0000) >> 2) + ((encSize & 0x7f00) >> 1) + (encSize & 0x7f)
unsync = (flags >> 7) & 0x1
extendedHeader = (flags >> 6) & 0x1
experimental = (flags >> 5) & 0x1
#print ("Found ID3v2 header")
#print ("version", majorVer, minorVer, unsync, extendedHeader, experimental)
#print ("size", size)
#TODO extendedHeader not supported yet
fi.seek(startPos + 10 + size)
continue
#Check for 4 byte headers
fi.seek(startPos)
headerRaw = fi.read(4)
if len(headerRaw) == 4:
headerWord = struct.unpack(">I", headerRaw)[0]
#Check for MPEG-1 audio frame
if headerWord & 0xfff00000 == 0xfff00000:
#print ("Possible MPEG-1 audio header", hex(headerWord))
countMpegFrames += 1
ver = (headerWord & 0xf0000) >> 16
bitrateEnc = (headerWord & 0xf000) >> 12
freqEnc = (headerWord & 0xf00) >> 8
mode = (headerWord & 0xf0) >> 4
cpy = (headerWord & 0xf)
if ver & 0xe == 0xa and freqEnc != 0xf:
#print ("Probably an MP3 frame")
bitrate = bitrates[bitrateEnc]
freq = freqrates[freqEnc >> 2]
padding = ((freqEnc >> 1) & 0x1) == 1
#print ("bitrate", bitrate, "kbps")
#print ("freq", freq, "Hz")
#print ("padding", padding)
frameLen = int((144 * bitrate * 1000 / freq ) + padding)
#Copy frame to output
fi.seek(startPos)
frameData = fi.read(frameLen)
if (secondSplitFrame >= countMpegFrames) and (countMpegFrames >= firstSplitFrame):
out.write(frameData)
fi.seek(startPos + frameLen)
continue
else:
raise RuntimeError("Unsupported format:", hex(ver), "header:", hex(headerWord))
#If no header can be detected, move on to the next byte
fi.seek(startPos)
nextByteRaw = fi.read(1)
if len(nextByteRaw) == 0:
break #End of file
unrecognizedBytes += 1
#print ("unrecognizedBytes", unrecognizedBytes)
#print ("countMpegFrames", countMpegFrames)
#print ("duration", countMpegFrames * frameDuration, "sec")
When I use this function it produces loosy output . For instance if I want to split 0.0 to 41.00 it gives me 0.00 to 37.00 , and this loosieness is increasing with amount of slice. I've struggled to understand some parts of code . So I am asking how can I solve that loosiness ? Am I missing something ?
Note : I already tried to pydub and similar modules . But they are useless . Always giving memory error and slow . This is really fast .
I couldn't find a solution for loosiness problem therefore I used ffmpeg for slicing .
subprocess.call(["ffmpeg","-i",input_file,"-acodec","copy","-loglevel","quiet","-ss",str(start),"-to",str(end),"-metadata","title={}".format(name),output_file+".mp3"])
I try to use a AD5270, 20KOhm SPI potentiometer for a personal project with my Raspberry Pi 3B+. I translate some Arduino libraries code to Python language but it looks like it won't work. I can't test if the potentiometer is good value configured so I read the resistor value and always get 0 from SPI register.
Problem : I don't know if my writing is well done because I can't probe the resistor. To know if it works, I read the register and always receive 0x00. Writing and/or reading won't work.
Expect : reading what I have written.
Hardware setup :
!SYNC = CE0 = PIN24
DIN = MISO = PIN19
SDO = MOSI = PIN21
SLCK = SCLK = PIN23
with 1uF ext capacitor and 3V3 supply (from Raspberry).
The datasheet of the AD5270 is available here.
Minimalist code following the datasheet that won't work :
spi = spidev.SpiDev()
spi.open(spi_bus, spi_device_select)
spi.max_speed_hz = 50000 # Datasheet p7
spi.mode = 1 # CPOL = 0, CPHA = 1 (Datasheet p7)
# Datasheet example
data = [0x1C, 0x03]
r = spi.xfer(data)
print(r)
data = [0x05, 0x00]
r = spi.xfer(data)
print(r)
data = [0x08, 0x00]
r = spi.xfer(data)
print(r)
data = [0xC0, 0x00]
r = spi.xfer(data)
print(r)
From your hardware setup:
DIN = MISO = PIN21 (through 10 Ohm resistor)
SDO = MOSI = PIN19 (through 10 Ohm resistor)
DIN is input to AD5270, and therefore output of your RPI, so it should be MOSI. Same problem for SDO.
I finally got the tricks. Don't forget to add a pullup on SDO line and configure Spidev for the AD5270. This code work quite well :
# SPI test code for AD5270BRMZ-20
import time
import spidev
spi_bus = 0 # SPI0
spi_device_select = 0 # CE0
spi = spidev.SpiDev()
spi.open(spi_bus, spi_device_select)
spi.max_speed_hz = 50000 # Datasheet p7
spi.mode = 1 # CPOL = 0, CPHA = 1 (Datasheet p7)
spi.lsbfirst = False # Datasheet p18
MAX_RESISTANCE = 20000.0
WRITE_CTRL_REG = 0x1C
READ_CTRL_REG = 0x20
WRITE_RDAC = 0x04
READ_RDAC = 0x08
RDAC_WRITE_PROTECT = 0x02
def AD5270_CalcRDAC(resistance):
return int((resistance / MAX_RESISTANCE) * 1024.0)
def AD5270_ReadReg(command):
data = [(command & 0x3C), 0]
r = spi.xfer2(data)
data = [0x00, 0x00]
r2 = spi.xfer2(data)
result = r2[0]
result = (result << 8) | r2[1]
return result
def AD5270_WriteReg(command, value):
ui16Command = (command & 0x3C) << 8 | (value & 0x3FF)
data = [(ui16Command >> 8) & 0xFF, ui16Command & 0xFF]
spi.xfer2(data)
def AD5270_ReadRDAC():
RDAC_val = AD5270_ReadReg(READ_RDAC)
RDAC_val &= 0x03FF
return ((RDAC_val) * MAX_RESISTANCE) / 1024.0
def AD5270_WriteRDAC(resistance):
RDAC_val = AD5270_CalcRDAC(resistance)
spi.xfer2([WRITE_CTRL_REG, RDAC_WRITE_PROTECT])
AD5270_WriteReg(WRITE_RDAC, RDAC_val);
return ((RDAC_val * MAX_RESISTANCE) / 1024.0)
while(1):
AD5270_WriteRDAC(10000.0) # Write 10KOhm
print(AD5270_ReadRDAC())
time.sleep(1)
spi.close()
I have a problem in performance (scanning speed) with my Pi and the MPU6050.
The task of the code is to log the data from the MPU as fast as possible and in an accurate interval.
To reach a high scanning speed I just record the raw register values and convert everything later.
Moreover, I change the I2C baud rate from the Raspberry to 400kHz.
At the moment the code provide a raw data record frequency with max 135Hz.
Can you help me to get higher sampling rate and a better accurate interval. Wherein the exact interval the more important point is.
#!/usr/bin/python
import smbus
from datetime import datetime, timedelta
import time
bus = smbus.SMBus(1) # Bus for Revision 2 boards
address = 0x68 # Sensor i2c address
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
# Accelerometer
# Data register
ACCEL_XOUT0 = 0x3B
ACCEL_XOUT1 = 0x3C
ACCEL_YOUT0 = 0x3D
ACCEL_YOUT1 = 0x3E
ACCEL_ZOUT0 = 0x3F
ACCEL_ZOUT1 = 0x40
# Range
ACCEL_CONFIG_REGISTER = 0x1C
ACCEL_2G = 0x00
ACCEL_4G = 0x08
ACCEL_8G = 0x10
ACCEL_16G = 0x18
# Scale Modifiers
ACCEL_SCALE_MODIFIER_2G = 16384.0
ACCEL_SCALE_MODIFIER_4G = 8192.0
ACCEL_SCALE_MODIFIER_8G = 4096.0
ACCEL_SCALE_MODIFIER_16G = 2048.0
# Gyroscope
# Data register
GYRO_XOUT0 = 0x43
GYRO_XOUT1 = 0x44
GYRO_YOUT0 = 0x45
GYRO_YOUT1 = 0x46
GYRO_ZOUT0 = 0x47
GYRO_ZOUT1 = 0x48
# Range
GYRO_CONFIG_REGISTER = 0x1B
GYRO_250DEG = 0x00
GYRO_500DEG = 0x08
GYRO_1000DEG = 0x10
GYRO_2000DEG = 0x18
# Scale Modifiers
GYRO_SCALE_MODIFIER_250DEG = 131.0
GYRO_SCALE_MODIFIER_500DEG = 65.5
GYRO_SCALE_MODIFIER_1000DEG = 32.8
GYRO_SCALE_MODIFIER_2000DEG = 16.4
# Temperature
# Data register
TEMP_OUT0 = 0x41
TEMP_OUT1 = 0x42
# -- Functions --
def read_register(adr):
return [bus.read_byte_data(address, adr),bus.read_byte_data(address, adr+1)]
def convert_register(raw_val):
convert_val = (raw_val[0] << 8) + raw_val[1]
if (convert_val >= 0x8000):
return -((65535 - convert_val) + 1)
else:
return convert_val
def convert_temp(raw_val):
raw_temp = convert_register(raw_val)
temp = (raw_temp / 340) + 36.53
return temp
def set_range_get_scale(register, range):
bus.write_byte_data(address, register, range) # set new range
time.sleep(0.5)
current_range = bus.read_byte_data(address, register) # read current set range
if register == ACCEL_CONFIG_REGISTER:
if current_range == ACCEL_2G:
return ACCEL_SCALE_MODIFIER_2G
elif current_range == ACCEL_4G:
return ACCEL_SCALE_MODIFIER_4G
elif current_range == ACCEL_8G:
return ACCEL_SCALE_MODIFIER_8G
else: #current_range == ACCEL_16G
return ACCEL_SCALE_MODIFIER_16G
if register == GYRO_CONFIG_REGISTER:
if current_range == GYRO_250DEG:
return GYRO_SCALE_MODIFIER_250DEG
elif current_range == GYRO_500DEG:
return GYRO_SCALE_MODIFIER_500DEG
elif current_range == GYRO_1000DEG:
return GYRO_SCALE_MODIFIER_1000DEG
else: #current_range == GYRO_2000DEG:
return GYRO_SCALE_MODIFIER_2000DEG
# -- INIT --
print('| Loading...')
bus.write_byte_data(address, power_mgmt_1, 0)
acc_scale = set_range_get_scale(ACCEL_CONFIG_REGISTER,ACCEL_2G)
gyro_scale = set_range_get_scale(GYRO_CONFIG_REGISTER,GYRO_250DEG)
# -- MAIN --
# query of parameters
freqInput = raw_input("Measuring frequency[Hz]: ")
durationInput=[0,0]
tmp = raw_input("Measuring duration[m]: ")
durationInput[0] = int(tmp)
tmp = raw_input("Measuring duration[s]: ")
durationInput[1] = int(tmp)
# Calculation of frequency
milsec = float(1000.0/float(freqInput))
if milsec==1000:
freq=timedelta(0,1)
elif milsec%1==0:
freq=timedelta(0,0,0,int(milsec))
else:
freq=timedelta(0,0,(milsec-int(milsec))*1000,int(milsec))
# Set measurement duration
duration=timedelta(0,durationInput[1],0,0,durationInput[0]) # days, seconds, microseconds, milliseconds, minutes
# List for data record
time=[]
temp=[]
acc=[]
gyro=[]
# Loop
print('| Start Logging')
tend = datetime.now()+duration
t = datetime.now()
while datetime.now().time() < tend.time(): # interrupts if the total measuring time is passed
t = datetime.now()
time.append(datetime.now())
temp.append(read_register(0x41))
acc.append([read_register(0x3B),read_register(0x3D),read_register(0x3F)])
gyro.append([read_register(0x43),read_register(0x45),read_register(0x47)])
while datetime.now() < t+freq: # interrupts if it time for the next record
pass
tend = datetime.now()
print('| Finish Logging')
# Test Records
print('| Start Test Record')
if len(time) == len(temp) and len(time) == len(acc) and len(time) == len(gyro):
print('| Finish Record Test; Result = OK')
else:
print('| Finish Record Test; Result = FALSE')
SystemExit(0)
# Convert Raw Data
print('| Start Raw Data Converting')
for i in range(len(time)):
temp[i] = convert_temp(temp[i])
for j in range(0,3):
acc[i][j] = convert_register(acc[i][j]) / acc_scale
gyro[i][j] = convert_register(gyro[i][j]) / gyro_scale
print('| Finish Raw Data Converting')
# write file
print ("| Start file writing")
name = datetime.now()
file = name.strftime('%Y%m%d_%H%M%S')
datei_out = open(file+".csv","w")
for i in range(len(time)):
datei_out.write(str(i+1)+";") # number of measurment
datei_out.write(str(time[i].time())+";") # time stamp of measurment
datei_out.write(str(time[i]-time[0])+";") # time delta since measurement start
datei_out.write(str(acc[i][0])+";") # Accelerometer X
datei_out.write(str(acc[i][1])+";") # Accelerometer X
datei_out.write(str(acc[i][2])+";") # Accelerometer X
datei_out.write(str(gyro[i][0])+";") # Gyroscope X
datei_out.write(str(gyro[i][1])+";") # Gyroscope X
datei_out.write(str(gyro[i][2])+"\n") # Gyroscope X
datei_out.close()
print ("| Finish file writing")
# end
print ("| Completely Finish")