How i understanding AD9833 SPI communication using Python with my raspberry? - python

Hi i had an issue to discuss,
and i dont realy understand to send data with SPI with Python
I want to send data with my Raspberry Pi 4 ver.b using Python to send data to my module named AD9833 DDS. So i found code in internet, writed in Python (sor. https://ez.analog.com/dds/f/q-a/28431/ad9833-programming-in-raspberry-pi-using-python). This is the code :
# The code write by SamMaster, Oct 21 2016
# importing library
import time
import spidev
# activate spidev module and settings SPI
spi = spidev.SpiDev()
spi.open(0,1)
spi.max_speed_hz = 976000
# initialize frequency and another value
freq_out = 400
Two28 = 268435456
phase = 0
after the programmer call all library, function and set the value, his try to define a function to send a data.
def send_data(input):
tx_msb = input >> 8
tx_lsb = input & 0xFF
spi.xfer([tx_msb,txlsb])
print(input)
so that this frequencies value is able to read by AD9833, this frequency must convert to freq word, so programmer write the code,
freq_word = int(round(float(freq_out*Two28)/25000000))
and then the programmer define all of MSB and LSB
MSB = (freq_word & 0xFFC000)>>14
LSB = (freq_word & 0x3FFF)
LSB |= 0x4000
MSB |= 0x4000
phase|= 0xC000
and then, function that the programmer built implement in this blocks of codes
send_data(LSB)
send_data(MSB)
send_data(phase)
send_data(0x2000)
its worked on my Raspberry Pi 4, this is the result on my device,
Result for 400Hz
Result for 500Hz
when i change the frequency so freq_out = 500 there is no changes, just the value is aproximately 400 Hz on my scope. So i try this simple solution, i put the code send_data(0x2000), 0x2000 it mean Reset AD9833 according to datasheet, above the send_data(LSB) code. So the code became,
send_data(0x2000)
send_data(LSB)
send_data(MSB)
send_data(phase)
and this the result,
freq_out = 400 freq_out = 400
freq_out = 500 freq_out = 500
freq_out = 600 freq_out = 600
freq_out = 1000freq_out = 1000
i don't know why when i writing freq_out = 600 the value output frequency not correct with what i'm inputing. So can anyone want to comment / state argument to my issue ?

This problem can be split into a number of sub tasks.
Values to send
Sequence values sent in
How values sent over SPI
As SamMaster pointed out there is an application note from Analog Devices that shows the sequence of values to send to set the frequency to 400 Hz
https://www.analog.com/media/en/technical-documentation/application-notes/AN-1070.pdf
They summarise the five values to send and in what order in the following table:
If I look at the code that SamMaster has written it is writing the correct values in the correct order (I don't have the hardware but I can print the values).
sending: [0x21, 0x00]
sending: [0x50, 0xc7]
sending: [0x40, 0x00]
sending: [0xc0, 0x00]
sending: [0x20, 0x00]
That just leaves bullet 3 that is causing the problems.
The fact that you get changes happening on the hardware suggests that some kind of communication is happening, just not the correct values.
Looking at the limited documentation at https://pypi.org/project/spidev/ there are two likely commands that could be used: xfer or xfer2.
The difference between the two are the value of the chip select pin between blocks.
Figure 4 in the data sheet I think is saying that chip select should not be released between the two bytes.
https://www.analog.com/media/en/technical-documentation/data-sheets/ad9833.pdf
That would suggest that xfer2 should be to used to send the blocks and not xfer as SamMaster has done. Although SamMaster seems to suggest he got it working with xfer and you were able to set the value to 400 Hz successfully. You would need your scope/logic analyser to see if the GPIO is doing the right thing on the hardware.
At some point in your development you seem to have changed the sequence of values to send. It should be:
send_data(0x2100) # Start
send_data(LSB) # Frequency 14 bits (LSB)
send_data(MSB) # Frequency 14 bits (MSB)
send_data(phase) # Phase value
send_data(0x2000) # End
This could be another source of your error.
I looked at what the values should be that get sent for the different frequency you tested. I calculated the values follows:
For Frequency: 400
Frequency setting: 4295 = 0x10c7 = 0001000011000111
send_data(0x2100)
send_data(0x50c7)
send_data(0x4000)
send_data(0xc000)
send_data(0x2000)
For Frequency: 500
Frequency setting: 5369 = 0x14f9 = 0001010011111001
send_data(0x2100)
send_data(0x54f9)
send_data(0x4000)
send_data(0xc000)
send_data(0x2000)
For Frequency: 600
Frequency setting: 6442 = 0x192a = 0001100100101010
send_data(0x2100)
send_data(0x592a)
send_data(0x4000)
send_data(0xc000)
send_data(0x2000)
For Frequency: 1000
Frequency setting: 10737 = 0x29f1 = 0010100111110001
send_data(0x2100)
send_data(0x69f1)
send_data(0x4000)
send_data(0xc000)
send_data(0x2000)
And finally, I refactored the code to make it easier for me to test the different parts of the code. I'm sharing it here for your information. I had to comment out any of the spi communication parts because I don't have the hardware.
import time
import spidev
# activate spidev module and settings SPI
bus = 0
device = 1
spi = spidev.SpiDev()
spi.open(bus, device)
spi.max_speed_hz = 976000
def output_freq(hz_value):
return int(round((hz_value * 2**28) / 25e6))
def freq_change_start():
ctrl_reg = 0
ctrl_reg += 2**13 # set DB13 (28 bit freq reg)
ctrl_reg += 2**8 # set DB8 (Reset)
return ctrl_reg
def freq_reg_lsb(freq_reg):
fourteen_bit_mask = 0b0011111111111111
write_value = 0
write_value += 2**14 # set DB14
lsb = freq_reg & fourteen_bit_mask
write_value += lsb
return write_value
def freq_reg_msb(freq_reg):
fourteen_bit_mask = 0b0011111111111111
write_value = 0
write_value += 2**14 # set DB14
msb = freq_reg >> 14 & fourteen_bit_mask
write_value += msb
return write_value
def phase_register():
# Currently always the same value
write_value = 0
# Set phase register address
write_value += 2 ** 15 # set DB15
write_value += 2 ** 14 # set DB14
return write_value
def freq_change_end():
ctrl_reg = 0
ctrl_reg += 2**13 # set DB13 (28 bit freq reg)
return ctrl_reg
def word_split(word16):
tx_msb = word16 >> 8
tx_lsb = word16 & 0xFF
return tx_msb, tx_lsb
def send_spi_sequence(sequence):
for word16 in sequence:
two_bytes = word_split(word16)
print(f"\tsending:[{two_bytes[0]:#02x}, {two_bytes[1]:#02x}]")
print(f"\tsend_data({word16:#06x})")
spi.xfer(two_bytes)
# spi.xfer2(two_bytes)
def change_freq(freq_hz):
# Calc values to send
print("For Frequency:", freq_hz)
freq_reg = output_freq(freq_hz)
print(f"Frequency setting: {freq_reg} = {freq_reg:#04x} = {freq_reg:016b}")
ctrl_start = freq_change_start()
print(f"Control register write: {ctrl_start:#04x}")
lsb_value = freq_reg_lsb(freq_reg)
print(f"lsb value: {lsb_value:#04x}")
msb_value = freq_reg_msb(freq_reg)
print(f"lsb value: {msb_value:#04x}")
phase_reg = phase_register()
print(f"Phase register write: {phase_reg:#04x}")
ctrl_end = freq_change_end()
print(f"Control register write: {ctrl_end:#04x}")
# Write values to spi
send_spi_sequence([ctrl_start, lsb_value, msb_value, phase_reg, ctrl_end])
def main():
show_freq_for = 20
change_freq(400)
time.sleep(show_freq_for)
change_freq(500)
time.sleep(show_freq_for)
change_freq(600)
time.sleep(show_freq_for)
change_freq(1000)
time.sleep(show_freq_for)
if __name__ == '__main__':
main()

Related

Get all transactions from OKX with python

I try to make full overview over my transaktions (bye/sell/deposit/withdrawl/earnings and boot trades) with python for Okx, but I get only 2 Trades (but I have made more than 2).
I have tried to send request with orders-history-archive and fetchMyTrades from CCXT Library (have tried some other functions, but I steed don't get my transactions.)
Is there some way to get full overview for Okx with python (and other Brocker/Wallets)?
here How I try to get the data with CCXT (it give only 2 outputs):
def getMyTrades(self):
tData = []
tSymboles = [
'BTC/USDT',
'ETH/USDT',
'SHIB/USDT',
'CELO/USDT',
'XRP/USDT',
'SAMO/USDT',
'NEAR/USDT',
'ETHW/USDT',
'DOGE/USDT',
'SOL/USDT',
'LUNA/USDT'
]
for item in tSymboles:
if exchange.has['fetchMyTrades']:
since = exchange.milliseconds() - 60*60*24*180*1000 # -180 days from now
while since < exchange.milliseconds():
symbol = item # change for your symbol
limit = 20 # change for your limit
orders = exchange.fetchMyTrades(symbol, since, limit)
if len(orders):
since = orders[len(orders) - 1]['timestamp'] + 1
tData += orders
else:
break

Get DBa value using gravity sound meter with ADC module with raspberry pi

I need help to get actual value from gravity sound meter with raspberry pi.
I have a python program to get those details
import sys
sys.path.append('../')
import time
from DFRobot_ADS1115 import ADS1115
ADS1115_REG_CONFIG_PGA_6_144V = 0x00 # 6.144V range = Gain 2/3
ADS1115_REG_CONFIG_PGA_4_096V = 0x02 # 4.096V range = Gain 1
ADS1115_REG_CONFIG_PGA_2_048V = 0x04 # 2.048V range = Gain 2 (default)
ADS1115_REG_CONFIG_PGA_1_024V = 0x06 # 1.024V range = Gain 4
ADS1115_REG_CONFIG_PGA_0_512V = 0x08 # 0.512V range = Gain 8
ADS1115_REG_CONFIG_PGA_0_256V = 0x0A # 0.256V range = Gain 16
ads1115 = ADS1115()
while True :
#Set the IIC address
ads1115.setAddr_ADS1115(0x48)
#Sets the gain and input voltage range.
ads1115.setGain(ADS1115_REG_CONFIG_PGA_6_144V)
#Get the Digital Value of Analog of selected channel
adc0 = ads1115.readVoltage(0)
time.sleep(0.2)
adc1 = ads1115.readVoltage(1)
time.sleep(0.2)
adc2 = ads1115.readVoltage(2)
time.sleep(0.2)
adc3 = ads1115.readVoltage(3)
print "A0:%dmV A1:%dmV A2:%dmV A3:%dmV"%(adc0['r'],adc1['r'],adc2['r'],adc3['r'])
It's displaying values like
A0:0mv A1:1098mV A2:3286mV A3:498mV
But I don't know how to get actual sound value in decibel unit.
You can find the documentation here:
https://wiki.dfrobot.com/Gravity__Analog_Sound_Level_Meter_SKU_SEN0232
To anwser your question:
For this product,the decibel value is linear with the output
voltage.When the output voltage is 0.6V, the decibel value should be
30dBA. When the output voltage is 2.6V, the decibel value should be
130dBA. The calibration is done before leaving the factory, so you
don't need to calibrate it. So we can get this relation: Decibel
Value(dBA) = Output Voltage(V) × 50
So you need to check to which connector (A0, A1, A2 or A3) you connected your sound level meter. Take that value (which seems to be in mV) convert it to V and multiple by 50.
Or simple divide your value by 20.

How to increases the CPU usage of my Python program?

I am writing a program in Raspberry Pi 3 to read the inputs using an MCP3008 ADC from a function generator. I want to read two channels at the same time and then write it to a file. When I have just one channel, I get about 12000 samples per second, however, when I have two channels, I get about 6000 samples per second for each channel. To get 12000 samples per second for each channels, I tried to write two different scripts, one for each channel and then run them simultaneously in two different terminals. However, that does not solve the problem and gives me 6000 samples per second for each channel.
When I have just one script, I get about 9% CPU usage. When I run two scripts at the same time in two different terminals, I get about 5% CPU usage for each process. How do I get each process to use 9% CPU each or higher?
Thank you!
Here is my code:
import spidev, time, os
# opens SPI bus
spi = spidev.SpiDev()
spi.open(0, 0)
#spi1 = spidev.SpiDev()
#spi1.open(0, 1)
ch0 = 0
#ch1 = 1
now = time.time() * 1000
data = open("test_plot.dat", "w")
#data1 = open("test_plot_1.dat", "w")
def getReading(channel):
# pull raw data from chip
rawData = spi.xfer([1, (8 + channel) << 4, 0])
# process raw data to something we understand
processedData = ((rawData[1]&3) << 8) + rawData[2]
return processedData
"""
def getReading1(channel):
# pull raw data from chip
rawData = spi1.xfer([1, (8 + channel) << 4, 0])
# process raw data to something we understand
processedData = ((rawData[1]&3) << 8) + rawData[2]
return processedData
"""
while True:
if (((time.time() * 1000) - now) < 10001):
data.write("%d\n" % getReading(ch0))
#data1.write("%d\n" % getReading1(ch1))
else:
break
# http://www.takaitra.com/posts/492

TMC222 Stepper Controller, motor busy function

I am currently working on a robot that has to traverse a maze.
For the robot I am using a TMC222 Stepper controller and the software is coded in Python.
I am in need of a function which can tell me when the motors are busy so that the robot will seize all other activity while the motors are running.
My idea is to check the current position on the motors and compare it to the target position, but i haven't gotten it to work yet.
My current attempt:
def isRunning(self):
print("IS RUNNING TEST")
fullstatus=self.getFullStatus2()
#print("FULL STATUS: " + str(fullstatus[0]) + " 2 " + str(fullstatus[1]))
actLeft=fullstatus[0][1]<<8 | fullstatus[0][2]<<0
actRight=fullstatus[1][1]<<8 | fullstatus[1][2]<<0
tarLeft=fullstatus[0][3]<<8 | fullstatus[0][4]<<0
tarRight=fullstatus[1][3]<<8 | fullstatus[1][4]<<0
value = (actLeft==tarLeft) and (actRight==tarRight)
value = not value
# print("isbusy="+str(value))
print 'ActPos = ' + str(actLeft)
print 'TarPos = ' + str(tarLeft)
return value
It would be helpful to see your getFullStatus2() code as well, since it's unclear to me how you're getting a multidimensional output.
In general, you can form a 16-bit "word" from two 8-bit bytes just as you have it:
Word = HB << 8 | LB << 0
Where HB and LB are the high (bits 15-8) and low (bits 7-0) bytes.
That being said, there are multiple ways to detect motor stall. The ideal way would be an external pressure switch that closed when it hit a wall. Another would be to monitor the motor's current, when the motor faces resistance (when accelerating or in stall), the current will rise.
Since it looks like neither of these are possible, I'd use still a different approach, monitoring the motor's position (presumably from some sort of encoder) over time.
Lets say you have a function get_position() that returns an unsigned 16-bit integer. You should be able to write something like:
class MotorPosition(object):
def __init__(self):
readings = []
def poll(self):
p = get_position()
self.readings.append(readings)
# If the list is now too long, remove the oldest entries
if len(self.readings) > 5:
self.readings.pop(0)
def get_deltas():
deltas = []
for x,y in zip(self.readings[1:4], self.readings[0:3]):
d = x - y
# Wraparound detection
if (d < -THRESHOLD): d += 65536
elif(d > THRESHOLD): d -= 65536
deltas.append(d)
return deltas
def get_average_delta():
deltas = self.get_deltas()
return sum(deltas) / float(len(deltas))
Note that this assumes you're polling the encoder fast enough and with consistent frequency.
You could then monitor the average delta (from get_average_delta()) and if it drops below some value, you consider the motor stalled.
Assumptions:
This is the datasheet for the controller you're using
Your I²C code is working correctly

python reads some data twice device file

I'm running xillinux (more or less ubuntu 12.04) on zedboard. Zedboard combines arm with fpga.
Now have written a python script wich reads data from a device driver (/dev/xillybus_read_32).
Now i know the data i recieve is complete and correct (i used a prewritten program that stored al the data in a dumpfile, i splitted this dumpfile in frames and cheched if the content was correct ( every frame contains an addition, so easy to check).
Now when i try to recieve data from the device driver with the following python script:
#Read data
#Framesize
CONST_FRAMESIZE = (640*480*16)/8
#Info
frame_true = 0
frame_false = 0
#Open file
pipe_in = open("/dev/xillybus_read_32","r")
count = 0
count_false = 0
for z in xrange(1000):
frame = "frame" + str(count) + ".raw"
pipe_out = open(frame,"wb")
for r in xrange(CONST_FRAMESIZE/4):
value = pipe_in.read(4)
pipe_out.write(value)
pipe_out.close()
#Compare goldendata with frame
if filecmp.cmp("goldendata",frame):
frame_true = frame_true + 1
if count >= 1:
os.remove(frame_last)
frame_last = frame
else:
print "frame_true:", frame_true
pipe_in.close()
sys.exit()
#frame_false = frame_false + 1
#os.remove(frame)
count = count + 1;
#Close opend file
pipe_in.close()
I recieve all the data but, sometimes i get my 32 bit words 2 times. It's like it sometimes reads the 32bit word twice. I doesn't lose data, it just reads a 32 bit sometimes 2 times. Very strange.
Thnx

Categories

Resources