content
stringlengths 10
4.9M
|
---|
// Set the logfile header and footer (chainable). Must be called before the first log
// message is written. These are formatted similar to the FormatLogRecord (e.g.
// you can use %D and %T in your header/footer for date and time).
func (w *FileLogWriter) SetHeadFoot(head, foot string) *FileLogWriter {
w.header, w.trailer = head, foot
if w.maxlines_curlines == 0 {
w.writeToBuf(FormatLogRecord(w.header, &LogRecord{Created: time.Now()}))
}
return w
} |
#include <stdio.h>
int main()
{
int i,a,n,k,z,l,j,sum=0,p=0,d=0,r,temp;
scanf ("%d" , &n);
int ar[101];
for (l=0;l<n;l++)
{
scanf("%d", &ar[l]);
}
for (k=0; k<n; k++)
sum+=ar[k];
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (ar[i] < ar[j])
{
a = ar[i];
ar[i] = ar[j];
ar[j] = a;
}
}
}
for (r=0; r<n && 2*p<=sum;r++ )
{
p+=ar[r];
d++;}
printf ("%d", d);
return 0;
}
|
<reponame>errord/sputnik
#-*- coding: utf-8 -*
#
# Copyright 2011 shuotao.me
# by <EMAIL>
# 2011-11-3
#
# Sputnik File System (IFS)
#
# ToDoList:
#
import random
import os
from SpuDateTime import SpuDateTime
from SpuDebug import *
from SpuLogging import *
_fs = {}
def createSpuFS(type, cfg, fs_name = 'fs_default'):
global _fs
if not type or type == 'spuFS' or type == 'default':
_fs[fs_name] = SpuFileSystem(cfg)
return
assert None, 'Unknow SpuFileSystem Type:%s' % type
def getSpuFS(fs_name = 'fs_default'):
global _fs
if _fs:
if fs_name not in _fs:
assert None, 'Not File System Name: %s' % fs_name
pass
return _fs[fs_name]
assert None, 'Not Create SpuFS'
class SpuFileSystem:
def __init__(self, cfg):
self._cfg = cfg
self.root_dir = cfg.get('root', None)
self.urlbase = cfg.get('urlbase', None)
self._debug_time = SpuDebugTime()
self._logging = SpuLogging()
self._logging.set_class('SpuFileSystem')
assert self.root_dir, 'Not Root Path'
assert self.urlbase, 'Not Url Base'
def mkdir(self, dir_path):
full_path = self.full_path(dir_path, '')
os.makedirs(full_path)
def rmdir(self, dir_path):
full_path = self.full_path(dir_path, '')
os.removedirs(full_path)
def isfile(self, path, file):
full_path = self.full_path(path, file)
return os.path.isfile(full_path)
def exists(self, path):
full_path = self.full_path(path, '')
return os.path.exists(full_path)
def _new_file(self, dir_path, file_name, open_type, file):
full_path = self.full_path(dir_path, file_name)
try:
fd = open(full_path, open_type)
fd.write(file)
fd.close()
except IOError as m:
if m.errno == 2:
return False
return True
def new_binfile(self, dir_path, file_name, file):
self._logging.set_function('new_binfile')
self._debug_time.start()
b = self._new_file(dir_path, file_name, 'wb', file)
t = self._debug_time.end()
self._logging.perf("file:%s" % dir_path + file_name, t)
return b
def get_file_size(self, dir_path, file_name):
full_path = self.full_path(dir_path, file_name)
return os.path.getsize(full_path)
def read_binfile(self, dir_path, file_name):
self._logging.set_function('read_binfile')
self._debug_time.start()
full_path = self.full_path(dir_path, file_name)
try:
fd = open(full_path, 'rb')
file_size = self.get_file_size(dir_path, file_name)
binfile = fd.read(file_size)
fd.close()
except Exception as m:
self._logging.error('read_binfile error: %s' % m)
binfile = None
t = self._debug_time.end()
self._logging.perf("file:%s" % dir_path + file_name, t)
return binfile
def new_textfile(self, dir_path, file_name, file):
return self._new_file(dir_path, file_name, 'w', file)
def remove_file(self, dir_path, file_name):
full_path = self.full_path(dir_path, file_name)
os.remove(full_path)
def _merge_path(self, a, b):
if a[-1] == '/' and b[0] == '/':
c = a + b[1:]
elif a[-1] != '/' and b[0] != '/':
c = ''.join([a, '/', b])
else:
c = a + b
return c
def full_path(self, dir_path, file_name):
full_path = self._merge_path(self.root_dir, dir_path)
if file_name:
full_path = self._merge_path(full_path, file_name)
return full_path
def url(self, dir_path, file_name):
url = self._merge_path(self.urlbase, dir_path)
if file_name:
url = self._merge_path(url, file_name)
return url
def make_timebase_path(base):
(y, m, d) = SpuDateTime.y_m_d()
return "%s/%s/%s/%s/" % (base, y, m, d)
def make_random_arg_path(suffix, *args):
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z']
fl = []
if len(args) > 1:
for arg in args:
if type(arg) == float:
arg = int(arg)
fl.append(str(arg))
fl.append(random.choice(l))
sfilename = ''.join(fl)
else:
sfilename = str(args[0])
filename = sfilename + '%s' % suffix
return (sfilename, filename)
if __name__ == "__main__":
createSpuFS(None, {'root':'.', 'urlbase':'http://www.google.com'})
fs = getSpuFS()
p = '/aa/bb/cc'
fn = 'asf'
fs.mkdir(p)
if not fs.exists(p):
assert None, 'mkdir faield %s' % p
fs.new_textfile(p, fn, 'aaaaa')
full = fs.full_path(p, fn)
fs.remove_file(p, fn)
if fs.exists(full):
assert None, 'rm file faield'
fs.rmdir(p)
if fs.exists(p):
assert None, 'rm dir faield'
print fs.url(p, fn)
print 'success'
|
<filename>reactive-banana-playground/josephus/src/Main.hs<gh_stars>0
module Main
( main
)
where
import Control.Concurrent.Async
import Control.Concurrent
import Control.Monad
import Data.Function
import Data.List
{-
(WIP) Simulation of Josephus problem (https://en.wikipedia.org/wiki/Josephus_problem)
with reactive-banana.
-}
{-
Design draft:
- every thread simulates one people
- every thread keeps the list of people that are still alive
- we'll need a ticking mechanism, so that every time it ticks,
exactly one people announces a `Countdown i-1`, if it is previously `Countdown i`
from previous person.
- whenever a thread counts to 0, it stops its loop.
- all counting and ticking are received by all living members.
- when a thread finds out that it is the only living member, it announces that it is the winner.
example sequence of events (n = 4, people = 2)
> Start, Tick, Countdown 4 0, Tick, Countdown 3 1, Tick, Countdown 2 0, Tick, Countdown 1 1, Tick,
> Countdown 0 0, Execute 0, Tick, Won 1
-}
data Message
= Start {num :: Int} -- a special message for starting the game, first person should start counting down from this number.
| Countdown {num :: Int, who :: Int} -- one person announces a number
| Tick -- next tick
| Execute {who :: Int} -- one person gets executed.
| Won {who :: Int} -- the last living member.
deriving (Show)
person :: Int -> [Int] -> Chan Message -> (Message -> IO ()) -> IO ()
person myId allPeople recvChan sendMessage = do
initMsg <- readChan recvChan
case initMsg of
Start k -> do
let amINextInit = myId == 0
fix
(\loop amINext curCount livings -> do
msg <- readChan recvChan
case msg of
Start {} -> error "not expecting Start."
Countdown {num = curNum, who = w} ->
if curNum /= curCount
then error $ "Expect vs actual counting: " <> show (curCount, curNum)
else
let (_, nextId) : _ = filter ((== w) . fst) $ zip livings (tail $ cycle livings)
amINext' = myId == nextId
curCount' = if curCount - 1 == 0 then k else curCount - 1
in loop amINext' curCount' livings
Tick -> do
if length livings == 1
then sendMessage (Won myId) >> loop amINext curCount livings
else do
when amINext $
sendMessage (Countdown curCount myId)
loop amINext curCount livings
Execute w ->
if w == myId
then pure ()
else
let livings' = delete w livings
(_, nextId) : _ = filter ((== w) . fst) $ zip livings (tail $ cycle livings)
amINext' = myId == nextId
in loop amINext' k livings'
Won w ->
if w == myId
then pure ()
else error $ "thread " <> show myId <> " should have been executed.")
amINextInit
k
allPeople
_ -> error "expecting only Start."
{-
TODO: a driver that sends Start, Tick and Execute.
-}
driver recvChan sendMessage k = do
sendMessage (Start k)
fix $ \loop -> do
threadDelay 1000
msg <- readChan recvChan
case msg of
Start _ -> do
sendMessage Tick
loop
Countdown {num = curNum , who = w} -> do
when (curNum == 1) $
sendMessage $ Execute w
sendMessage Tick
loop
Tick {} -> loop
Execute {} -> loop
Won {} -> pure ()
-- putStrLn $ "Simulation done, winner is " <> show w
joseph n k = do
noisyChan <- newChan
driverChan <- newChan
peopleChans <- replicateM n newChan
let allPeople = [0..n-1]
sendToAll msg = mapM_ (\ch -> writeChan ch msg) (noisyChan : driverChan : peopleChans)
_hdrs <- mapM (\(pId, ch) -> async $ person pId allPeople ch sendToAll) (zip allPeople peopleChans)
_ <- async $ forever $ do
msg <- readChan noisyChan
print msg
hDriver <- async $ driver driverChan sendToAll k
wait hDriver
main :: IO ()
main = joseph 36 12
|
<reponame>ExaByt3s/hack_scripts
#ifndef __ETHERNET_F_H_
#define __ETHERNET_F_H_
err_t ethernetif_init(struct netif *netif);
#endif //__ETHERNET_F_H_ |
/**
* A {@link com.adito.table.TableItem} implementation used by displaying
* certificates or keys in a {@link com.adito.boot.KeyStoreManager}.
*/
public class CertificateItem implements TableItem {
// Private instance variables
/**
* Constant for the if the selected item is a key.
*/
public static final String KEY = "key";
/**
* Constant for the if the selected item is a certificate.
*/
public static final String CERTIFICATE = "cert";
/**
* Constant for the if the selected item is unknown.
*/
public static final String UNKNOWN = "unknown";
private String alias;
private KeyStoreManager keyStoreManager;
/**
* Constructor
*
* @param alias alias for certificate
* @param certificate the certificate object itself
* @param keyStoreManager the key store manager that stores this key
*
*/
public CertificateItem(String alias, Certificate certificate, KeyStoreManager keyStoreManager) {
super();
this.alias = alias;
this.keyStoreManager = keyStoreManager;
}
/**
* Get if this item is removable
*
* @return removeable
*/
public boolean isRemoveable() {
return keyStoreManager.getRemoveable() && !(keyStoreManager.getName().equals(KeyStoreManager.DEFAULT_KEY_STORE) && alias.equals(InstallAction.SERVER_CERTIFICATE));
}
/**
* Get the type of certificate as a string. Current possible values are
* <b>Trusted Cert.</b>, <b>Certificate</b>, <b>Trusted Key</b>,
* <b>Key</b> or <b>Unknown</b>.
*
* @return type of certificate as a string.
*/
public String getType() {
try {
if(keyStoreManager.getKeyStore().isCertificateEntry(alias)) {
return CERTIFICATE ;
}
else if (keyStoreManager.getKeyStore().isKeyEntry(alias)){
return KEY ;
}
}
catch(Exception e) {
}
return UNKNOWN;
}
/**
* Get the alias of the certificate / key
*
* @return alias
*/
public String getAlias() {
return alias;
}
/* (non-Javadoc)
* @see com.adito.table.TableItem#getColumnValue(int)
*/
public Object getColumnValue(int col) {
switch(col) {
case 0:
return alias;
default:
return getType();
}
}
public String getSmallIconPath(HttpServletRequest request) {
if (getType().equals(CERTIFICATE)){
return CoreUtil.getThemePath(request.getSession()) + "/images/actions/exportCertificate.gif";
}
else{
return CoreUtil.getThemePath(request.getSession()) + "/images/actions/exportPrivate.gif";
}
}
} |
Cancer genetics of sporadic colorectal cancer: BRAF and PI3KCA mutations, their impact on signaling and novel targeted therapies.
Novel activating mutations in sporadic colorectal cancer (CRC) have recently been identified on major kinase encoding genes such as BRAF and PI3KCA. The presence of these activating point mutations, including the well characterized KRAS oncogene mutations, represent up to 75% of cases in CRC. These genes, that have been implicated in the adenoma-carcinoma transition, cause deregulation and constitutive activation of the MAP AKT/kinase pathways, rendering growth advantages to colon tumor cells. This review focuses on the key genetic alterations underlying the cumulative effect of multiple mutations within the colon cancer cell. Moreover, the currently available and alternative treatment approaches that may target these different genetic alterations are discussed, such as the novel BRAF inhibitor. Identification of novel mutations as well as differential gene expression analyzed by microarray reveal potential targets for combined therapeutic protocols which will result in personalized treatments in the near future. |
# Table of Contents
1. Cover
2. Title Page
3. Copyright
4. Dedication
5. Preface
6. Chapter 1: ARM® CORTEX®-M4 Development Systems
1. 1.1 Introduction
2. Reference
7. Chapter 2: Analog Input and Output
1. 2.1 Introduction
2. 2.2 TLV320AIC3104 (AIC3104) Stereo Codec for Audio Input and Output
3. 2.3 WM5102 Audio Hub Codec for Audio Input and Output
4. 2.4 Programming Examples
5. 2.5 Real-Time Input and Output Using Polling, Interrupts, and Direct Memory Access (DMA)
6. 2.6 Real-Time Waveform Generation
7. 2.7 Identifying the Frequency Response of the DAC Using Pseudorandom Noise
8. 2.8 Aliasing
9. 2.9 Identifying The Frequency Response of the DAC Using An Adaptive Filter
10. 2.10 Analog Output Using the STM32F407'S 12-BIT DAC
11. References
8. Chapter 3: Finite Impulse Response Filters
1. 3.1 Introduction to Digital Filters
2. 3.2 Ideal Filter Response Classifications: LP, HP, BP, BS
3. 3.3 Programming Examples
9. Chapter 4: Infinite Impulse Response Filters
1. 4.1 Introduction
2. 4.2 IIR Filter Structures
3. 4.3 Impulse Invariance
4. 4.4 BILINEAR TRANSFORMATION
5. 4.5 Programming Examples
6. Reference
10. Chapter 5: Fast Fourier Transform
1. 5.1 Introduction
2. 5.2 Development of the FFT Algorithm with RADIX-2
3. 5.3 Decimation-in-Frequency FFT Algorithm with RADIX-2
4. 5.4 Decimation-in-Time FFT Algorithm with RADIX-2
5. 5.5 Decimation-in-Frequency FFT Algorithm with RADIX-4
6. 5.6 Inverse Fast Fourier Transform
7. 5.7 Programming Examples
8. 5.8 Frame- or Block-Based Programming
9. 5.9 Fast Convolution
10. Reference
11. Chapter 6: Adaptive Filters
1. 6.1 Introduction
2. 6.2 Adaptive Filter Configurations
3. 6.3 Performance Function
4. 6.4 Searching for the Minimum
5. 6.5 Least Mean Squares Algorithm
6. 6.6 Programming Examples
12. Index
13. End User License Agreement
## Pages
1. xi
2. xii
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
## Guide
1. Cover
2. Table of Contents
3. Preface
4. Begin Reading
## List of Illustrations
1. Chapter 1: ARM® CORTEX®-M4 Development Systems
1. Figure 1.1 Texas Instruments TM4C123 LaunchPad.
2. Figure 1.2 STMicroelectronics STM32F407 Discovery.
3. Figure 1.3 AIC3104 audio booster pack.
4. Figure 1.4 Wolfson Pi audio card.
2. Chapter 2: Analog Input and Output
1. Figure 2.1 Basic digital signal processing system.
2. Figure 2.2 Simplified block diagram representation of input side of AIC3104 codec showing selected blocks and signal paths used by the example programs in this book (left channel only).
3. Figure 2.3 Simplified block diagram representation of output side of AIC3104 codec showing selected blocks and signal paths used by the example programs in this book (left channel only).
4. Figure 2.4 Analog input and output connections on the AIC3104 audio booster pack.
5. Figure 2.5 Analog input and output connections on the Wolfson audio card.
6. Figure 2.6 Pulse output on GPIO pin PE2 by program tm4c123_loop_dma.c.
7. Figure 2.7 Delay introduced by use of DMA-based i/o in program tm4c123_loop_dma.c. Upper trace shows rectangular pulse of duration 1 ms applied to LINE IN, lower trace shows output from LINE OUT. BUFSIZE = 256, sampling rate 48 kHz.
8. Figure 2.8 Delay introduced by use of interrupt-based i/o in program tm4c123_loop_intr.c. Upper trace shows rectangular pulse of duration 1 ms applied to LINE IN, lower trace shows output from LINE OUT. Sampling rate 48 kHz.
9. Figure 2.9 Delay introduced by use of DMA-based i/o in program stm32f4_loop_dma.c. Upper trace shows rectangular pulse of duration 1 ms applied to LINE IN, lower trace shows output from LINE OUT. BUFSIZE = 256, sampling rate 48 kHz.
10. Figure 2.10 Delay introduced by use of interrupt-based i/o in program stm32f4_loop_intr.c. Upper trace shows rectangular pulse of duration 1 ms applied to LINE IN, lower trace shows output from LINE OUT. Sampling rate 48 kHz.
11. Figure 2.11 Block diagram representation of program tm4c123_delay_intr.c.
12. Figure 2.12 Block diagram representation of program tm4c123_echo_intr.c.
13. Figure 2.13 Block diagram representation of program tm4c123_flanger_intr.c.
14. Figure 2.14 (a) impulse response and (b) magnitude frequency response of flanger implemented using program tm4c123_flanger_intr.c at an instant when delay is equal to 104.2 µs. The notches in the magnitude frequency response are at frequencies 4800 and 14,400 Hz.
15. Figure 2.15 (a) Impulse response and (b) magnitude frequency response of modified flanger implemented using program tm4c123_flanger_intr.c at an instant when delay is equal to 208.3 µs. The notches in the magnitude frequency response are at frequencies 0, 4800, 9600, 14,400, and 19,200 Hz.
16. Figure 2.16 Output waveform produced using program tm4c123_flanger_dimpulse_intr.c at an instant when delay is equal to approximately 400 µs.
17. Figure 2.21 Rectangular pulse output on GPIO pin PD15 by program stm32f4_sine_intr.c.
18. Figure 2.17 Spectrum and spectrogram of flanger output for pseudorandom noise input. In the spectrogram, the -axis represents time in seconds and the -axis represents frequency in Hz.
19. Figure 2.18 Sample values stored in array lbuffer by program stm32f4_loop_buf_intr.c plotted using MATLAB function stm32f4_logftt(). Input signal frequency was 350 Hz.
20. Figure 2.19 (a) 1-kHz sinusoid generated using program tm4c123_sine48_intr.c viewed using _Rigol DS1052E_ oscilloscope connected to (black) LINE OUT connection on audio booster pack. (b) Magnitude of FFT of signal plotted using MATLAB.
21. Figure 2.20 (a) 1-kHz sinusoid generated using program tm4c123_sine48_intr.c viewed using _Rigol DS1052E_ oscilloscope connected to scope hook on audio booster pack. (b) Magnitude of FFT of signal plotted using MATLAB.
22. Figure 2.22 Output from program tm4c123_sineDTMF_intr.c viewed using _Rigol DS1052 oscilloscope_.
23. Figure 2.23 Output from program stm32f4_square_intr.c viewed using _Rigol DS1052 oscilloscope_.
24. Figure 2.24 Output from program stm32f4_square_intr.c viewed in both time and frequency domains using _Rigol DS1052 oscilloscope_.
25. Figure 2.25 Output from program tm4c123_square_intr.c viewed using _Rigol DS1052 oscilloscope_.
26. Figure 2.26 Output from program tm4c123_square_intr.c viewed in both time and frequency domains using _Rigol DS1052 oscilloscope_.
27. Figure 2.27 Output from program tm4c123_square_1khz_intr.c viewed using _Rigol DS1052 oscilloscope_.
28. Figure 2.28 Output from program stm32f4_dimpulse_intr.c viewed in time and frequency domains using _Rigol DS1052 oscilloscope_.
29. Figure 2.29 Output from program tm4c123_dimpulse_intr.c viewed using _Rigol DS1052 oscilloscope_.
30. Figure 2.30 Output waveform generated by program tm4c123_ramp_intr.c.
31. Figure 2.31 Output waveform generated by program tm4c123_am_intr.c.
32. Figure 2.32 Output from program tm4c123_prbs_intr.c viewed using _Rigol DS1052_ oscilloscope and _Goldwave_.
33. Figure 2.33 Output from program tm4c123_prbs_deemph_intr.c viewed using _Rigol DS1052_ oscilloscope and _Goldwave_.
34. Figure 2.34 Output from program tm4c123_prbs_hpf_intr.c viewed using _Rigol DS1052_ oscilloscope and _Goldwave_.
35. Figure 2.35 Output from program tm4c123_prbs_biquad_intr.c viewed using _Rigol DS1052_ oscilloscope and _Goldwave_.
36. Figure 2.36 Output from program tm4c123_prandom_intr.c viewed using _Rigol DS1052 oscilloscope_.
37. Figure 2.38 Sample values read from the WM5102 ADC and stored in array lbuffer by program stm32f4_loop_buf_intr.c.
38. Figure 2.37 Square wave input signal used with program stm32f4_loop_buf_intr.c.
39. Figure 2.39 Sample values read from the WM5102 ADC and stored in array lbuffer by program tm4c123_loop_buf_intr.c.
40. Figure 2.40 Sample values read from the AIC3104 ADC and stored in array buffer by program tm4c123_sine48_loop_intr.c.
41. Figure 2.41 Connection diagram for program tm4c123_sysid_CMSIS_intr.c.
42. Figure 2.42 The impulse response and magnitude frequency identified using program tm4c123_sysid_CMSIS_intr.c with connections as shown in Figure 2.41, displayed using MATLAB function tm4c123_logfft(). Sampling frequency 8000 Hz, 128-coefficient adaptive filter.
43. Figure 2.43 The impulse response and magnitude frequency identified using program tm4c123_sysid_CMSIS_intr.c with a first-order low-pass analog filter connected between LINE IN and LINE OUT sockets, displayed using MATLAB function tm4c123_logfft(). Sampling frequency 8000 Hz, 128-coefficient adaptive filter.
44. Figure 2.44 The impulse response and magnitude frequency identified using program tm4c123_sysid_CMSIS_intr.c with connections as shown in Figure 2.41 and de-emphasis enabled, displayed using MATLAB function tm4c123_logfft(). Sampling frequency 8000 Hz, 128-coefficient adaptive filter.
45. Figure 2.45 The impulse response and magnitude frequency identified using program stm32f4_sysid_CMSIS_intr.c with LINE OUT connected directly to LINE OUT, displayed using MATLAB function stm32f4_logfft(). Sampling frequency 8000 Hz, 128-coefficient adaptive filter.
46. Figure 2.46 Connection diagram for program tm4c123_sysid_CMSIS_intr.c.
47. Figure 2.47 The impulse response and magnitude frequency identified using program tm4c123_sysid_CMSIS_intr.c with connections as shown in Figure 2.46, displayed using MATLAB function tm4c123_logfft(). Sampling frequency 16,000 Hz, 192-coefficient adaptive filter.
48. Figure 2.48 Pulse output on GPIO pin PE2 by program tm4c123_sysid_CMSIS_intr.c running at a sampling rate of 16 kHz and using 192 adaptive filter coefficients.
49. Figure 2.49 Output from program stm32f4_sine8_dac12_intr.c viewed using _Rigol DS1052 oscilloscope_.
50. Figure 2.50 Output from program stm32f4_square_dac12_intr.c viewed using _Rigol DS1052 oscilloscope_.
51. Figure 2.51 Output from program stm32f4_dimpulse_dac12_intr.c viewed using _Rigol DS1052 oscilloscope_.
52. Figure 2.52 Output from program stm32f4_prbs_dac12_intr.c viewed using _Rigol DS1052 oscilloscope_.
3. Chapter 3: Finite Impulse Response Filters
1. Figure 3.1 Block diagram representation of a generic FIR filter.
2. Figure 3.2 Poles and zeros and region of convergence for causal sequence , , plotted in the -plane.
3. Figure 3.3 Poles and zeros and region of convergence for anticausal sequence , , plotted in the -plane.
4. Figure 3.4 Possible region of convergence, plotted in the -plane, corresponding to a right-sided causal sequence for a system with two real-valued poles.
5. Figure 3.6 Possible region of convergence, plotted in the -plane, corresponding to a two-sided noncausal sequence for a system with two real-valued poles.
6. Figure 3.7 Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is causal and stable.
7. Figure 3.9 Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is causal and unstable.
8. Figure 3.10 Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is anticausal and stable.
9. Figure 3.12 Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is anticausal and unstable.
10. Figure 3.13 Time-domain and -domain block diagram representations of a discrete-time LTI system.
11. Figure 3.14 Mapping from the -plane to the -plane.
12. Figure 3.15 Ideal filter magnitude frequency responses. (a) Low-pass (LP). (b) High-pass (HP). (c) Band-pass (BP). (d) Band-stop (BS).
13. Figure 3.16 Ideal low-pass frequency response defined over normalized frequency range .
14. Figure 3.17 Sixty-one of the infinite number of values in the discrete-time impulse response obtained by taking the inverse DTFT of the ideal low-pass frequency response of Figure 3.16.
15. Figure 3.18 The discrete-time impulse response of Figure 3.17 truncated to values.
16. Figure 3.19 The continuous, periodic magnitude frequency response obtained by taking the DTFT of the truncated impulse response shown in Figure 3.18 (plotted against normalized frequency ).
17. Figure 3.20 A 33-point Hanning window.
18. Figure 3.21 The magnitude frequency response corresponding to the filter coefficients of Figure 3.22 (plotted against normalized frequency ).
19. Figure 3.22 The filter coefficients of Figure 3.17 multiplied by the Hanning window of Figure 3.20.
20. Figure 3.23 The magnitude frequency responses of Figure 3.19 and 3.21 plotted on a logarithmic scale, against normalized frequency .
21. Figure 3.24 Ideal high-pass filter magnitude frequency response.
22. Figure 3.25 Ideal band-pass filter magnitude frequency response.
23. Figure 3.26 Ideal band-stop filter magnitude frequency response.
24. Figure 3.27 Theoretical magnitude frequency response of the five-point moving average filter (sampling rate 8 kHz).
25. Figure 3.28 Magnitude frequency response of the five-point moving average filter demonstrated using program stm32f4_average_prbs_intr.c and displayed using (a) _Rigol DS1052E_ oscilloscope (lower trace) and (b) _Goldwave_.
26. Figure 3.29 Connection diagram for use of program tm4c123_sysid_CMSIS_intr.c to identify the characteristics of a moving average filter implemented using two sets of hardware.
27. Figure 3.30 Impulse response of the five-point moving average filter identified using two launchpads and booster packs and programs tm4c123_sysid_CMSIS_intr.c and tm4c123_average_intr.c.
28. Figure 3.31 Magnitude frequency response of the five-point moving average filter identified using two sets of hardware and programs tm4c123_sysid_CMSIS_intr.c and tm4c123_average_intr.c.
29. Figure 3.32 Connection diagram for program tm4c123_sysid_average_CMSIS_intr.c.
30. Figure 3.33 Magnitude frequency response of an eleven-point moving average filter implemented using program tm4c123_average_prbs_intr.c and displayed using _Goldwave_.
31. Figure 3.34 Magnitude frequency response of a five-point moving average filter with Hanning window implemented using program stm32f4_average_prbs_intr.c and displayed using _Goldwave_.
32. Figure 3.35 MATLAB fdatool window corresponding to design the of an FIR band-stop filter centered at 2700 Hz.
33. Figure 3.36 MATLAB fdatool window corresponding to design of FIR band-pass filter centered at 1750 Hz.
34. Figure 3.37 Output generated using program tm4c123_fir_prbs_intr.c and coefficient file bs2700.h displayed using (a) _Rigol DS1052E_ oscilloscope and (b) _GoldWave_.
35. Figure 3.38 Output generated using program tm4c123_fir_prbs_intr.c using coefficient files (a) pass2b.h and (b) hp55.h.
36. Figure 3.39 Magnitude of the FFT of the output from program stm32f4_fir_prbs_buf_intr.c using coefficient header file bp1750.h.
37. Figure 3.40 Filter coefficients used in program stm32f4_fir_prbs_buf_intr.c (bp1750.h).
38. Figure 3.41 Magnitude of the FFT of the filter coefficients used in program stm32f4_fir_prbs_buf_intr.c.
39. Figure 3.42 A 200 Hz square wave passed through three different low-pass filters implemented using program tm4c123_fir3lp_intr.c.
40. Figure 3.43 Output generated using program tm4c123_fir_4types_intr.c.
41. Figure 3.44 Pseudorandom noise filtered using program tm4c123_notch2_intr.c.
42. Figure 3.45 Block diagram representation of scrambler implemented using program tm4c123_scrambler_intr.c.
43. Figure 3.46 Pulses output on GPIO pin PE2 by programs tm4c123_fir_prbs_intr.c and tm4c123_fir_prbs_dma.c.
4. Chapter 4: Infinite Impulse Response Filters
1. Figure 4.1 Direct form I IIR filter structure.
2. Figure 4.2 Direct form II IIR filter structure.
3. Figure 4.3 Direct form II transpose IIR filter structure.
4. Figure 4.4 Cascade form IIR filter structure.
5. Figure 4.5 Fourth-order IIR filter with two direct form II sections in cascade.
6. Figure 4.6 Parallel form IIR filter structure.
7. Figure 4.7 Fourth-order IIR filter with two direct form II sections in parallel.
8. Figure 4.8 Relationship between analog and digital frequencies, and , due to frequency warping in the bilinear transform.
9. Figure 4.9 (a) Magnitude frequency response of filter . (b) Phase response of filter .
10. Figure 4.10 Impulse responses (scaled by sampling period ) and of continuous-time filter and its impulse-invariant digital implementation.
11. Figure 4.11 Output from program tm4c123_iirsos_prbs_intr.c using coefficient file impinv.h, viewed using the FFT function of a _Rigol DS1052E_ oscilloscope.
12. Figure 4.12 Output from program tm4c123_iirsos_prbs_intr.c using coefficient file impinv.h, viewed using _Goldwave_.
13. Figure 4.13 Output from program tm4c123_iirsos_delta_intr.c using coefficient file impinv.h, viewed using the FFT function of a _Rigol DS1052E_ oscilloscope.
14. Figure 4.14 The magnitude frequency response of the filter implemented by program tm4c123_iirsos_delta_intr.c using coefficient file impinv.h, plotted using MATLAB function tm4c123_logfft().
15. Figure 4.15 Output from program tm4c123_iirsos_prbs_intr.c using coefficient file bilinear.h, viewed using the FFT function of a _Rigol DS1052E_ oscilloscope.
16. Figure 4.18 The magnitude frequency response of the filter implemented by program tm4c123_iirsos_delta_intr.c using coefficient file bilinear.h, plotted using MATLAB function tm4c123_logfft().
17. Figure 4.19 The effect of the bilinear transform on the magnitude frequency response of the example filter.
18. Figure 4.20 MATLAB fdatool window showing the magnitude frequency response of a fourth-order elliptic low-pass filter.
19. Figure 4.21 MATLAB fdatool window showing the magnitude frequency response of a second-order Chebyshev low-pass filter.
20. Figure 4.16 Output from program tm4c123_iirsos_prbs_intr.c using coefficient file bilinear.h, viewed using _Goldwave_.
21. Figure 4.22 Impulse response and magnitude frequency response of the filter implemented by program tm4c123_iirsos_delta_intr.c, using coefficient file elliptic.h, plotted using MATLAB function tm4c123_logfft().
22. Figure 4.23 Output from program tm4c123_iirsos_delta_intr.c, using coefficient file elliptic.h viewed using a _Rigol DS1052E_ oscilloscope.
23. Figure 4.24 MATLAB fdatool window showing the magnitude frequency response of an 18th-order band-pass filter centered on 2000 Hz.
24. Figure 4.25 Output from program tm4c123_iirsos_prbs_intr.c, using coefficient file bp2000.h viewed using a _Rigol DS1052E_ oscilloscope.
25. Figure 4.26 Output from program tm4c123_iirsos_prbs_intr.c, using coefficient file bp2000.h viewed using _Goldwave_.
26. Figure 4.27 Connection diagram for program tm4c123_sysid_biquad_intr.c.
27. Figure 4.28 Frequency response of signal path through DAC, connecting cable, and ADC shown in Figure 4.27 with biquad filters disabled.
28. Figure 4.29 Frequency response of signal path through DAC, connecting cable, and ADC shown in Figure 4.27 with biquad filters programmed as a fourth-order elliptic low-pass filter and enabled.
29. Figure 4.30 fdatool used to design a fourth-order elliptic band-pass filter.
30. Figure 4.31 Frequency response of signal path through DAC, connecting cable, and ADC shown in Figure 4.27 with biquad filters programmed as a fourth-order elliptic band-pass filter and enabled.
31. Figure 4.32 Block diagram representation of Equation (4.53).
32. Figure 4.33 Block diagram representation of Equation (4.54).
33. Figure 4.34 Output samples generated by program stm32f4_sinegenDTMF_intr.c plotted using MATLAB function stm32f4_logfft().
34. Figure 4.35 Output signal generated by program stm32f4_sinegenDTMF_intr.c viewed using a _Rigol DS1052E_ oscilloscope.
35. Figure 4.36 Pole-zero map for notch filter described by Equation (4.56) for and .
36. Figure 4.37 Frequency response of notch filter described by Equation (4.56) for and .
37. Figure 4.38 Pseudorandom noise filtered by program tmc123_iirsos_prbs_intr.c using header file iir_notch_coeffs.h.
5. Chapter 5: Fast Fourier Transform
1. Figure 5.1 Twiddle factors for represented as vectors in the complex plane.
2. Figure 5.2 Decomposition of 8-point DFT into two 4-point DFTs using decimation-in-frequency with radix-2.
3. Figure 5.3 Decomposition of 4-point DFT into two 2-point DFTs using decimation-in-frequency with radix-2.
4. Figure 5.4 2-point FFT butterfly structure.
5. Figure 5.5 Block diagram representation of 8-point FFT using decimation-in-frequency with radix-2.
6. Figure 5.6 Decomposition of 8-point DFT into two 4-point DFTs using decimation-in-time with radix-2.
7. Figure 5.7 Decomposition of 4-point DFT into two 2-point DFTs using decimation-in-time with radix-2.
8. Figure 5.8 Block diagram representation of 8-point FFT using decimation-in-time with radix-2.
9. Figure 5.9 Complex contents of array samples (TESTFREQ = 800.0) before calling function dft(), viewed in a _Memory_ window in the _MDK-ARM debugger_.
10. Figure 5.10 Complex contents of array samples (TESTFREQ = 800.0) before calling function dft(), plotted using MATLAB function stm32f4_plot_complex().
11. Figure 5.11 Complex contents of array samples (TESTFREQ = 800.0) after calling function dft(), plotted using MATLAB function stm32f4_plot_complex().
12. Figure 5.12 Complex contents of array samples (TESTFREQ = 900.0) after calling function dft(), plotted using MATLAB function stm32f4_plot_complex().
13. Figure 5.13 _MDK-ARM Register_ window showing _Sec_ item.
14. Figure 5.14 Output signal from program tm4c123_dft128_dma.c viewed using an oscilloscope.
15. Figure 5.15 Output signal from program stm32f4_dft128_dma.c viewed using an oscilloscope.
16. Figure 5.16 Partial contents of array outbuffer, plotted using MATLAB function tm4c123_plot_real(), for input sinusoid of frequency 1750 Hz.
17. Figure 5.17 Detail of output signal from program tm4c123_dft128_dma.c for input sinusoid of frequency 1781 Hz.
18. Figure 5.18 Detail of output signal from program tm4c123_dft128_dma.c for input sinusoid of frequency 1750 Hz.
19. Figure 5.19 Partial contents of array outbuffer, plotted using MATLAB function tm4c123_plot_real(), for input sinusoid of frequency 1781 Hz.
20. Figure 5.20 Detail of output signal from program tm4c123_dft128_dma.c, modified to apply a Hamming window to blocks of input samples, for input sinusoid of frequency 1750 Hz.
21. Figure 5.21 Detail of output signal from program tm4c123_dft128_dma.c, modified to apply a Hamming window to blocks of input samples, for input sinusoid of frequency 1781 Hz.
22. Figure 5.22 Partial contents of array outbuffer, plotted using MATLAB function tm4c123_plot_real(), for input sinusoid of frequency 1750 Hz. (Hamming window applied to blocks of input samples.)
23. Figure 5.23 Partial contents of array outbuffer, plotted using MATLAB function tm4c123_plot_real(), for input sinusoid of frequency 1781 Hz. (Hamming window applied to blocks of input samples.)
24. Figure 5.24 Output signal generated by program tm4c123_fft128_sinetable_dma.c, displayed using a _Rigol DS1052E_ oscilloscope.
25. Figure 5.25 Output signal from program tm4c123_graphicEQ_CMSIS_dma.c, displayed using _Goldwave_ , for a pseudorandom noise input signal. bass_gain = 0.1, mid_gain = 0.1, treble_gain = 0.25.
6. Chapter 6: Adaptive Filters
1. Figure 6.1 Basic adaptive filter structure.
2. Figure 6.2 Simplified block diagram of basic adaptive filter structure.
3. Figure 6.3 Basic adaptive filter structure configured for prediction.
4. Figure 6.4 Basic adaptive filter structure configured for system identification.
5. Figure 6.5 Basic adaptive filter structure configured for noise cancellation.
6. Figure 6.6 Alternative representation of basic adaptive filter structure configured for noise cancellation emphasizing the difference in paths from a single noise source to primary and reference sensors.
7. Figure 6.7 Basic adaptive filter structure configured for equalization.
8. Figure 6.8 Block diagram representation of FIR filter.
9. Figure 6.9 Performance function for single weight case.
10. Figure 6.10 Steepest descent algorithm illustrated for single weight case.
11. Figure 6.11 Plots of (a) desired output, (b) adaptive filter output, and (c) error generated using program stm32f4_adaptive.c and displayed using MATLAB function stm32f4_plot_real().
12. Figure 6.12 Block diagram representation of program tm4c213_adaptnoise_intr.c.
13. Figure 6.13 Block diagram representation of program tm4c123_noise_cancellation_intr.c.
14. Figure 6.14 Impulse response and magnitude frequency response of IIR filter identified by the adaptive filter in program tm4c123_noise_cancellation_intr.c and plotted using MATLAB function tm4c123_logfft().
15. Figure 6.15 Block diagram representation of program tm4c123_adaptIDFIR_CMSIS_intr.c.
16. Figure 6.16 Output from program stm32f4_adaptIDFIR_CMSIS_intr.c using coefficient header file bs55.h viewed using _Rigol DS1052E_ oscilloscope.
17. Figure 6.17 Output from adaptive filter in program tm4c123_adaptIDFIR_CMSIS_init_intr.c.
18. Figure 6.18 Block diagram representation of program tm4c123_iirsosadapt_CMSIS_intr.c.
19. Figure 6.19 Output from adaptive filter in program tm4c123_iirsosadapt_CMSIS_intr.c viewed using a _Rigol DS1052E_ oscilloscope.
20. Figure 6.20 Adaptive filter coefficients from program tm4c123_iirsosadapt_CMSIS_intr.c plotted using MATLAB function tm4c123_logfft().
21. Figure 6.21 Connection diagram for program tm4c123_sysid_CMSIS_intr.c in Example 6.14.
22. Figure 6.22 Adaptive filter coefficients from program tm4c123_sysid_CMSIS_intr.c plotted using MATLAB function tm4c123_logfft()
23. Figure 6.23 Adaptive filter coefficients from program tm4c123_sysid_CMSIS_dma.c plotted using MATLAB function tm4c123_logfft(). (a) BUFSIZE = 32 (b) BUFSIZE = 64.
## List of Tables
1. Chapter 2: Analog Input and Output
1. Table 2.1 Summary of DMA Control Structures Used and Flags Set in Interrupt Service Routines SSI0IntHandler() and SSI1IntHandler() in Program tm4c123_loop_dma.c
2. Chapter 5: Fast Fourier Transform
1. Table 5.1 Execution Times for Functions dft(), dftw(), fft() and arm_cfft_f32()
# DIGITAL SIGNAL PROCESSING USING THE ARM® CORTEX®-M4
**DONALD S. REAY**
Heriot-Watt University
Copyright © 2016 by John Wiley & Sons, Inc. All rights reserved
Published by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
ARM and Cortex are registered trademarks of ARM Limited (or its subsidiaries) in the EU and/or elsewhere. All rights reserved.
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/ trademarks for a list of additional trademarks. The MathWorks Publisher Logo identifies books that contain MATLAB® content. Used with Permission. The book's or downloadable software's use of discussion of MATLAB® software or related products does not constitute endorsement or sponsorship by the MathWorks of a particular use of the MATLAB® software or related products.
For MATLAB® product information, or information on other related products, please contact:
The MathWorks, Inc., 3 Apple Hill Drive, Natick. MA 01760-2098 USA, Tel: 508-647-7000, Fax: 508-647-7001, E-mail: [email protected], Web: www.mathworks.com, How to buy: www.mathworks.com/store
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at <http://www.wiley.com/go/permissions>.
Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages.
For general information on our other products and services or for technical support, please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic formats. For more information about Wiley products, visit our web site at www.wiley.com.
**_Library of Congress Cataloging-in-Publication Data:_**
Reay, Donald (Donald S.), author.
Digital signal processing using the ARM Cortex-M4 / Donald Reay.
pages cm
Includes bibliographical references and index.
ISBN 978-1-118-85904-9 (pbk.)
1. Signal processing–Digital techniques. 2. ARM microprocessors. I. Title.
TK5102.9.R4326 2015
621.382′2–dc23
2015024771
_To Reiko_
# Preface
This book continues the series started in 1990 by Rulph Chassaing and Darrell Horning's _Digital Signal Processing with the TMS320C25_ , which tracked the development of successive generations of digital signal processors by Texas Instruments. More specifically, each book in the series up until now has complemented a different inexpensive DSP development kit promoted for teaching purposes by the Texas Instruments University Program. A consistent theme in the books has been the provision of a large number of simple example programs illustrating DSP concepts in real time, in an electrical engineering laboratory setting.
It was Rulph Chassaing's belief, and this author continues to believe, that hands-on teaching of DSP, using hardware development kits and laboratory test equipment to process analog audio frequency signals, is a valuable and effective way of reinforcing the theory taught in lectures.
The contents of the books, insofar as they concern fundamental concepts of digital signal processing such as analog-to-digital and digital-to-analog conversion, finite impulse response (FIR) and infinite impulse response (IIR) filtering, the Fourier transform, and adaptive filtering, have changed little. Every academic year brings another cohort of students wanting to study this material. However, each book has featured a different DSP development kit.
In 2013, Robert Owen suggested to me that hands-on DSP teaching could be implemented using an inexpensive ARM® Cortex-M4® microcontroller. I pointed out that a Texas Instruments C674x processor was very significantly more computationally powerful than an ARM Cortex-M4. But I also went ahead and purchased a Texas Instruments Stellaris LaunchPad. I constructed an audio interface using a Wolfson WM8731 codec and successfully ported the program examples from my previous book to that hardware platform.
This book is aimed at senior undergraduate and postgraduate electrical engineering students who have some knowledge of C programming and linear systems theory, but it is intended, and hoped, that it may serve as a useful resource for anyone involved in teaching or learning DSP and as a starting point for teaching or learning more.
I am grateful to Robert Owen for first making me aware of the ARM Cortex-M4; to Khaled Benkrid at the ARM University Program and to the Royal Academy of Engineering for making possible a six-month Industrial Secondment to ARM during which teaching materials for the STM32f01 platform were developed; to Gordon McLeod and Scott Hendry at Wolfson Microelectronics for their help in getting the Wolfson Pi audio card to work with the STM32f01 Discovery; to Sean Hong, Karthik Shivashankar, and Robert Iannello at ARM for all their help; to Joan Teixidor Buixeda for helping to debug the program examples; to Cathy Wicks at the TI University Program and Hieu Duong at CircuitCo for developing the audio booster pack; and to Kari Capone and Brett Kurzman at Wiley for their patience. But above all, I thank Rulph Chassaing for inspiring me to get involved in teaching hands-on DSP.
Donald S. Reay
Edinburgh
2015
# Chapter 1
ARM® CORTEX®-M4 Development Systems
## 1.1 Introduction
Traditionally, real-time digital signal processing (DSP) has been implemented using specialized and relatively expensive hardware, for example, digital signal processors or field-programmable gate arrays (FPGAs). The ARM® Cortex®-M4 processor makes it possible to process audio in real time (for teaching purposes, at least) using significantly less expensive, and simpler, microcontrollers.
The ARM Cortex-M4 is a 32-bit microcontroller. Essentially, it is an ARM Cortex-M3 microcontroller that has been enhanced by the addition of DSP and single instruction multiple data (SIMD) instructions and (optionally) a hardware floating-point unit (FPU). Although its computational power is a fraction of that of a floating-point digital signal processor, for example, the Texas Instruments C674x, it is quite capable of implementing DSP algorithms, for example, FIR and IIR filters and fast Fourier transforms for audio signals in real-time.
A number of semiconductor manufacturers have developed microcontrollers that are based on the ARM Cortex-M4 processor and that incorporate proprietary peripheral interfaces and other IP blocks. Many of these semiconductor manufacturers make available very-low-cost evaluation boards for their ARM Cortex-M4 microcontrollers. Implementing real-time audio frequency example programs on these platforms, rather than on more conventional DSP development kits, constitutes a reduction of an order of magnitude in the hardware cost of implementing hands-on DSP teaching. For the first time, students might realistically be expected to own a hardware platform that is useful not only for general microcontroller/microprocessor programming and interfacing activities but also for implementation of real-time DSP.
### 1.1.1 Audio Interfaces
At the time that the program examples presented in this book were being developed, there were no commercially available low-cost ARM Cortex-M4 development boards that incorporated high-quality audio input and output. The STMicroelectronics STM32F407 Discovery board features a high-quality audio digital-to-analog converter (DAC) but not a correspondinganalog-to-digital converter (ADC). Many ARM Cortex-M4 devices, including both the STMicroelectronics STM32F407 and the Texas Instruments TM4C123, feature multichannel instrumentation-quality ADCs. But without additional external circuitry, these are not suitable for the applications discussed in this book.
The examples in this book require the addition (to an inexpensive ARM Cortex-M4 development board) of an (inexpensive) audio interface.
In the case of the STMicroelectronics STM32F407 Discovery board and of the Texas Instruments TM4C123 LaunchPad, compatible and inexpensive audio interfaces are provided by the Wolfson Pi audio card and the CircuitCo audio booster pack, respectively. The low-level interfacing details and the precise performance characteristics and extra features of the two audio interfaces are subtly different. However, each facilitates the input and output of high-quality audio signals to and from an ARM Cortex-M4 processor on which DSP algorithms may be implemented.
Almost all of the program examples presented in the subsequent chapters of this book are provided, in only very slightly different form, for both the STM32F407 Discovery and the TM4C123 LaunchPad, on the partner website `http://www.wiley.com/go/Reay/ARMcortexM4`.
However, in most cases, program examples are described in detail, and program listings are presented, only for one or other hardware platform. Notable exceptions are that, in Chapter 2, low-level i/o mechanisms (implemented slightly differently in the two devices) are described in detail for both hardware platforms and that a handful of example programs use features unique to one or other processor/audio interface.
This book does not describe the internal architecture or features of the ARM Cortex-M4 processor in detail. An excellent text on that subject, including details of its DSP-related capabilities, is _The Definitive Guide to ARM ® Cortex®-M3 and Cortex®-M4 Processors_ by Yiu [1].
### 1.1.2 Texas Instruments TM4C123 LaunchPad and STM32F407 Discovery Development Kits
The Texas Instruments and STMicroelectronics ARM Cortex-M4 processor boards used in this book are shown in Figures 1.1 and 1.2. The program examples presented in this book assume the use of the _Keil MDK-ARM_ development environment, which is compatible with both development kits. An alternative development environment, Texas Instruments' _Code Composer Studio_ , is available for the TM4C123 LaunchPad and the program examples have been tested using this. Versions of the program examples compatible with _Code Composer Studio version 6_ are provided on the partner website `http://www.wiley.com/go/Reay/ARMcortexM4`.
**Figure 1.1** Texas Instruments TM4C123 LaunchPad.
**Figure 1.2** STMicroelectronics STM32F407 Discovery.
The CircuitCo audio booster pack (for the TM4C123 LaunchPad) and the Wolfson Pi audio card (for the STM32F407 Discovery) are shown in Figures1.3 and 1.4. The audio booster pack and the launchpad plug together, whereas the Wolfson audio card, which was designed for use with a Raspberry Pi computer, must be connected to the Discovery using a custom ribbon cable (available from distributor Farnell).
**Figure 1.3** AIC3104 audio booster pack.
**Figure 1.4** Wolfson Pi audio card.
Rather than presenting detailed instructions here that may be obsolete as soon as the next version of _MDK-ARM_ is released, the reader is directed to the "getting started" guide at the partner website `http://www.wiley.com/go/Reay/ARMcortexM4`. and before progressing to the next chapter of this book will need to install _MDK-ARM_ , including the "packs" appropriate to the hardware platform being used and including the CMSIS DSP library, download the program examples from the website, and become familiar with how to open a project in _MDK-ARM_ , add and remove files from a project, build a project, start and stop a debug session, and run and halt a program running on the ARM Cortex-M4 processor.
Some of the example programs implement DSP algorithms straightforwardly, and with a view to transparency and understandability rather than computational efficiency or elegance. In several cases, ARM's CMSIS DSP library functions are used. These are available for both the STMicroelectronics and Texas Instruments processors as part of the _MDK-ARM_ development environment. In appropriate circumstances, these library functions are particularly computationally efficient. This is useful in some of the program examples where the demands of running in real-time approach the limits of what is achievable with the ARM Cortex-M4. One difference between the two devices used in this book is that STM32F407 uses a processor clock speed of 168 MHz, whereas the TM4C123 clock speed is 84 MHz. As presented in the book, all of the program examples will run in real time on either device. However, if the parameter values used are changed, for example, if the number of coefficients in an FIR filter is increased, it is likely that the limits of the slower device will be reached more readily than those of the faster one.
All of the program examples have been tested using the free, code size-limited, version of _MDK-ARM_. The aim of hands-on DSP teaching, and the intention of this book, is not to teach about the architecture of the ARM Cortex-M4. The device is used because it provides a capable and inexpensive platform. Nor is it the aim of hands-on DSP teaching, or the intention of this book, to teach about the use of _MDK-ARM_. The aim of hands-on DSP teaching is to reinforce DSP theory taught in lectures through the use of illustrative examples involving the real-time processing of audio signals in an electrical engineering laboratory environment. That is to say where test equipment such as oscilloscopes, signal generators, and connecting cables are available.
### 1.1.3 Hardware and Software Tools
To perform the experiments described in this book, a number of software and hardware resources are required.
1. An ARM Cortex-M4 development board and audio interface. Either aTexas Instruments TM4C123 LaunchPad and a CircuitCo audio booster pack or an STMicroelectronics STM32F407 Discovery board and a Wolfson Microelectronics Pi audio card are suitable hardware platforms.
2. A host PC running an integrated development environment (IDE) and with a spare USB connection. The program examples described in this book were developed and tested using the _Keil MDK-ARM_ development environment. However, versions of the program examples for the TM4C123 LaunchPad and project files compatible with Texas Instruments _Code Composer Studio_ IDE are provided on the partner website `http://www.wiley.com/go/Reay/ARMcortexM4`.
3. The TM4C123 LaunchPad and the STM32F407 Discovery board use slightly different USB cables to connect to the host PC. The launchpad is supplied with a USB cable, while the STM32F407 Discovery is not.
4. Whereas the audio booster pack and the launchpad plug together, the Wolfson Pi audio card does not plug onto the STM32F407 Discovery board. Connections between the two can be made using a custom ribbon cable, available from distributor Farnell.
5. An oscilloscope, a signal generator, a microphone, headphones, and various connecting cables. Several of these items will be found in almost any electrical engineering laboratory. If you are using the STM32F407 Discovery and Wolfson Pi audio card, then a microphone is unnecessary. The audio card has built-in digital MEMS microphones. The Wolfson Pi audio card is also compatible with combined microphone and headphone headsets (including those supplied with Apple and Samsung smartphones). Stereo 3.5 mm jack plug to 3.5 mm jack plug cables and stereo 3.5 mm jack plug to (two) RCA (phono) plugs and RCA to BNC adapters are the specific cables required.
6. Project and example program files from the partner website `http://www.wiley.com/go/Reay/ARMcortexM4`.
## Reference
1. 1 .Yiu, J., " _The Definitive Guide to ARM ® Cortex®-M3 and Cortex®-M4 Processors_", Third Edition, Elsevier Inc., 2014.
# Chapter 2
Analog Input and Output
## 2.1 Introduction
A basic DSP system, suitable for processing audio frequency signals, comprises a digital signal processor (DSP) and analog interfaces as shown in Figure 2.1. The Texas Instruments TM4C123 LaunchPad and audio booster pack provide such a system, using a TM4C123 ARM® Cortex®-M4 processor and a TLV320AIC3104 (AIC3104) codec [1]. The STMicro STM32F407 Discovery and the Wolfson audio card provide such a system, using an STM32407 ARM® Cortex®-M4 processor and a WM5102 codec [2]. The term codec refers to the coding of analog waveforms as digital signals and the decoding of digital signals as analog waveforms. The AIC3104 and WM5102 codecs perform both the analog-to-digital conversion (ADC) and digital-to-analog conversion (DAC) functions shown in Figure 2.1.
**Figure 2.1** Basic digital signal processing system.
Both the AIC3104 and WM5102 codecs communicate with their associated processors (TM4C123 and STM32F407) using I2C bus for control (writing to the codec's control registers) and I2S for (audio) data transfer.
### 2.1.1 Sampling, Reconstruction, and Aliasing
Within DSPs, signals are represented as sequences of discrete sample values, and whenever signals are sampled, the possibility of aliasing arises. Later in this chapter, the phenomenon of aliasing is explored in more detail. Suffice to say at this stage that aliasing is undesirable and that it may be avoided by the use of an antialiasing filter placed at the input to the system shown in Figure 2.1 and by suitable design of the DAC. In a low-pass system, an effective antialiasing filter is one that allows frequency components at frequencies below half the sampling frequency to pass but that attenuates greatly, or stops, frequency components at frequencies greater than or equal to half the sampling frequency. A suitable DAC for a low-pass system is itself a low-pass filter having characteristics similar to the aforementioned antialiasing filter. The term DAC commonly refers to an electronic device that converts discrete sample values represented in digital hardware into a continuous analogue electrical signal. When viewed purely from a signal processing perspective, a DAC acts as a reconstruction filter. Although they differ in a number of respects, both the AIC3104 and WM5102 codecs contain both digital and analog antialiasing and reconstruction filters and therefore do not require additional external filters.
## 2.2 TLV320AIC3104 (AIC3104) Stereo Codec for Audio Input and Output
The audio booster pack makes use of a TLV320AIC3104 (AIC3104) codec for analog input and output (see Figures 2.2 and 2.3). The AIC3104 is a low-power stereo audio codec, based on sigma-delta technology, and designed for use in portable battery-powered applications. It features a number of microphone and line-level inputs, configurable for single-ended or differential connection. On its output side, a number of differential and high-power outputs are provided. The high-power outputs are capable of driving headphones. A number of different sampling rates ranging from 8 to 96 kHz are supported by the device. The analog-to-digital converter (ADC), or coder, part of the codec converts an analog input signal into a sequence of (16-bit, 24-bit, or 32-bit signed integer) sample values to be processed by the DSP. The digital-to-analog converter (DAC), or decoder, part of the codec reconstructs an analog output signal from a sequence of (16-bit, 24-bit, or 32-bit signed integer)sample values that have been processed by the DSP and written to the DAC.
**Figure 2.2** Simplified block diagram representation of input side of AIC3104 codec showing selected blocks and signal paths used by the example programs in this book (left channel only).
**Figure 2.3** Simplified block diagram representation of output side of AIC3104 codec showing selected blocks and signal paths used by the example programs in this book (left channel only).
Also contained in the device are several programmable digital filters and gain blocks. The codec is configured using a number of control registers, offering so many options that it is beyond the scope of this text to describe them fully. However, choices of sampling frequency, input connection, and ADC PGA gain are made available in the example programs through the parameters passed to function `tm4c123_aic3104_init()`. In addition, it is possible to write to any of the codec control registers using function `I2CRegWrite()`.
Later in this chapter, examples of enabling some of the internal digital filter blocks by writing to the control registers of the AIC3104 are described. In Chapter 4, the characteristics of the programmable digital filters within the AIC3104 are examined in greater detail.
Data is passed to and from the AIC3104 via its I2S serial interface. MIC IN (pink), LINE IN (blue), LINE OUT (green), and HP OUT (black) connections are made available via four 3.5 mm jack sockets on the audio booster pack, and these are connected to the AIC3104 as shown in Figure 2.4. In addition, for reasons explained later in this chapter, jumpers J6 and J7 on the audio booster pack allow connection of first-order low-pass filters and scope hook test points TP2 and TP3 to LINE OUT on the AIC3104.
**Figure 2.4** Analog input and output connections on the AIC3104 audio booster pack.
## 2.3 WM5102 Audio Hub Codec for Audio Input and Output
The Wolfson audio card makes use of a WM5102 audio hub for analog input and output. The WM5102 features a low-power, high-performance audio codec.
Data is passed to and from the WM5102 via its I2S serial interface, and the device is configured by writing to its control registers via an I2C interface. In addition to a number of configurable filter and gain blocks, the WM5102 codec contains a programmable DSP. However, use of this proprietary DSP is beyond the scope of this book.
LINE IN (pink), LINE OUT (green), and combined MIC IN and HP OUT (black) connections are made available via three 3.5 mm jack sockets on the Wolfson audio card.
## 2.4 Programming Examples
The following examples illustrate analog input and output using either the TM4C123 LaunchPad and audio booster pack or the STM32F407 Discovery and Wolfson audio card. The program examples are available for either platform, although in most cases, only one platform is mentioned per example. A small number of example programs in this chapter concern programming the internal digital filters in the AIC3104 codec and are therefore applicable only to the Texas Instruments hardware platform. A small number of example programs concern use of the 12-bit DAC built in to the STM32F407 processor and are therefore applicable only to the STMicroelectronics hardware platform.
The example programs demonstrate some important concepts associated with analog-to-digital and digital-to-analog conversion, including sampling, reconstruction, and aliasing. In addition, they illustrate the use of polling-, interrupt-, and DMA-based i/o in order to implement real-time applications. Many of the concepts and techniques described in this chapter are revisited in subsequent chapters.
## 2.5 Real-Time Input and Output Using Polling, Interrupts, and Direct Memory Access (DMA)
Three basic forms of real-time i/o are demonstrated in the following examples. Polling- and interrupt-based i/o methods work on a sample-by-sample basis, and processing consists of executing a similar set of program statements at each sampling instant. DMA-based i/o deals with blocks, or frames, of input and output samples and is inherently more efficient in terms of computer processing requirements. Processing consists of executing a similar set of program statements after each DMA transfer. Block- or frame-based processing is closely linked to, but not restricted to, use with frequency-domain processing (using the FFT) as described in Chapter 5.
The following examples illustrate the use of the three different i/o mechanisms in order to implement a simple talk-through function. Throughout the rest of this book, use is made primarily of interrupt- and DMA-based methods. Compared to polling- and interrupt-based methods, there is a greater time delay between a signal entering the digital signal processing system and leaving it introduced by the DMA-based method. It is possible to make use of the DMA mechanism with a frame size of just one sample, but this rather defeats the purpose of using DMA-based i/o.
* * *
# Example 2.1 Basic Input and Output Using Polling (`tm4c123_loop_poll.c`).
* * *
* * *
# Listing 2.1 Program `tm4c123_loop_poll.c`
_// tm4c123_loop_poll.c_
**#include** "tm4c123_aic3104_init.h"
**void** SSI_interrupt_routine( **void** ){ **while** (1){}}
**int** main( **void** )
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_MIC_IN,
IO_METHOD_POLL,
PGA_GAIN_6_DB);
**while** (1)
{
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
sample_data.bit32 = ((int16_t)(input_left));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(input_right));
SSIDataPut(SSI0_BASE,sample_data.bit32);
}
}
* * *
The C language source file for program, `tm4c123_loop_poll.c`, which simply copies input samples read from the AIC3104 codec ADC to the AIC3104 codec DAC as output samples, is shown in Listing 2.1. Effectively, the MIC IN input socket is connected straight through to the LINE OUT and HP OUT output sockets on the audio booster pack via the AIC3104 codec and the TM4C123 processor. Function `tm4c123_aic3104_init()`, called by program `tm4c123_loop_poll.c`, is defined in support file `tm4c123_aic3104_init.c`. In this way, the C source file `tm4c123_loop_poll.c` is kept as short as possible and potentially distracting low-level detail is hidden. The implementation details of function `tm4c123_aic3104_init()` and other functions defined in `tm4c123_aic3104_init.c` need not be studied in detail in order to use the examples presented in this book.
### 2.5.1 I2S Emulation on the TM4C123
The TM4C123 processor does not feature an I2S interface. Instead, two synchronous serial interface (SSI) interfaces, SSI0 and SSI1, are used to emulate a bidirectional stereo I2S interface and to pass audio data to and from the AIC3104 codec. One SSI interface handles the left channel and the other handles the right channel. Details of the I2S emulation are described in application note SPMA042 [3].
### 2.5.2 Program Operation
Following the call to function `tm4c123_aic3104_init()`, program `tm4c123_loop_poll.c` enters an endless while loop and repeatedly copies left and right channel input sample values into variables `input_left` and `input_right`, using function `SSIDataGet()`, before writing these sample values to the AIC3104 DAC, using function `SSIDataPut()`. Function `SSIDataGet()` waits until there is data in the receive FIFO of the specified SSI peripheral, `SSI0_BASE` or `SSI1_BASE`, and function `SSIDataPut()` waits until there is space available in the transmit FIFO of the specified SSI peripheral. In this way, the real-time operationof the program is controlled by the timing of the I2S interface, which, in turn, is determined by the AIC3104 codec (acting as I2S master). Functions `SSIDataGet()` and `SSIDataPut()` are defined in the TM4C123 device family pack (DFP) installed as part of the _MDK-ARM_ development environment. Although the AIC3104 is configured to use 16-bit sample values, function `SSIDataGet()` returns a 32-bit value and function `SSIDataPut()` is passed a 32-bit value.
Function `SSI_interrupt_routine()` is not used by program `tm4c123_loop_poll.c` but has been defined here as a trap for unexpected SSI peripheral interrupts.
In this simple example, it is not strictly necessary to convert the 16-bit sample values read from the AIC3104 ADC by function `SSIDataGet()` into 32-bit floating-point values. However, in subsequent program examples, DSP algorithms are implemented using floating-point arithmetic and input sample values are converted into type `float32_t`. Processing of the floating-point sample values could be implemented by adding program statements between
input_right = (float32_t)(sample_data.bit16[0]);
and
sample_data.bit32 = ((int16_t)(input_left));
### 2.5.3 Running the Program
Connect a microphone to the (pink) MIC IN socket on the audio booster card and headphones to the (green) HP OUT socket. Run the program and verify that the input to the microphone can be heard in the headphones.
### 2.5.4 Changing the Input Connection to LINE IN
Change the program statement
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_MIC_IN,
IO_METHOD_POLL,
PGA_GAIN_6_DB);
to read
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_LINE_IN,
IO_METHOD_POLL,
PGA_GAIN_6_DB);
Rebuild the project and run the program again using a signal from a sound card, a signal generator, or an MP3 player connected to the (blue) LINE IN socket as input.
### 2.5.5 Changing the Sampling Frequency
Change the sampling frequency used by passing parameter value `FS_8000_HZ` rather than `FS_48000_HZ` to the codec initialization function, that is, by changing the program statement
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_LINE_IN,
IO_METHOD_POLL,
PGA_GAIN_6_DB);
to read
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_POLL,
PGA_GAIN_6_DB);
Rebuild the project and run the program again. Signals passed through the system should sound less bright than previously due to the lower sampling rate and correspondingly reduced system bandwidth.
Valid parameter values (constants) that may be passed to function `tm4c123_AIC3104_init()` are
FS_48000_HZ
FS_44100_HZ
FS_32000_HZ
FS_24000_HZ
FS_22050_HZ
FS_16000_HZ
FS_11025_HZ
FS_8000_HZ
which set the sampling rate,
IO_METHOD_POLL
IO_METHOD_INTR
IO_METHOD_DMA
which set the i/o method,
AIC3104_MIC_IN
AIC3104_LINE_IN
which set the input connection used, and
PGA_GAIN_0_DB
PGA_GAIN_1_DB
PGA_GAIN_2_DB
PGA_GAIN_3_DB
PGA_GAIN_4_DB
PGA_GAIN_5_DB
PGA_GAIN_6_DB
PGA_GAIN_7_DB
PGA_GAIN_8_DB
PGA_GAIN_9_DB
PGA_GAIN_10_DB
PGA_GAIN_11_DB
PGA_GAIN_12_DB
which set the gain of the PGA that precedes the ADC (shown in Figure 2.2). Parameter value `PGA_GAIN_6_DB` is used by default in order to compensate for the potential divider circuits between the LINE IN socket on the audio booster pack and LINEIN_L and LINEIN_R on the AIC3104 (as shown in Figure 2.4).
* * *
# Example 2.2
**Basic Input and Output Using Polling (`stm32f4_loop_poll.c`).**
* * *
Program `stm32f4_loop_poll.c`, shown in Listing 2.4, is functionally equivalent to program `tm4c123_loop_poll.c` but runs on the STM32F407 Discovery. Full duplex I2S communication between the WM5102 codec and the STM32F407 processor is implemented on the STM32F407 using two I2S instances SPI/I2S2 and I2S2_ext. SPI/I2S2 is configured as a receiver and I2S2_ext as a transmitter. The WM5102 codec, which operates in master mode, generates the I2S word and bit clock signals (WCLK and BCLK), and the STM32F407 I2S peripheral operates in slave mode.
Following the call to function `stm32f4_wm5102_init()`, program `stm32f4_loop_poll.c` enters an endless while loop.
Status flag `SPI_I2S_FLAG_RXNE` in SPI/I2S2 is repeatedly tested using function `SPI_I2S_GetFlagStatus()` until it is set, indicating that the SPI/I2S2 receive buffer is not empty. Then, status flag `I2S_FLAG_CHSIDE` is tested. This indicates whether the data received corresponds to the left or the right channel.
If the value of `I2S_FLAG_CHSIDE` indicates that a left channel sample value has been received, function `SPI_I2S_ReceiveData()` is used to read that sample from SPI/I2S2 into the `int16_tvariable` `input_left`, and after waiting for status flag `SPI_I2S_FLAG_TXE` to be set, the value of variable `input_left` is written to I2S2_ext.
If the value of `I2S_FLAG_CHSIDE` indicates that a right channel sample value has been received, function `SPI_I2S_ReceiveData()` is used to read that sample from SPI/I2S2 into the `int16_t` variable `input_right`, and after waiting for status flag `SPI_I2S_FLAG_TXE` to be set, the value of variable `input_right` is written to I2S2_ext.
The endless while loop then returns to testing status flag `SPI_I2S_FLAG_RXNE` in SPI/I2S2. In this way, the real-time operation of the program is controlled by the timing of the I2S interface, which, in turn, is determined by the WM5102 codec (acting as I2S master).
In this simple talk-through example, it is not strictly necessary to test whether received samples correspond to the left or right channel. However, the program has been written so that processing of the signals on either or both channels could easily be added between, for example, program statements.
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
and
while(SPI_I2S_GetFlagStatus(I2Sxext,
* * *
# Listing 2.2 Program `stm32f4_loop_poll.c`
_// stm32f4_loop_poll.c_
**#include** "stm32f4_wm5102_init.h"
**int** main( **void** )
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
stm32_wm5102_init(FS_48000_HZ,
WM5102_DMIC_IN,
IO_METHOD_POLL);
**while** (1)
{
**while** (SPI_I2S_GetFlagStatus(I2Sx,
SPI_I2S_FLAG_RXNE ) != SET){}
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
left_out_sample = left_in_sample;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = right_in_sample;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
}
* * *
Valid parameter values (constants) that may be passed to function `stm32_wm5102_init()` are
FS_48000_HZ
FS_44100_HZ
FS_32000_HZ
FS_24000_HZ
FS_22050_HZ
FS_16000_HZ
FS_11025_HZ
FS_8000_HZ
which set the sampling rate,
IO_METHOD_POLL
IO_METHOD_INTR
IO_METHOD_DMA
which set the i/o method, and
WM5102_MIC_IN
WM5102_DMIC_IN
WM5102_LINE_IN
which set the input connection used.
### 2.5.6 Using the Digital MEMS Microphone on the Wolfson Audio Card
Unlike the audio booster pack for the TM4C123 LaunchPad, which has separate MIC IN and HP OUT sockets, the Wolfson audio card has a single HEADSET socket (shown in Figure 2.5) that may be used for a combined microphone and earphone headset, conventional stereo headphones, an electret microphone that uses a four-pole (TRRS) 3.5 mm jack plug. In addition, the Wolfson audio card features high-quality stereo digital MEMS microphones that may be selected by passing parameter value `WM5102_DMIC_IN` to function `stm32_wm5102_init()`.
**Figure 2.5** Analog input and output connections on the Wolfson audio card.
### 2.5.7 Running the Program
As provided, program `stm32f4_loop_poll.c` accepts input from the digital MEMS microphones on the audio card and routes this to the (green) LINE OUT and (black) HEADSET sockets. If you want to use a sound card, signal generator, or MP3 player to supply a line-level input signal to the (pink) LINE IN socket, change program statement.
stm32f4_wm5102_init(FS_48000_HZ,
WM5102_DMIC_IN,
IO_METHOD_INTR);
to read
stm32f4_wm5102_init(FS_48000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
Polling-based i/o is not computationally efficient and is used in very few of the example programs in this book.
* * *
# Example 2.3
**Basic Input and Output Using Interrupts (`tm4c123_loop_intr.c`).**
* * *
Viewed in terms of analog input and output signals, program `tm4c123_loop_intr.c`, shown in Listing 2.6, is functionally equivalent to program `tm4c123_loop_poll.c` but uses interrupt-based i/o.
* * *
# Listing 2.3 Program `tm4c123_loop_intr.c`
_// tm4c123_loop_intr.c_
**#include** "tm4c123_aic3104_init.h"
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
sample_data.bit32 = ((int16_t)(input_left));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(input_right));
SSIDataPut(SSI0_BASE,sample_data.bit32);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_MIC_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
This simple program is important because many of the example programs in this book use interrupt-based i/o and are structured similarly. Instead of simply copying the sequence of sample values read from the ADC to the DAC, a digital filtering operation could be performed each time a new input sample is received, that is, a sample-by-sample processing algorithm could be inserted between the program statements.
input_right = (float32_t)(sample_dat.bit16[0]);
and
sample_dat.bit16[0] = (int16_t)(input_left);
For this reason, it is worth taking time to ensure that you understand how program `tm4c123_loop_intr.c` works.
Strictly speaking, it is not good practice to carry out digital signal processing operations within a hardware interrupt service routine, for example, function `SSI_interrupt_routine()`. However, in the program examples in this book, there are no other tasks being carried out by the processor, and, in most cases, the algorithms being demonstrated have been placed within the interrupt service routine function(s).
In function `main()`, parameter value `IO_METHOD_INTR` is passed to initialization function `tm4c123_aic3104_init()`. This selects the use, by the program, of interrupt-based i/o.
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_MIC_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
Following initialization, function `main()` enters an endless, and empty, while loop, effectively doing nothing but waiting for interrupts.
SSI0 receive FIFO interrupts (`SSI_RXFF`), which occur at the sampling rate (48 kHz), are handled by interrupt service routine function `SSI_interrupt_routine()`. In this function, left- and right-channel 16-bit sample values are read from the SSI1 and SSI0 receive FIFOs, respectively. These are converted into `float32_t` values `input_left` and `input_right`. Strictly speaking, type conversions are unnecessary in this simple talk-through program since the values of `input_left` and `input_right` are subsequently converted back to type `int16_t` and written to SSI1 and SSI0 transmit FIFOs, respectively.
### 2.5.8 Running the Program
As provided, program `tm4c123_loop_intr.c` accepts input from the (pink) MIC IN socket on the audio booster card and routes this to both the (black) LINE OUT and (green) HP OUT sockets. If you want to use a sound card, signal generator or MP3 player to supply a line-level input signal, change program statement.
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_MIC_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
to read
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
GPIO pin PE2 is set high at the start, and reset low near the end, of function `SSI_interrupt_routine()`. This signal is accessible via the J3 connector on the TM4C123 LaunchPad.
* * *
# Example 2.4
**Basic Input and Output Using Interrupts (`stm32f4_loop_intr.c`).**
* * *
Program `stm32f4_loop_intr.c` is shown in Listing 2.8. In terms of analog input and output signals, it is functionally equivalent to program `tm4c123_loop_intr.c` but is written for the STM32F407 Discovery and Wolfson audio card. Because the WM5012 and AIC3104 codecs differ and because, unlike the TM4C123 processor, the STM32F407 features an I2S interface, there are subtle differences between programs `stm32f4_loop_intr.c` and `tm4c123_loop_intr.c`.
* * *
# Listing 2.4 Program `stm32f4_loop_intr.c`
_// stm32f4_loop_intr.c_
**#include** "stm32f4_wm5102_init.h"
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
left_out_sample = left_in_sample;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = right_in_sample;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
GPIO_ToggleBits(GPIOD, GPIO_Pin_15);
}
**int** main( **void** )
{
stm32_wm5102_init(FS_48000_HZ,
WM5102_DMIC_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
Following a call to initialization function `stm32_wm5102_init()`, function `main()` enters an endless, and empty, while loop, effectively doing nothing but waiting for interrupts.
The I2S peripheral in the STM32F407 processor is configured for full-duplex slave mode, using PCM standard audio protocol, with 16-bit data packed into 32-bit frames. Receive buffer not empty (RXNE) interrupts are generated by I2S instance SPI/I2S2 when data is received from the WM5102 codec. These interrupts, which occur at the sampling rate (48 kHz) for _both_ left- and right-channel samples, are handled by function `SPI2_IRQHandler()`. This tests the status flag `CHSIDE` in order to determine whether a left- or right-channel sample has been received. If a left-channel sample has been received (`CHSIDE 1`), then that value is read from SPI/I2S2 into the variable `input_left` by function `SPI_I2S_ReceiveData(I2Sx)`. It is then copied to variable `output_left` and written to I2S2_ext using function `SPI_I2S_SendData()`. Finally, GPIO pin PD15 is toggled. This pin is accessible via J2 on the STM32F407 Discovery and may be monitored using an oscilloscope. On the STM32F407 Discovery, GPIO pin PD15 drives a blue LED, and, hence, its duty cycle is discernible from the apparent brightness of the blue LED. In this program example, since interrupts occur twice per sampling period (once each for left and right channels), GPIO pin PD15 should output a 48-kHz square wave and the blue LED should emit light with medium intensity.
* * *
# Example 2.5
**Basic Input and Output Using DMA (`tm4c123_loop_dma.c`).**
* * *
In terms of analog input and output signals, program `tm4c123_loop_dma.c`, shown in Listing 2.10, is functionally equivalent to the preceding program examples but makes use of direct memory access (DMA). DMA-based i/o moves blocks or frames of data (samples) between codec and processor memory without CPU involvement, allowing the CPU to carry out other tasks at the same time, and is therefore more computationally efficient than polling- or interrupt-based i/o methods.
* * *
# Listing 2.5 Program `tm4c123_loop_dma.c`
_// tm4c123_loop_dma.c_
**#include** "tm4c123_aic3104_init.h"
**extern** int16_t LpingIN[BUFSIZE], LpingOUT[BUFSIZE];
**extern** int16_t LpongIN[BUFSIZE], LpongOUT[BUFSIZE];
**extern** int16_t RpingIN[BUFSIZE], RpingOUT[BUFSIZE];
**extern** int16_t RpongIN[BUFSIZE], RpongOUT[BUFSIZE];
**extern** int16_t Lprocbuffer, Rprocbuffer;
**extern volatile** int16_t LTxcomplete, LRxcomplete;
**extern volatile** int16_t RTxcomplete, RRxcomplete;
**void** Lprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Lprocbuffer PING)
{ inBuf = LpingIN; outBuf = LpingOUT; }
**if** (Lprocbuffer PONG)
{ inBuf = LpongIN; outBuf = LpongOUT; }
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = *inBuf++;
}
LTxcomplete = 0;
LRxcomplete = 0;
**return** ;
}
**void** Rprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Rprocbuffer PING)
{ inBuf = RpingIN; outBuf = RpingOUT; }
**if** (Rprocbuffer PONG)
{ inBuf = RpongIN; outBuf = RpongOUT; }
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = *inBuf++;
}
RTxcomplete = 0;
RRxcomplete = 0;
**return** ;
}
**void** SSI_interrupt_routine( **void** ){ **while** (1){}}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_LINE_IN,
IO_METHOD_DMA,
PGA_GAIN_6_DB);
**while** (1)
{
**while** ((!RTxcomplete)|(!RRxcomplete));
Rprocess_buffer();
**while** ((!LTxcomplete)|(!LRxcomplete));
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
Lprocess_buffer();
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
}}
* * *
### 2.5.9 DMA in the TM4C123 Processor
The TM4C123 DMA controller has 32 channels, each of which may be assigned to one of up to five different peripherals (each peripheral device in the TM4C123 processor is associated with a specific DMA controller channel). Each channel can operate in basic, ping-pong, or scatter-gather mode. DMA transfers are made up of up to 1024 × 8-, 16-, or 32-bit elements. An I2S interface is emulated on the TM4C123 using two separate SSI peripherals (SSI0 and SSI1), SSI1 for the left channel and SSI0 for the right channel. The SSI0 peripheral is set up to trigger on the positive edge of the I2S frame clock, WCLK (generated by the AIC3104 codec), and the SSI1 peripheral is set up to trigger on the negative edge of the I2S frame clock (strictly speaking, the positive edge of the inverted I2S frame clock). The AIC3104 codec on the audio booster pack acts as I2S master and supplies frame and bit clock signals (WCLK and BCLK).
DMA channel control is implemented using a table (aligned on a 1024-byte boundary in memory) of control structures. Associated with each channel are two control structures (primary (PRI) and alternative (ALT)) and both of these are used in ping-pong mode.
Each control structure includes a source address pointer (SRC), a destination address pointer (DST), and a control word specifying SRC and DST data element sizes, SRC and DST address increments, the total number of elements to transfer, and the transfer mode (basic, ping-pong, or scatter-gather). The SRC and DST address pointers in the control table must be initialized before a DMA transfer starts, and according to the SRC and DST address increments, they are updated as the transfer progresses.
In ping-pong mode, as soon as one DMA transfer (PRI or ALT) has been completed, another transfer (ALT or PRI) on the same channel starts. When a DMA transfer is completed, an interrupt may be generated and this signals an opportunity, in ping-pong mode, not only to process the block of input data most recently transferred, but also to reinitialize the currently inactive (PRI or ALT) control structure.
In the example programs in this book, I2S protocol bidirectional stereo audio data transfer makes use of four unidirectional DMA channels, associated with SSI0TX, SSI0RX, SSI1TX, and SSI1RX.
Transfers specified by the SSI0TX primary (PRI) control structure (from array `RpingOUT` to SSI0 transmit FIFO) alternate with those specified by the SSI0TX alternative (ALT) control structure (from array `RpongOUT` to SSI0 transmit FIFO). Each time either transfer is completed, an interrupt is generated and handled by function `SSI0IntHandler()`. Following completion of an SSI0TX PRI DMA transfer (from array `RpingOUT` to SSI0), the SSI0 interrupt service routine must reinitialize the SSI0TX PRI control structure (principally by resetting SRC and DST addresses). At that point in time, the SSI0TX ALT DMA transfer (from array `RpongOUT` to SSI0) should be in progress.
SSI0RX DMA transfers (PRI from SSI0 receive FIFO to array `RpingIN` and ALT from SSI0 receive FIFO to array `RLpongIN`) take place in parallel with the SSI0TX transfers, and completion of either of these transfers generates interrupts also handled by `SSI0IntHandler()`.
Interrupt service routine `SSI0IntHandler()` must therefore determine which of four possible different DMA transfers has completed and reinitialize the corresponding control structure. This is summarized in Table 2.1. Function `SSI0IntHandler()` is shown in Listing 2.11. Its functions are
1. Determine which one of four possible DMA transfers has completed (and generated an SSI0IRQ interrupt).
2. Reinitialize the corresponding control structure resetting the SRC or DST (memory) address pointers.
3. Set the value of flag `RprocBuffer` to either `PING` or `PONG`.
4. If the completed transfer was from memory to the SSI0 transmit FIFO, set flag `RTxcomplete`.
5. If the completed transfer was from the SSI0 receive FIFO to memory, set flag `RRxcomplete`.
**Table 2.1** Summary of DMA Control Structures Used and Flags Set in Interrupt Service Routines `SSI0IntHandler()` and `SSI1IntHandler()` in Program `tm4c123_loop_dma.c`
Channel | Option | SRC | DST | Flags Set
---|---|---|---|---
SSI0RX | PRI | SSI0RX | `RpingIN` | `RRxcomplete`
| | | | `Rprocbuffer = PING`
SSI0RX | ALT | SSI0RX | `RpongIN` | `RRxcomplete`
| | | | `Rprocbuffer = PONG`
SSI0TX | PRI | `RpingOUT` | SSI0TX | `RTxcomplete`
| | | | `Rprocbuffer = PING`
SSI0TX | ALT | `RpongOUT` | SSI0TX | `RTxcomplete`
| | | | `Rprocbuffer = PONG`
SSI1RX | PRI | SSI1RX | `LpingIN` | `LRxcomplete`
| | | | `Lprocbuffer = PING`
SSI1RX | ALT | SSI1RX | `LpongIN` | `LRxcomplete`
| | | | `Lprocbuffer = PONG`
SSI1TX | PRI | `LpingOUT` | SSI1TX | `LTxcomplete`
| | | | `Lprocbuffer = PING`
SSI1TX | ALT | `LpongOUT` | SSI1TX | `LTxcomplete`
| | | | `Lprocbuffer = PONG`
In parallel with these DMA transfers, a corresponding set of DMA transfers take place between memory and the SSI1 peripheral. These deal with left channel audio data.
In function `main()`, an endless `while()` loop waits until both `RTxcomplete` and `RRxcomplete` are set before calling function `RprocessBuffer()` This function uses the value of `RprocBuffer` to decide whether to process the contents of array `RpingIN` or `RpongIN`. It also resets flags `RTxcomplete` and `RRxcomplete`.
Function `main()` then waits until both `LTxcomplete` and `LRxcomplete` are set before calling function `LprocessBuffer()`.
Interrupts generated on completion of transfers are handled by the interrupt service routines associated with the peripheral involved, that is, either `SSI0IntHandler()` or `SSI1IntHandler()`, and these are defined in file `tm4c123_aic3104_init.c`.
Each DMA transfer is of `BUFSIZE` 16-bit sample values, corresponding to `BUFSIZE sampling` instants. The value of the constant `BUFSIZE` is defined in header file `tm4c123_aic3104_init.h`. Function `SSI_interrupt_routine()` is not used by program `tm4c123_loop_dma.c` but has been defined here as a trap for unexpected SSI peripheral interrupts.
* * *
# Listing 2.6 Function `SSI0IntHandler()`, defined in file `tm4c123_aic3104_init.c`
**void** SSI0IntHandler( **void** )
{
**unsigned long** ulModeTXPRI,ulModeTXALT;
**unsigned long** ulModeRXPRI,ulModeRXALT;
ulModeTXPRI = ROM_uDMAChannelModeGet(UDMA_CHANNEL_SSI0TX |
UDMA_PRI_SELECT);
ulModeTXALT = ROM_uDMAChannelModeGet(UDMA_CHANNEL_SSI0TX |
UDMA_ALT_SELECT);
ulModeRXPRI = ROM_uDMAChannelModeGet(UDMA_CHANNEL_SSI0RX |
UDMA_PRI_SELECT);
ulModeRXALT = ROM_uDMAChannelModeGet(UDMA_CHANNEL_SSI0RX |
UDMA_ALT_SELECT);
**if** (ulModeTXPRI UDMA_MODE_STOP)
{
Rprocbuffer = PING;
ROM_uDMAChannelTransferSet(UDMA_CHANNEL_SSI0TX |
UDMA_PRI_SELECT,
UDMA_MODE_PINGPONG,
RpingOUT,
( **void** *)(SSI0_BASE + 0x008),
BUFSIZE);
RTxcomplete = 1;
{
**if** (ulModeTXALT UDMA_MODE_STOP)
{
Rprocbuffer = PONG;
ROM_uDMAChannelTransferSet(UDMA_CHANNEL_SSI0TX |
UDMA_ALT_SELECT,
UDMA_MODE_PINGPONG,
RpongOUT,
( **void** *)(SSI0_BASE + 0x008),
BUFSIZE);
RTxcomplete = 1;
}
**if** (ulModeRXPRI UDMA_MODE_STOP)
{
Rprocbuffer = PING;
ROM_uDMAChannelTransferSet(UDMA_CHANNEL_SSI0RX |
UDMA_PRI_SELECT,
UDMA_MODE_PINGPONG,
( **void** *)(SSI0_BASE + 0x008),
RpingIN,
BUFSIZE);
RRxcomplete = 1;
}
**if** (ulModeRXALT UDMA_MODE_STOP)
{
Rprocbuffer = PONG;
ROM_uDMAChannelTransferSet(UDMA_CHANNEL_SSI0RX |
UDMA_ALT_SELECT,
UDMA_MODE_PINGPONG,
( **void** *)(SSI0_BASE + 0x008),
RpongIN,
BUFSIZE);
RRxcomplete = 1;
}
}
* * *
### 2.5.10 Running the Program
Build and run program `tm4c123_loop_dma.c` and verify its operation. As supplied, the program uses the (blue) LINE IN connection for input. If you wish to use a microphone connected to the (pink) MIC IN connection as an input device, you will have to change the parameters passed to function `tm4c123_aic3104_init()` to
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_MIC_IN,
IO_METHOD_DMA
PGA_GAIN_6_DB);
### 2.5.11 Monitoring Program Execution
GPIO pin PE2 is set just before, and reset just after, the call to function `Lprocessbuffer`. Hence, the signal on that pin is a rectangular pulse, the duration of which indicates the time taken to execute function `Lprocessbuffer`. In this example, the duration of the pulse is very short since no significant processing takes place in the function. The rectangular pulse is repeated with a period equal to the time between consecutive DMA transfers, that is, `BUFSIZE` sampling periods. An example of the pulse output on GPIO pin PE2 by program `tm4c123_loop_dma.c` is shown in Figure 2.6. In this case, the value of the constant `BUFSIZE` is 256, the sampling rate is 48 kHz, and hence, the time between consecutive pulses is equal to ms.
**Figure 2.6** Pulse output on GPIO pin PE2 by program `tm4c123_loop_dma.c`.
### 2.5.12 Measuring the Delay Introduced by DMA-Based I/O
The extra delay between analog input and output, of `2*BUFSIZE` sampling periods, introduced by DMA-based i/o using ping-pong buffering as implemented on the TM4C123, may be measured using a signal generator and oscilloscope.
Connect the signal generator output to both the left channel of the (blue) LINE IN socket on the audio booster pack and one channel of the oscilloscope, and connect an oscilloscope probe from another channel on the oscilloscope to the left channel scope hook (TP2) on the audio booster pack. Scope selector jumper J6 should be fitted. Figure 2.7 shows a delay of approximately 11.7 ms introduced by the program to a rectangular pulse of duration 1.0 ms. In contrast, program `tm4c123_loop_intr.c` introduces a delay of approximately 1.0 ms, as shown in Figure 2.8. The additional delay introduced by the use of DMA-based i/o is equal to approximately 10.7 ms. At a sampling rate of 48 kHz, ping-pong mode DMA transfers of `BUFSIZE = 256` samples correspond to a delay of 2 * 256/48,000 = 10.67 ms. The value of constant `BUFSIZE` is defined in file `tm4c123_aic3104_init.h`.
**Figure 2.7** Delay introduced by use of DMA-based i/o in program `tm4c123_loop_dma.c`. Upper trace shows rectangular pulse of duration 1 ms applied to LINE IN, lower trace shows output from LINE OUT. `BUFSIZE = 256`, sampling rate 48 kHz.
**Figure 2.8** Delay introduced by use of interrupt-based i/o in program `tm4c123_loop_intr.c`. Upper trace shows rectangular pulse of duration 1 ms applied to LINE IN, lower trace shows output from LINE OUT. Sampling rate 48 kHz.
* * *
# Example 2.6
**Basic Input and Output Using DMA (`stm32f4_loop_dma.c`).**
* * *
ARM Cortex-M4 processors from different manufacturers implement DMA slightly differently (although the underlying principles are similar). Program `stm32f4_loop_dma.c`, shown in Listing 2.13, is functionally equivalent to program `tm4c123_loop_dma.c` but differs slightly because of the differences between the DMA peripherals in the TM4C123 and STM32F407 processors.
* * *
# Listing 2.7 Program `stm32f4_loop_dma.c`
_// stm32f4_loop_dma.c_
**#include** "stm32f4_wm5102_init.h"
**extern** uint16_t pingIN[BUFSIZE], pingOUT[BUFSIZE];
**extern** uint16_t pongIN[BUFSIZE], pongOUT[BUFSIZE];
**int** rx_proc_buffer, tx_proc_buffer;
**volatile int** RX_buffer_full = 0;
**volatile int** TX_buffer_empty = 0;
**void** DMA1_Stream3_IRQHandler()
{
**if** (DMA_GetITStatus(DMA1_Stream3,DMA_IT_TCIF3))
{
DMA_ClearITPendingBit(DMA1_Stream3,DMA_IT_TCIF3);
**if** (DMA_GetCurrentMemoryTarget(DMA1_Stream3))
rx_proc_buffer = PING;
**else**
rx_proc_buffer = PONG;
RX_buffer_full = 1;
}
}
**void** DMA1_Stream4_IRQHandler()
{
**if** (DMA_GetITStatus(DMA1_Stream4,DMA_IT_TCIF4))
{
DMA_ClearITPendingBit(DMA1_Stream4,DMA_IT_TCIF4);
**if** (DMA_GetCurrentMemoryTarget(DMA1_Stream4))
tx_proc_buffer = PING;
**else**
tx_proc_buffer = PONG;
TX_buffer_empty = 1;
}
}
**void** process_buffer()
{
uint16_t *rxbuf, *txbuf;
int16_t i;
**if** (rx_proc_buffer PING)
rxbuf = pingIN;
**else**
rxbuf = pongIN;
**if** (tx_proc_buffer PING)
txbuf = pingOUT;
**else**
txbuf = pongOUT;
**for** (i=0 ; i<(BUFSIZE/2) ; i++)
{
*txbuf++ = *rxbuf++;
*txbuf++ = *rxbuf++;
}
TX_buffer_empty = 0;
RX_buffer_full = 0;
}
**int** main( **void** )
{
stm32_wm5102_init(FS_48000_HZ,
WM5102_LINE_IN,
IO_METHOD_DMA);
**while** (1)
{
**while** (!(RX_buffer_full && TX_buffer_empty)){}
GPIO_SetBits(GPIOD, GPIO_Pin_15);
process_buffer();
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
}
}
* * *
### 2.5.13 DMA in the STM32F407 Processor
DMA in the STM32F407 processor is organized into unidirectional streams. Two DMA controllers have eight streams each, and streams are subdivided into eight channels. Individual channels are associated with specific peripheral devices. Bidirectional I2S on the STM32F407 is implemented using the SPI/I2S2 and I2Sext peripheral devices. Program `stm32f4_loop_dma.c` makes use of the inbuilt ping-pong mode of buffering possible on the STM32F407. DMA-based i/o is selected by passing parameter value `IO_METHOD_DMA` to function `stm32_wm5102_init()`.
In function `stm32_wm5102_init()`, stream 3 channel #0 is configured to make DMA transfers between the I2S peripheral and input buffers (arrays) in memory (alternately `pingIN` and `pongIN`). It generates an interrupt when a transfer of `BUFSIZE` 16-bit samples has completed. (Those 16-bit samples correspond alternately to L and R audio channels and so a transfer of `BUFSIZE` samples corresponds to `BUFSIZE/2` sampling instants.)
Stream 4 channel #2 is configured to make DMA transfers between output buffers in memory (alternately `pingOUT` and `pongOUT`) and the I2S peripheral. It too generates an interrupt when a transfer of `BUFSIZE` 16-bit samples has completed. (Those 16-bit samples correspond alternately to L and R audio channels and so a transfer of `BUFSIZE` samples corresponds to `BUFSIZE/2` sampling instants.) Two separate interrupt service routines are used; one for each of the aforementioned DMA processes. The actions carried out in these routines are simply to assign to variables `rx_proc_buffer` and `tx_proc_buffer` the values `PING` or `PONG` and to set flags `RX_buffer_full` and `TX_buffer_empty`. These variables are used in function `process_buffer()`.
Switching between buffers `pingIN`, `pongIN`, `pingOUT`, and `pongOUT` is handled automatically by the STM32F4's DMA mechanism. If, for example, `rx_proc_buffer` is equal to `PING`, this indicates that the most recently completed stream 3 DMA transfer has filled buffer `pingIN` and this data is available to be processed. If `tx_proc_buffer` is equal to `PING`, this indicates that the most recently completed stream 4 DMA transfer has written the contents of buffer `pingOUT` to the I2S peripheral and this buffer is available to be filled with new data.
Function `main()` simply waits until both `RX_buffer_full` and `TX_buffer_empty` flags are set, that is, until both DMA transfers have completed, before calling function `process_buffer()`.
In program `stm32f4_loop_dma.c`, function `process_buffer()` simply copies the contents of the most recently filled input buffer (`pingIN` or `pongIN`) to the most recently emptied output buffer (`pingOUT` or `pongOUT`), according to the values of variables `rx_proc_buffer` and `tx_proc_buffer`.
Frame-based processing may be carried out in function `process_buffer()` using the contents of the most recently filled input buffer as input and writing output sample values to the most recently emptied output buffer. DMA transfers will complete, and function `proc_buffer()` will be called, every `BUFSIZE/2` sampling instants and therefore any processing must be completed within `BUFSIZE/(2*fs)` seconds (or, more strictly speaking, before the next DMA transfer completion).
### 2.5.14 Running the Program
Run program `stm32f4_loop_dma.c` and verify its operation using a signal source and oscilloscope or headphones. As supplied, the program reads input from the (green) LINE IN socket on the audio card and outputs to the (pink) LINE OUT and (black) HEADSET connections.
### 2.5.15 Measuring the Delay Introduced by DMA-Based I/O
The extra delay between analog input and output, of `BUFSIZE` sampling periods, introduced by DMA-based i/o as implemented on the STM32F407, may be measured using a signal generator and oscilloscope.
Connect the signal generator output to both the left channel of the (green) LINE IN socket on the Wolfson audio card and one channel of the oscilloscope, and connect another channel on the oscilloscope to the left channel of the (pink) LINE OUT socket on the Wolfson audio card. Figure 2.9 shows a delay of approximately 5.9 ms introduced by the program to a rectangular pulse of duration 1.0 ms. In contrast, program `stm32f4_loop_intr.c` introduces a delay of approximately 560 µs, as shown in Figure 2.10. The additional delay introduced by the use of DMA-based i/o is equal to approximately 5.3 ms. At a sampling rate of 48 kHz, ping-pong mode DMA transfers of `BUFSIZE = 256` samples (128 samples per channel) correspond to a delay of 256/48,000 = 5.33 ms. The value of constant `BUFSIZE` is defined in file `stm32f4_aic3104_init.h`.
**Figure 2.9** Delay introduced by use of DMA-based i/o in program `stm32f4_loop_dma.c`. Upper trace shows rectangular pulse of duration 1 ms applied to LINE IN, lower trace shows output from LINE OUT. `BUFSIZE = 256`, sampling rate 48 kHz.
**Figure 2.10** Delay introduced by use of interrupt-based i/o in program `stm32f4_loop_intr.c`. Upper trace shows rectangular pulse of duration 1 ms applied to LINE IN, lower trace shows output from LINE OUT. Sampling rate 48 kHz.
* * *
# Example 2.7
**Modifying Program`tm4c123_loop_intr.c` to create a delay (`tm4c123_delay_intr.c`).**
* * *
Some simple, yet striking, effects can be achieved simply by delaying the sample values as they pass from input to output. Program `tm4c123_delay_intr.c`, shown in Listing 2.15, demonstrates this.
* * *
# Listing 2.8 Program `tm4c123_delay_intr.c`
_// tm4c123_delay_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#define** BUFFER_SIZE 2000
float32_t buffer[BUFFER_SIZE];
int16_t buf_ptr = 0;
**void** SSI_interrupt_routine(void)
{
AIC3104_data_type sample_data;
float32_t input_left, input_right, delayed;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
delayed = buffer[buf_ptr] + input_left;
buffer[buf_ptr] = input_left;
buf_ptr = (buf_ptr+1)% BUFFER_SIZE;
sample_data.bit32 = ((int16_t)(delayed));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(0));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_MIC_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
A delay line is implemented using the array `buffer` to store samples as they are read from the ADC. Once the array is full, the program overwrites the oldest stored input sample with the current, or newest, input sample. Just prior to overwriting the oldest stored input sample in `buffer`, that sample value is retrieved, added to the current input sample, and written to the DAC. Figure 2.11 shows a block diagram representation of the operation of program `tm4c123_delay_intr.c` in which the block labeled represents a delay of seconds. The value of is equal to the number of samples stored in `buffer` multiplied by the sampling period. Run program `tm4c123_delay_intr.c`, using a microphone connected to the (pink) MIC IN socket on the audio booster pack as an input device.
**Figure 2.11** Block diagram representation of program `tm4c123_delay_intr.c`.
* * *
# Example 2.8
**Modifying Program`tm4c123_loop_intr.c` to create an echo (`tm4c123_echo_intr.c`).**
* * *
By feeding back a fraction of the output of the delay line to its input, a fading echo effect can be realized. Program `tm4c123_echo_intr.c`, shown in Listing 2.17 and represented in block diagram form in Figure 2.12, does this.
**Figure 2.12** Block diagram representation of program `tm4c123_echo_intr.c`.
* * *
# Listing 2.9 Program `tm4c123_echo_intr.c`
_// tm4c123_echo_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#define** BUFFER_SIZE 2000
**#define** GAIN 0.6f
float32_t buffer[BUFFER_SIZE];
int16_t buf_ptr = 0;
**void** SSI_interrupt_routine(void)
{
AIC3104_data_type sample_data;
float32_t input_left, input_right, delayed;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
delayed = buffer[buf_ptr];
buffer[buf_ptr] = input_left + delayed * GAIN;
buf_ptr = (buf_ptr+1) % BUFFER_SIZE;
sample_data.bit32 = ((int16_t)(delayed));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(0));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_MIC_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
The value of the constant `BUFFER_SIZE` in program `tm4c123_echo_intr.c` determines the number of samples stored in the array `buffer` and hence the duration of the delay implemented. The value of the constant `GAIN` determines the fraction of the output that is fed back into the delay line and hence the rate at which the echo effect fades away. Setting the value of `GAIN` equal to, or greater than, 1 will cause instability. Build and run this program. Experiment with different values of `GAIN` (between 0.0 and 1.0) and `BUFFER_SIZE` (between 100 and 8000). Source file `tm4c123_echo_intr.c` must be edited and the project rebuilt in order to make these changes.
* * *
# Example 2.9
**Modifying Program`tm4c123_loop_intr.c` to create a flanging effect (`tm4c123_flanger_intr.c`).**
* * *
Flanging is an audio effect used in recording studios (and live performances) that, depending on its parameter settings, can add a whooshing sound not unlike a jet aircraft passing overhead. It is a delay-based effect and can therefore be implemented as an extension of the previous two examples. The flanging effect is shown in block diagram form in Figure 2.13. The addition of a delayed and attenuated version of the input signal to itself creates a comb-like frequency response. If the frequency of the input signal is such that an integer multiple of its period is equal to the delay , adding the delayed input signal will cancel out the input signal and this corresponds to a notch in the frequency response. The notches in the magnitude frequency response will therefore be spaced at regular intervals in frequency equal to Hz with the first notch located at frequency Hz. If the length of the delay is varied slowly, then the positions of the notches in the magnitude frequency response will vary accordingly to produce the flanging effect. As implemented in program `tm4c123_flanger_intr.c` (Listing 2.19), the delay varies sinusoidally between 200 and 1800 µs at a frequency of 0.1 Hz. Applied to music containing significant high-frequency content (e.g., drum sounds), the characteristic "jet aircraft passing overhead" type sound can be heard. Increasing the rate of change of delay to, for example, 3 Hz gives an effect closer to that produced by a Leslie rotating speaker.
**Figure 2.13** Block diagram representation of program `tm4c123_flanger_intr.c`.
* * *
# Listing 2.10 Program `tm4c123_flanger_intr.c`
_// tm4c123_flanger_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#define** TS 0.000020833333f // _sampling rate 48 kHz_
**#define** PERIOD 10.0f // _period of delay modulation_
**#define** MEAN_DELAY 0.001f // _mean delay in seconds_
**#define** MODULATION_MAG 0.0008f // _delay modulation magnitude_
**#define** BUFFER_SIZE 2048
**#define** ALPHA 0.9f
uint16_t in_ptr = 0; // _pointers into buffers_
uint16_t out_ptr;
float32_t buffer[BUFFER_SIZE];
float32_t t = 0.0f;
float32_t Rxn, Lxn, Ryn, Lyn, delay_in_seconds;
uint16_t delay_in_samples;
float32_t theta;
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
Lxn = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
Rxn = (float32_t)(sample_data.bit16[0]);
buffer[in_ptr] = Lxn;
in_ptr = (in_ptr + 1)
t = t + TS;
theta = (float32_t)((2*PI/PERIOD)*t);
delay_in_seconds = MEAN_DELAY
+ MODULATION_MAG * arm_sin_f32(theta);
delay_in_samples = (uint16_t)(delay_in_seconds
* 48000.0);
out_ptr = (in_ptr + BUFFER_SIZE
- delay_in_samples) % BUFFER_SIZE;
Lyn = Lxn + buffer[out_ptr]*ALPHA;
sample_data.bit32 = ((int16_t)(Lyn));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(Lyn));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_48000_HZ,
AIC3104_MIC_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
If the delayed signal is subtracted from, rather than added to, the input signal, then the first notch in the magnitude frequency response will be located at 0 Hz, giving rise to a high-pass (very little bass response) effect overall. To subtract, rather than add, the delayed signal, change the statement in program `tm4c123_flanger_intr.c` that reads
Lyn = Lxn + buffer[out_ptr]*ALPHA;
to read
Lyn = Lxn - buffer[out_ptr]*ALPHA;
Figures 2.14 and 2.15 show experimentally measured examples of the instantaneous impulse and magnitude frequency responses of the flanger program for the two cases described. Details of how these results were obtained are given later in this chapter.
**Figure 2.14** (a) impulse response and (b) magnitude frequency response of flanger implemented using program `tm4c123_flanger_intr.c` at an instant when delay is equal to 104.2 µs. The notches in the magnitude frequency response are at frequencies 4800 and 14,400 Hz.
**Figure 2.15** (a) Impulse response and (b) magnitude frequency response of modified flanger implemented using program `tm4c123_flanger_intr.c` at an instant when delay is equal to 208.3 µs. The notches in the magnitude frequency response are at frequencies 0, 4800, 9600, 14,400, and 19,200 Hz.
The time-varying delay implemented by the flanger may be illustrated using program `tm4c123_flanger_dimpulse_intr.c` and an oscilloscope. In this program, input samples are generated within the program rather than being read from the ADC. The sequence of input samples used is one nonzero value followed by 2047 zero values, and this sequence is repeated periodically. The effect is to excite the flanger with a sequence of discrete-time impulses separated by 2048 sampling periods or 42.67 ms. The output from program `tm4c123_flanger_dimpulse_intr.c` comprises the input (which passes straight through) plus a delayed and attenuated version of the input. Figure 2.16 shows an example of the output from the program captured using a _Rigol DS1052E_ oscilloscope. The pulse in the centre of the screen corresponds to the input pulse and the pulse to the right corresponds to the delayed pulse. At the instant of capture shown in Figure 2.21, the delay is equal to approximately 400 µs. When the program is running, you should see the delay between the pulses varying slowly. The shape of the pulses in Figure 2.21 is explained in Example 2.31.
**Figure 2.16** Output waveform produced using program `tm4c123_flanger_dimpulse_intr.c` at an instant when delay is equal to approximately 400 µs.
The time-varying magnitude frequency response of the flanger is illustrated in Figure 2.17, which shows the output of program `tm4c123_flanger_intr.c`, modified so that the input signal is a pseudorandom binary sequence, displayed as a spectrogram (frequency vs. time) using _Goldwave_. The dark bands in the spectrogram correspond to the notches in the magnitude frequency responses. An effective alternative to pseudorandom noise as an input signal is to blow gently on the microphone.
**Figure 2.17** Spectrum and spectrogram of flanger output for pseudorandom noise input. In the spectrogram, the -axis represents time in seconds and the -axis represents frequency in Hz.
* * *
# Example 2.10
**Loop Program with Input Data Stored in a Buffer (`stm32f4_loop_buf_intr.c`).**
* * *
Program `stm32f4_loop_buf_intr.c`, shown in Listing 2.21, is similar to program `stm32f4_loop_intr.c` except that it implements circular buffers in arrays `lbuffer` and `rbuffer`, each containing the `BUFFER_SIZE` most recent input sample values on one or other channel. Consequently, it is possible to examine this data after halting the program.
* * *
# Listing 2.11 Program `stm32f4_loop_buf_intr.c`
_// stm32f4_loop_buf_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#define** BUFFER_SIZE 256
float32_t rbuffer[BUFFER_SIZE];
int16_t rbufptr = 0;
float32_t lbuffer[BUFFER_SIZE];
int16_t lbufptr = 0;
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
left_out_sample = left_in_sample;
lbuffer[lbufptr] = (float32_t)(left_in_sample);
lbufptr = (lbufptr+1)
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = right_in_sample;
rbuffer[rbufptr] = (float32_t)(right_in_sample);
rbufptr = (rbufptr+1) % BUFFER_SIZE;
while(SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
GPIO_ToggleBits(GPIOD, GPIO_Pin_15);
}
**int** main( **void** )
{
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
### 2.5.16 Running the Program
Build and run the program. Use a signal generator connected to the (pink) LINE IN socket on the Wolfson audio card to input a sinusoidal signal with a frequency between 100 and 3500 Hz. Halt the program after a short time and save the contents of the array `rbuffer` or `lbuffer` to a data file by typing
save <filename> <start address>, <start address + 0x400>
at the _Command_ line in the _MDK-ARM debugger_ , where `start address` is the address of array `rbuffer` or `lbuffer` (and which may be determined using _Watch_ and _Memory_ functions in the _MDK-ARM debugger_.
The contents of the data file can be plotted using MATLAB® function `stm32f4_logfft()`. Figure 2.18 shows an example of the contents of array `lbuffer` when the frequency of the input signal was 350 Hz. The discontinuity in the waveform at time ms corresponds to the value of the index `lbufptr` into the array when program execution was halted. Recall that array `lbuffer` is used as a circular buffer in which older sample values are overwritten continually by newer ones. Program `stm32f4_loop_buf_intr.c` is used again later in this chapter in order to highlight the characteristics of the codec's antialiasing filter.
**Figure 2.18** Sample values stored in array `lbuffer` by program `stm32f4_loop_buf_intr.c` plotted using MATLAB function `stm32f4_logftt()`. Input signal frequency was 350 Hz.
## 2.6 Real-Time Waveform Generation
The following examples are concerned with the generation of a variety of different analog output waveforms, including sinusoids of different frequencies, by writing different sequences of sample values to the DACs in the WM5102 and AIC3104 codecs. In this way, the detailed characteristics of the DACs are revealed and the concepts of sampling, reconstruction, and aliasing are illustrated. In addition, the use of the _Goldwave_ shareware application is introduced. This virtual instrument is a useful alternative to an oscilloscope or spectrum analyzer and is used again in later chapters.
* * *
# Example 2.11
**Sine Wave Generation Using a Lookup Table (`stm32f4_sine48_intr.c`).**
* * *
Program `stm32f4_sine48_intr.c`, shown in Listing 2.23, generates a sinusoidal output signal using interrupt-based i/o and a table lookup method (Figure 2.18). Its operation is as follows. A 48-point lookup table is initialized in the array `sine_table` such that the value of `sine_table[i]` is equal to
**2.1**
Array `sine_table` therefore contains 48 samples of exactly one cycle of a sinusoid. In this example, a sampling rate of 48 kHz is used, and therefore, interrupts will occur every 20.833 µs. Within interrupt service routine `SPI2_IRQHandler()`, the most important program statements are executed. Every 20.833 µs, a sample value read from the array `sine_table` is written to the DAC and the index variable `sine_ptr` is incremented to point to the next value in the array. If the incremented value of `sine_ptr` is greater than, or equal to, the number of sample values in the table (`LOOPLENGTH`), it is reset to zero. The 1 kHz frequency of the sinusoidal output signal corresponds to the 48 samples per cycle output at a rate of 48 kHz.
* * *
# Listing 2.12 Program `stm32f4_sine48_intr.c`
_// stm32f4_sine48_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#define** LOOPLENGTH 48
int16_t sine_table[LOOPLENGTH] = {0, 1305, 2588, 3827,
5000, 6088, 7071, 7934, 8660, 9239, 9659, 9914, 10000,
9914, 9659, 9239, 8660, 7934, 7071, 6088, 5000, 3827,
2588, 1305, 0, -1305, -2588, -3827, -5000, -6088, -7071,
-7934, -8660, -9239, -9659, -9914, -10000, -9914, -9659,
-9239, -8660, -7934, -7071, -6088, -5000, -3827, -2588,
-1305};
int16_t sine_ptr = 0; // _pointer into lookup table_
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
left_out_sample = sine_table[sine_ptr];
sine_ptr = (sine_ptr+1)%LOOPLENGTH;
while(SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
else
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = 0;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
GPIO_ToggleBits(GPIOD, GPIO_Pin_15);
}
**int** main( **void** )
{
stm32_wm5102_init(FS_48000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
The DAC in the WM5102 codec reconstructs a sinusoidal analogue output signal from the output sample values.
### 2.6.1 Running the Program
Build and run the program and verify a 1 kHz output tone on the (green) LINE OUT and (black) HEADSET connections on the Wolfson audio card.
Program `stm32f4_sine8_intr.c` is similar to program `stm32f4_sine48_intr.c` in that it generates a sinusoidal analog output waveform with a frequency of 1 kHz from a lookup table of sample values. However, it uses a sampling rate of 8 kHz and a lookup table containing just eight sample values, that is,
#define LOOPLENGTH 8
int16_t sine_table[LOOPLENGTH] = {
0, 7071, 10000, 7071, 0, -7071, -10000, -7071};
### 2.6.2 Out-of-Band Noise in the Output of the AIC3104 Codec (`tm4c123_sine48_intr.c`)
While performing essentially similar functions, the codecs used in the two different hardware platforms differ subtly in their characteristics and functionality. If you are using the TM4C123 LaunchPad and AIC3104 audio booster pack rather than the STM32F407 Discovery and Wolfson audio card, connect an oscilloscope to the (black) LINE OUT socket on the audio booster pack. Run program `tm4c123_sine48_intr.c` and you should see a waveform similar to that shown in Figure 2.19. There is a significant level of noise superimposed on the 1-kHz sine wave, and this reveals something about the characteristics of the AIC3104 DAC. It is an oversampling sigma-delta DAC that deliberately moves noise out of the (audio) frequency band. The out-of-band-noise present in the DAC output can be observed in the frequency domain using a spectrum analyzer or an FFT function on a digital oscilloscope.
**Figure 2.19** (a) 1-kHz sinusoid generated using program `tm4c123_sine48_intr.c` viewed using _Rigol DS1052E_ oscilloscope connected to (black) LINE OUT connection on audio booster pack. (b) Magnitude of FFT of signal plotted using MATLAB.
The plot shown in Figure 2.19 was obtained using a _Rigol DS1052E_ digital oscilloscope to capture the output waveform and then the magnitude of the FFT of the data was plotted using MATLAB. It shows clearly both the 1-kHz tone and the out-of-band-noise above 100 kHz. The out-of-band-noise is not a problem for listening to audio signals because headphones or loudspeakers will not usually have frequency responses that extend that high and neither does the human ear. However, in order to see clearly the in-band detail of audio signals generated by the AIC3104 codec using an oscilloscope, it is useful to add a first-order low-pass filter comprising a capacitor and a resistor to the LINE OUT signal path. This can be done by fitting jumper J6 or J7 and looking at the output signals on the scope hooks, TP2 and TP3, on the audio booster pack. Figure 2.20 shows the filtered output signal from the program in both time and frequency domains for comparison with Figure 2.19.
**Figure 2.20** (a) 1-kHz sinusoid generated using program `tm4c123_sine48_intr.c` viewed using _Rigol DS1052E_ oscilloscope connected to scope hook on audio booster pack. (b) Magnitude of FFT of signal plotted using MATLAB.
**Figure 2.21** Rectangular pulse output on GPIO pin PD15 by program `stm32f4_sine_intr.c`.
In any examples in this book, in which an oscilloscope is used to view an output signal from the AIC3104 codec, it is recommended that the oscilloscope probe is connected to one of the scope hooks on the audio booster pack (TP2 or TP3) and the corresponding jumper J6 or J7 is fitted.
In contrast, the analog signals output by the WM5102 codec via the LINE OUT connection on the Wolfson audio card do not contain out-of-band-noise as described here and connections may be made directly from the (green) LINE OUT connection on the Wolfson audio card to an oscilloscope (using a 3.5-mm jack plug to RCA plug cable and an RCA to BNC adapter).
* * *
# Example 2.12
**Sine wave generation using a`sinf()` function call (`stm32f4_sine_intr.c`).**
* * *
Sine waves of different frequencies can be generated using the table lookup method employed by programs `stm32f4_sine48_intr.c` and `stm32f4_sine8_intr.c`. For example, a 3-kHz sine wave can be generated using program `stm32f4_sine8_intr.c` by changing the program statement that reads
int16_t sine_table[LOOPLENGTH] = {
0, 7071, 10000, 7071, 0, -7071, -10000, -7071};
to read
int16_t sine_table[LOOPLENGTH] = {
0, 7071, -10000, 7071, 0, -7071, 10000, -7071};
However, changing the contents and/or size of the lookup table is not a particularly flexible way of generating sinusoids of arbitrary frequencies (Example 2.26 demonstrates how different frequency sinusoids _may_ be generated from a fixed lookup table).
Program `stm32f4_sine_intr.c`, shown in Listing 2.25, takes a different approach. At each sampling instant, that is, in function `SPI2_IRQHandler()`, a new output sample value is calculated using a call to the math library function `sinf()`. The floating point parameter, `theta`, passed to that function is incremented at each sampling instant by the value `theta_increment = 2*PI*frequency/SAMPLING_FREQ`, and when the value of `theta` exceeds , the value is subtracted from it.
* * *
# Listing 2.13 Program `stm32f4_sine_intr.c`
_// stm32f4_sine_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#define** SAMPLING_FREQ 8000
float32_t frequency = 1000.0;
float32_t amplitude = 10000.0;
float32_t theta_increment;
float32_t theta = 0.0;
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
theta_increment = 2*PI*frequency/SAMPLING_FREQ;
theta += theta_increment;
if (theta > 2*PI) theta -= 2*PI;
GPIO_SetBits(GPIOD, GPIO_Pin_15);
left_out_sample = (int16_t)(amplitude*sinf(theta));
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
while(SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = 0;
while(SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
While program `stm32f4_sine_intr.c` has the advantage of flexibility, it also has the disadvantage, relative to program `stm32f4_sine48_intr.c`, that it requires greater computational effort. This is an important consideration in real-time applications.
### 2.6.3 Running the Program
Build and run this program and experiment by changing the value assigned to the variable `frequency` in the range from 100.0–3800.0 (editing the program and rebuilding the project each time). The sampling frequency used by this program is 8 kHz. Program `stm32f4_sine_intr.c` uses GPIO pin PD15 to indicate the time taken to execute interrupt service routine `SPI2_IRQHandler()`. GPIO pin PD15 is set high by program statement
GPIO_SetBits(GPIOD, GPIO_Pin_15);
at the start of the interrupt service routine `SPI2_IRQHandler()` and reset low by program statement
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
at the end of the interrupt service routine `SPI2_IRQHandler()`. In other words, it outputs a rectangular pulse on PD15 every 125 µs and the duration of that pulse is indicative of the time taken to compute each new output sample value. That time is determined primarily by the time taken to execute program statement
left_out_sample = (int16_t)(amplitude*sinf(theta));
Figure 2.21 shows the waveform output on GPIO pin PD15. The duration of the pulses is approximately 680 ns. Function `sinf()` is used because function `sin()` is computationally too expensive to be used in this application. A slightly more efficient alternative is provided by function `arm_sin_f32()`, defined in the CMSIS DSP library. Edit the program, replacing the program statement
left_out_sample = (int16_t)(amplitude*sinf(theta));
with
left_out_sample = (int16_t)(amplitude*arm_sin_f32(theta));
and you should find that the duration of the pulse output on PD15 is reduced to approximately 400 ns. In general, calls to trigonometrical functions defined in standard math libraries should be avoided in real-time DSP applications.
* * *
# Example 2.13
**Swept Sinusoid Using Table with 8000 Points (`stm32f4_sweep_intr.c`).**
* * *
This example illustrates the use of a fixed lookup table of sample values in order to generate sinusoidal analog output waveforms of arbitrary frequency (without changing the sampling frequency). Listing 2.27 is of program `stm32f4_sweep_intr.c`, which generates a swept frequency sinusoidal signal using a lookup table containing 8000 sample values. This is a method of waveform generation commonly used in laboratory signal generators. The header file `sine8000_table.h`, generated using the MATLAB command
>> x = 1000*sin(2*pi*[0:7999]/8000);
contains 8000 sample values that represent exactly one cycle of a sine wave. Listing 2.28 is a partial listing of the file `sine8000_table.h`.
* * *
# Listing 2.14 Program `stm32f4_sweep_intr.c`
_// stm32f4_sweep_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#include** "sine8000_table.h" //one cycle with 8000 points
**#define** SAMPLING_FREQ 8000.0
**#define** N 8000
**#define** START_FREQ 500.0
**#define** STOP_FREQ 3800.0
**#define** START_INCR START_FREQ*N/SAMPLING_FREQ
**#define** STOP_INCR STOP_FREQ*N/SAMPLING_FREQ
**#define** SWEEPTIME 4
**#define** DELTA_INCR (STOP_INCR - START_INCR)/(N*SWEEPTIME)
int16_t amplitude = 10;
float32_t float_index = 0.0;
float32_t float_incr = START_INCR;
int16_t i;
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
GPIO_SetBits(GPIOD, GPIO_Pin_15);
float_incr += DELTA_INCR;
**if** (float_incr > STOP_INCR) float_incr = START_INCR;
float_index += float_incr;
**if** (float_index > N) float_index -= N;
i = (int16_t)(float_index);
left_out_sample = (amplitude*sine8000[i]);
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = 0;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
* * *
# Listing 2.15 Partial listing of header file `sine8000_table.h`
_//sine8000_table.h Sine table with 8000 points_
**short** sine8000[8000]=
{0, 1, 2, 2, 3, 4, 5, 5,
6, 7, 8, 9, 9, 10, 11, 12,
13, 13, 14, 15, 16, 16, 17, 18,
19, 20, 20, 21, 22, 23, 24, 24,
25, 26, 27, 27, 28, 29, 30, 31,
31, 32, 33, 34, 35, 35, 36, 37,
38, 38, 39, 40, 41, 42, 42, 43,
44, 45, 46, 46, 47, 48, 49, 49,
50, 51, 52, 53, 53, 54, 55, 56,
57, 57, 58, 59, 60, 60, 61, 62,
63, 64, 64, 65, 66, 67, 67, 68,
69, 70, 71, 71, 72, 73, 74, 75,
.
.
.
-19, -18, -17, -16, -16, -15, -14, -13,
-13, -12, -11, -10, -9, -9, -8, -7,
-6, -5, -5, -4, -3, -2, -2, -1}
* * *
At each sampling instant, program `stm32f4_sweep_intr.c` reads an output sample value from the array `sine8000`, using the `float32_t` value of variable `float_index`, converted to type `int16_t`, as an index, and increments the value of `float_index` by the value `float_incr`. With `N` points in the lookup table representing one cycle of a sinusoid, the frequency of the output waveform is equal to `SAMPLING_FREQ*float_incr/N`. A fixed value of `float_incr` would result in a fixed output frequency. In program `stm32f4_sweep_intr.c`, the value of `float_incr` itself is incremented at each sampling instant by the value `DELTA_INCR` and hence the frequency of the output waveform increases gradually from `START_FREQ` to `STOP_FREQ`. The output waveform generated by the program can be altered by changing the values of the constants `START_FREQ`, `STOP_FREQ`, and `SWEEPTIME`, from which the value of `DELTA_INCR` is calculated. Build and run this program. Verify the output to be a sinusoid taking `SWEEPTIME` seconds to increase in frequency from `START_FREQ` to `STOP_FREQ`.
* * *
# Example 2.14
**Generation of DTMF Tones Using a Lookup Table (`tm4c123_sineDTMF_intr.c`).**
* * *
Program `tm4c123_sineDTMF_intr.c`, listed in Listing 2.30, uses a lookup table containing 512 samples of a single cycle of a sinusoid together with two independent pointers to generate a dual-tone multifrequency (DTMF) waveform. DTMF waveforms comprising the sum of two sinusoids of different frequencies are used in telephone networks to indicate key presses. A total of 16 different combinations of frequencies each comprising one of four low-frequency components (697, 770, 852, or 941 Hz) and one of four high-frequency components (1209, 1336, 1477, or 1633 Hz) are used. Program `tm4c123_sineDTMF_intr.c` uses two independent pointers into a single lookup table, each updated at the same rate (16 kHz) but each stepping through the values in the table using different step sizes.
* * *
# Listing 2.16
Program `tm4c123_sineDTMF_intr.c`.
_// tm4c123_sineDTMF_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#define** TABLESIZE 512 // size of look up table
**#define** SAMPLING_FREQ 16000
**#define** STEP_770 (float32_t)(770 * TABLESIZE)/SAMPLING_FREQ
**#define** STEP_1336 (float32_t)(1336 * TABLESIZE)/SAMPLING_FREQ
**#define** STEP_697 (float32_t)(697 * TABLESIZE)/SAMPLING_FREQ
**#define** STEP_852 (float32_t)(852 * TABLESIZE)/SAMPLING_FREQ
**#define** STEP_941 (float32_t)(941 * TABLESIZE)/SAMPLING_FREQ
**#define** STEP_1209 (float32_t)(1209 * TABLESIZE)/SAMPLING_FREQ
**#define** STEP_1477 (float32_t)(1477 * TABLESIZE)/SAMPLING_FREQ
**#define** STEP_1633 (float32_t)(1633 * TABLESIZE)/SAMPLING_FREQ
int16_t sine_table[TABLESIZE];
float32_t loopindexlow = 0.0;
float32_t loopindexhigh = 0.0;
int16_t output;
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
output = (sine_table[(int16_t)loopindexlow]
+ sine_table[(int16_t)loopindexhigh]);
loopindexlow += STEP_770;
**if** (loopindexlow > (float32_t)TABLESIZE)
loopindexlow -= (float32_t)TABLESIZE;
loopindexhigh += STEP_1477;
**if** (loopindexhigh > (float32_t)TABLESIZE)
loopindexhigh -= (float32_t)TABLESIZE;
sample_data.bit32 = ((int16_t)(output));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(output));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
int16_t i;
tm4c123_aic3104_init(FS_16000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**for** (i=0 ; i< TABLESIZE ; i++)
sine_table[i] = (int16_t)(10000.0*sin(2*PI*i/TABLESIZE));
**while** (1){}
}
* * *
A pointer that stepped through every single one of the `TABLESIZE` samples stored in the lookup table at a sampling rate of 16 kHz would generate a sinusoidal tone with a frequency equal to `(16000/TABLESIZE)`. A pointer that stepped through the samples stored in the lookup table, incremented by a value STEP, would generate a sinusoidal tone with a frequency equal to `(16000 * STEP/TABLESIZE)`. From this, it is possible to calculate the required step size for any desired frequency. For example, in order to generate a sinusoid with frequency 770 Hz, the required step size is `STEP = TABLESIZE * 770/16000 = 24.64`. In other words, at each sampling instant, the pointer into the lookup table should be incremented by 24.64. The pointer value, or index, into the lookup table must be an integer value (`(int16_t)(loopindexlow)`) but a floating-point value of the pointer, or index, (`loopindexlow`) is maintained by the program and incremented by 24.64 at each sampling instant and wrapping around to 0.0 when its value exceeds 512.0 using the statements
loopindexlow += 24.64;
if(loopindexlow>(float32_t)TABLESIZE)loopindexlow-=(float32_t)TABLESIZE;
In program `tm4c123_sineDTMF_intr.c`, the floating point values by which the table lookup indices are incremented are predefined using, for example,
#define STEP_770 (float32_t)(770 * TABLESIZE) / SAMPLING_FREQ
In order to change the DTMF tone generated and simulate a different key press, edit program `tm4c123_sineDTMF_intr.c` and change the program statements.
loopindexlow += STEP_697;
loopindexhi += STEP_1477;
to, for example
loopindexlow += STEP_770;
loopindexhi += STEP_1209;
An example of the output generated by program `tm4c123_sineDTMF_intr.c` is shown in Figure 2.22.
**Figure 2.22** Output from program `tm4c123_sineDTMF_intr.c` viewed using _Rigol DS1052 oscilloscope_.
* * *
# Example 2.15
**Signal Reconstruction, Aliasing, and the Properties of the WM5102 Codec (`stm32f4_sine_intr.c`).**
* * *
Generating analog output signals using, for example, program `stm32f4_sine_intr.c` is a useful means of investigating the characteristics of the WM5102 codec. If you are using the TM4C123 LaunchPad and AIC3104 audio booster pack, program `tm4c123_sine_intr.c` and others are useful means of investigating the slightly different characteristics of the AIC3104 codec.
Change the value of the variable `frequency` in program `stm32f4_sine_intr.c` to an arbitrary value between 100.0 and 3500.0, and you should find that a sine wave of that frequency (in Hz) is generated. Change the value of the variable `frequency` to 7000.0, however, and you will find that a 1000 Hz sine wave is generated. The same is true if the value of `frequency` is changed to 9000.0 or 15000.0. A value of `frequency` equal to 5000.0 will result in an output waveform with a frequency of 3000 Hz. These effects are related to the phenomenon of aliasing. Since the reconstruction (DAC) process that creates a continuous-time analog waveform from discrete-time samples is one of low-pass filtering, it follows that the bandwidth of signals output by the codec is limited (to less than half the sampling frequency). This can be demonstrated in a number of different ways.
For example, run program `stm32f4_sine_intr.c` with the value of the variable `frequency` set to 3500.0 and verify that the output waveform generated has a frequency of 3500 Hz. Change the value of the variable `frequency` to 4500.0. The frequency of the output waveform should again be equal to 3500 Hz. Try any value for the variable `frequency`. You should find that it is impossible to generate an analog output waveform with a frequency greater than or equal to 4000 Hz (assuming a sampling frequency of 8000 Hz). This is consistent with viewing the DAC as a low-pass filter with a cutoff frequency equal to slightly less than half its sampling frequency.
The following examples demonstrate a number of alternative approaches to observing the low-pass characteristic of the DAC.
* * *
# Example 2.16
**Square wave generation using a lookup table (`stm32f4_square_intr.c`).**
* * *
Program `stm32f4_square_intr.c`, shown in Listing 2.33, differs from program `stm32f4_sine8_intr.c` only in that it uses a lookup table containing 64 samples of one cycle of a square wave of frequency 125 Hz rather than 48 samples of one cycle of a sine wave of frequency 1 kHz.
* * *
# Listing 2.17 Program `stm32f4_square_intr.c`
_// stm32f4_square_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#define** LOOP_SIZE 64
int16_t square_table[LOOP_SIZE] = {
10000, 10000, 10000, 10000,
10000, 10000, 10000, 10000,
10000, 10000, 10000, 10000,
10000, 10000, 10000, 10000,
10000, 10000, 10000, 10000,
10000, 10000, 10000, 10000,
10000, 10000, 10000, 10000,
10000, 10000, 10000, 10000,
-10000, -10000, -10000, -10000,
-10000, -10000, -10000, -10000,
-10000, -10000, -10000, -10000,
-10000, -10000, -10000, -10000,
-10000, -10000, -10000, -10000,
-10000, -10000, -10000, -10000,
-10000, -10000, -10000, -10000,
-10000, -10000, -10000, -10000};
**static int** square_ptr = 0;
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
left_out_sample = square_table[square_ptr];
square_ptr = (square_ptr+1)%LOOP_SIZE;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = 0;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
### 2.6.4 Running the Program
Build and run the program, and using an oscilloscope connected to the (green) LINE OUT socket on the audio card, you should see an output waveform similar to that shown in Figure 2.23. This waveform is equivalent to a square wave (represented by the samples in the lookup table) passed through a low-pass filter (the DAC). The ringing that follows each transition in the waveform is indicative of the specific characteristics of the reconstruction filter implemented by the WM5102 DAC. The low-pass characteristic of the reconstruction filter can further be highlighted by looking at the frequency content of the output waveform. While the Fourier series representation of a square wave is the sum of an infinite series of harmonic components, only harmonic components with frequencies below 3.8 kHz are present in the analog output waveform as shown in the lower trace of Figure 2.24.
**Figure 2.23** Output from program `stm32f4_square_intr.c` viewed using _Rigol DS1052 oscilloscope_.
**Figure 2.24** Output from program `stm32f4_square_intr.c` viewed in both time and frequency domains using _Rigol DS1052 oscilloscope_.
* * *
# Example 2.17
**Square Wave Generation Using a Look Up Table (`tm4c123_square_intr.c`).**
* * *
Program `tm4c123_square_intr.c` is an equivalent (to `stm32f4_square_intr.c`) program that runs on the TM4C123 LaunchPad. The output waveform, as it appears on the scope hook connections on the audio booster pack and as shown in Figure 2.25, is subtly different to that shown in Figure 2.23. In this case, ringing precedes as well as follows transitions in the waveform. This suggests strongly that the reconstruction filter in the AIC3104 DAC is implemented as a digital FIR filter (at a higher sampling frequency than that at which sample values are written to the DAC by program `tm4c123_square_intr.c`). Viewed in the frequency domain (Figure 2.26), it is apparent that once again the analog output waveform contains only the harmonic components of a 125 Hz square wave at frequencies lower than 3.8 kHz.
**Figure 2.25** Output from program `tm4c123_square_intr.c` viewed using _Rigol DS1052 oscilloscope_.
**Figure 2.26** Output from program `tm4c123_square_intr.c` viewed in both time and frequency domains using _Rigol DS1052 oscilloscope_.
A further demonstration of the low-pass characteristic of the reconstruction filter is given by program `tm4c123_square_1khz_intr.c`. Here, the sequence of sample values written to the DAC at a sampling frequency of 8 kHz is given by
#define LOOPLENGTH 8
int16_t square_table[LOOPLENGTH] = {
10000, 10000, 10000, 10000,
-10000, -10000, -10000, -10000};
Ostensibly, these sample values represent one cycle of a 1-kHz square wave. However, the output waveform generated contains only the first two harmonic components of a 1-kHz square wave (at 1 and 3 kHz), that is, only the harmonic components of a 1-kHz square wave with frequencies lower than 3.8 kHz, the cutoff frequency of the DAC. The analog output waveform is shown in Figure 2.27 and is clearly not a square wave.
**Figure 2.27** Output from program `tm4c123_square_1khz_intr.c` viewed using _Rigol DS1052 oscilloscope_.
* * *
# Example 2.18
**Impulse Response of the WM5102 DAC Reconstruction Filter (`stm32f4_dimpulse_intr.c`).**
* * *
Each transition in the waveform generated by program `stm32f4_square_intr.c` may be considered as representative of the step response of the reconstruction filter in the WM5102 DAC. From this, the impulse response of the filter may be surmised.
That impulse response is of interest since, in accordance with linear systems theory, it characterizes the filter. Specifically, the impulse response of the WM5102 DAC is equal to the time derivative of its step response, and by inspection of Figure 2.23, it is apparent that the impulse response will have the form of a (relatively) slowly (exponentially) decaying oscillation. The impulse response can be illustrated more directly by running program `stm32f4_dimpulse_intr.c`. This program replaces the samples of a square wave in the lookup table used by program `stm32f4_square_intr.c` with a discrete impulse sequence. Figure 2.28 shows the output waveform generated by `stm32f4_dimpulse_intr.c` and its magnitude FFT calculated using a _Rigol DS1052E_ oscilloscope. The Fourier transform of the impulse response of a linear time-invariant system is equal to its frequency response.
**Figure 2.28** Output from program `stm32f4_dimpulse_intr.c` viewed in time and frequency domains using _Rigol DS1052 oscilloscope_.
* * *
# Example 2.19
**Impulse Response of the AIC3104 DAC Reconstruction Filter (`tm4c123_dimpulse_intr.c`).**
* * *
This program illustrates the impulse response of the AIC3104 DAC. As suggested by the output waveform generated using program `tm4c123_square_intr.c` in the previous example, the corresponding impulse response is subtly different from that of the WM5102 DAC. The two different impulse responses, each of which corresponds to a near-ideal low-pass frequency response, are representative of those found in the majority of audio codecs. That of the WM5102 is termed a low-latency response. It is perhaps tempting to view the impulse response of the AIC3104 codec as noncausal and think of the central peak of the pulse shown in Figure 2.29 as corresponding to the same time as that of the impulse causing it. This, of course, is impossible in practice. Without knowing the detailed workings of the AIC3104 DAC, it is nonetheless apparent that the impulse causing the response shown in Figure 2.29 must have occurred before any of the ripples evident in that pulse and hence approximately 1 ms before its peak. In contrast, the impulse causing the impulse response of the WM5102 DAC shown in Figure 2.28 probably occurred approximately 300 µs before the peak.
**Figure 2.29** Output from program `tm4c123_dimpulse_intr.c` viewed using _Rigol DS1052 oscilloscope_.
* * *
# Example 2.20
**Ramp Generation (`tm4c123_ramp_intr.c`).**
* * *
Listing 2.38 is of program `tm4c123_ramp_intr.c`, which generates a ramp, or sawtooth, output waveform. The value of the output sample `output_left` is incremented by 2000 every sampling instant until it reaches the value 30,000, at which point it is reset to the value 30,000. Build and run this program. Figure 2.30 shows the analog output waveform captured using an oscilloscope. The output comprises harmonic components at frequencies less than 4 kHz.
**Figure 2.30** Output waveform generated by program `tm4c123_ramp_intr.c`.
* * *
# Listing 2.18 Program `tm4c123_ramp_intr.c`
_// tm4c123_ramp_intr.c_
**#include** "tm4c123_aic3104_init.h"
int16_t output = 0;
**void** SSI_interrupt_routine(void)
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
output += 2000;
**if** (output >= 30000)
output = -30000;
sample_data.bit32 = ((int16_t)(output));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(output));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
* * *
# Example 2.21
**Amplitude Modulation (`tm4c123_am_poll.c`).**
* * *
This example illustrates the basic principles of amplitude modulation (AM). Listing 2.40 is of program `tm4c123_am_poll.c`, which generates an AM signal. The array `baseband` holds 20 samples of one cycle of a cosine waveform with a frequency of fs/20 = 400 Hz (sampling frequency, fs = 8000 Hz). The array `carrier` holds 20 samples of five cycles of a sinusoidal carrier signal with a frequency of 5fs/20 = 2000 Hz. Output sample values are calculated by multiplying the baseband signal `baseband` by the carrier signal `carrier`. In this way, the baseband signal modulates the carrier signal. The variable `amp` is used to set the modulation index.
* * *
# Listing 2.19 Program `tm4c123_am_poll.c`
_// tm4c123_am poll.c_
**#include** "tm4c123_aic3104_init.h"
**short** amp = 20; // _index for modulation_
**void** SSI_interrupt_routine( **void** ){ **while** (1){}}
**int** main( **void** )
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
int16_t baseband[20] = {1000,951,809,587,309,0,-309,
-587,-809,-951,-1000,-951,-809,
-587,-309,0,309,587,809,951}; // _400 Hz_
int16_t carrier[20] = {1000,0,-1000,0,1000,0,-1000,
0,1000,0,-1000,0,1000,0,-1000,
0,1000,0,-1000,0}; // _2 kHz_
int16_t output[20];
int16_t k;
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_POLL,
PGA_GAIN_6_DB);
**while** (1)
{
**for** (k=0; k<20; k++)
{
output[k]= carrier[k] + ((amp*baseband[k]*carrier[k]/10)>>12);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
sample_data.bit32 = ((int16_t)(20*output[k]));
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIDataPut(SSI0_BASE,sample_data.bit32);
}
}
}
* * *
### 2.6.5 Running the Program
Build and run this program. Verify that the output consists of the 2-kHz carrier signal and two sideband signals as shown in Figure 2.31. The sideband signals are at the frequency of the carrier signal, +/ the frequency of the baseband signal, or at 1600 and 2400 Hz. The magnitude of the sidebands relative to the carrier signal may be altered by changing the value of the variable `amp` in the source file. The project will need to be rebuilt for such a change to take effect.
**Figure 2.31** Output waveform generated by program `tm4c123_am_intr.c`.
## 2.7 Identifying the Frequency Response of the DAC Using Pseudorandom Noise
* * *
# Example 2.22
**Frequency Response of the AIC3104 DAC Reconstruction Filter Using a Pseudorandom Binary Sequence (`tm4c123_prbs_intr.c`).**
* * *
Program `tm4c123_prbs_intr.c`, shown in Listing 2.42, generates a pseudorandom binary sequence (PRBS) and writes this to the AIC3104 DAC. Function `prbs()`, defined in file `tm4c123_aic3104_init.c`, and shown in Listing 2.43, uses a 16-bit linear feedback shift register (LFSR) to generate a maximal-length pseudorandom binary sequence. The least significant bit of the register is used to determine whether function `prbs()` returns either the value `noise_level` or the value `-noise_level`, where `noise_level` is a 16-bit integer value passed to the function. The value of the LFSR (`lfsr`) is initialized to `0x0001`. Each time function `prbs()` is called, a feedback value (`fb`) is formed by the modulo-2 sum of bits 15, 14, 3, and 1 in `lfsr`. The contents of the LFSR are shifted left by one bit and the value of bit 0 is assigned the feedback value `fb`. If the value of `fb` is equal to zero, then the function returns the value `-noise_level`. Otherwise, it returns the value `noise_level`.
* * *
# Listing 2.20 Program `tm4c123_prbs_intr.c`
_// tm4c123_prbs_intr.c_
**#include** "tm4c123_aic3104_init.h"
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
float32_t output_left, output_right;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
output_left = (float32_t)(prbs(8000));
output_right = output_left;
sample_data.bit32 = ((int16_t)(output_left));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(output_right));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
* * *
# Listing 2.21 Definition of function `prbs()`, defined in file `tm4c123_aic3104_init.c`
**typedef union**
{
uint16_t value;
**struct**
{
**unsigned char** bit0 : 1;
**unsigned char** bit1 : 1;
**unsigned char** bit2 : 1;
**unsigned char** bit3 : 1;
**unsigned char** bit4 : 1;
**unsigned char** bit5 : 1;
**unsigned char** bit6 : 1;
**unsigned char** bit7 : 1;
**unsigned char** bit8 : 1;
**unsigned char** bit9 : 1;
**unsigned char** bit10 : 1;
**unsigned char** bit11 : 1;
**unsigned char** bit12 : 1;
**unsigned char** bit13 : 1;
**unsigned char** bit14 : 1;
**unsigned char** bit15 : 1;
} bits;
} shift_register;
shift_register sreg = {0x0001};
**short** prbs(int16_t noise_level)
{
**char** fb;
fb =((sreg.bits.bit15)+(sreg.bits.bit14)+(sreg.bits.bit3)
+(sreg.bits.bit1))%2
sreg.value = sreg.value << 1;
sreg.bits.bit0 = fb;
**if** (fb 0)
**return** (-noise_level);
**else**
**return** (noise_level);
}
* * *
Figure 2.32 shows the analog output signal generated by the program displayed using an oscilloscope and using _Goldwave_. The theoretical power spectral density of a PRBS is constant across all frequencies. When a PRBS is written to a DAC, the spectral content of the signal output by the DAC is indicative of the magnitude frequency response of the DAC. In this case, the magnitude frequency response is flat, or constant, at frequencies up to the cutoff frequency of the DAC's reconstruction filter just below half its sampling frequency.
**Figure 2.32** Output from program `tm4c123_prbs_intr.c` viewed using _Rigol DS1052_ oscilloscope and _Goldwave_.
### 2.7.1 Programmable De-Emphasis in the AIC3104 Codec
The AIC3104 codec features a programmable first-order de-emphasis filter that may optionally be switched into the signal path just before the DAC. Program `tm4c123_prbs_deemph_intr.c` demonstrates its use (see Figure 2.33). User switch SW1 on the TM4C123 LaunchPad may be used to enable or disable the de-emphasis function. The de-emphasis filters are enabled and disabled by writing to bits 0 (right channel) and 2 (left channel) in page 0 control register 12 ( _Audio Codec Digital Filter Control Register_ ) using function `I2CRegWrite()`.
**Figure 2.33** Output from program `tm4c123_prbs_deemph_intr.c` viewed using _Rigol DS1052_ oscilloscope and _Goldwave_.
The coefficients of the de-emphasis filter can be reprogrammed in order to implement a different first-order IIR filter. In program `tm4c123_prbs_hpf_intr.c`, a high-pass filter has been implemented and its characteristics are apparent in Figure 2.34.
**Figure 2.34** Output from program `tm4c123_prbs_hpf_intr.c` viewed using _Rigol DS1052_ oscilloscope and _Goldwave_.
### 2.7.2 Programmable Digital Effects Filters in the AIC3104 Codec
The AIC3104 codec also features two fourth-order IIR filters that may optionally be switched into the left and right channel signal paths just before the DAC. Program `tm4c123_prbs_biquad_intr.c` demonstrates how the characteristics of these filters can be programmed by writing filter coefficients to AIC3104 page 1 control registers 1 through 20 (left channel) and 27 through 46 (right channel). In this example, a fourth-order elliptic low-pass filter is implemented. Figure 2.35 shows the filtered PRBS signal viewed using an oscilloscope and using _Goldwave_. The IIR filters are enabled and disabled by writing to bits 1 (right channel) and 3 (left channel) in page 0 control register 12 ( _Audio Codec Digital Filter Control Register_ ). The characteristics of these filters and how to program them are described in greater detail in Chapter 4.
**Figure 2.35** Output from program `tm4c123_prbs_biquad_intr.c` viewed using _Rigol DS1052_ oscilloscope and _Goldwave_.
* * *
# Example 2.23
**Frequency response of the DAC reconstruction filter using pseudorandom noise (`tm4c123_prandom_intr.c`).**
* * *
Program `tm4c123_prandom_intr.c` is similar to program `tm4c123_prbs_intr.c` except that it uses a Parks–Miller algorithm to generate a pseudorandom noise sequence. This may be used as an alternative to PRBS in some applications. Function `prand()` (Listing 2.45) is defined in file `tm4c123_aic3104_init.c` and returns pseudorandom values in the range +/ `noise_level`, where `noise_level` is a 16-bit integer value passed to the function. Figure 2.36 shows the waveform output by program `tm4c123_prandom_intr.c` displayed using an oscilloscope. Compare this with the output waveform generated by program `tm4c123_prbs_intr.c`, shown in Figure 2.32.
**Figure 2.36** Output from program `tm4c123_prandom_intr.c` viewed using _Rigol DS1052 oscilloscope_.
Overall, the use of pseudorandom noise as an input signal is a simple and useful technique for assessing the magnitude frequency response of a system.
* * *
# Listing 2.22 Definition of function `prand()`, defined in file `tm4c123_aic3104_init.c`
uint32_t prand_seed = 1; // _used in function prand()_
uint32_t rand31_next()
{
uint32_t hi, lo;
lo = 16807 * (prand_seed & 0xFFFF);
hi = 16807 * (prand_seed >> 16);
lo += (hi & 0x7FFF) << 16;
lo += hi >> 15;
**if** (lo > 0x7FFFFFFF) lo -= 0x7FFFFFFF;
**return** (prand_seed = (uint32_t)lo);
}
int16_t prand(void)
{
**return** ((int16_t)(rand31_next()>>18)-4096);
}
* * *
## 2.8 Aliasing
The preceding examples demonstrate that neither the AIC3104 codec nor the WM5102 codec can generate signal components that have frequencies greater than half their sampling frequency. It follows that it is inadvisable to allow analog input signal components that have frequencies greater than half the sampling frequency to be sampled at the input to the DSP system. This can be prevented by passing analog input signals through a low-pass antialiasing filter prior to sampling. Antialiasing filters with characteristics similar to those of the reconstruction filters in the DACs of the AIC3104 and WM5102 codecs are incorporated into these devices.
* * *
# Example 2.24
**Step response of the WM5102 codec antialiasing filter (`stm32f4_loop_buf_intr.c`).**
* * *
In order to investigate the step response of the antialiasing filter on the WM5102, connect a signal generator to the left channel of the (pink) LINE IN socket on the Wolfson audio card. Adjust the signal generator to give a square wave output of frequency 270 Hz and amplitude 500 mV. Build and run program `stm32f4_loop_buf_intr.c`, halting the program after a few seconds. View the most recent input sample values by saving the contents of array `lbuffer` to a data file by typing
save <filename> <start address>, <start address + 0x400>
at the _Command_ line in the _MDK-ARM debugger_ , where `start address` is the address of array `lbuffer`, and plotting the contents of the data file using MATLAB function `stm32f4_plot_real()`. You should see something similar to that shown in Figure 2.38. Figure 2.37 shows the square wave input signal corresponding to the sample values shown in Figure 2.38. The ringing that follows each transition in the waveform represented by the samples is due to the antialiasing filter. Figure 2.39 shows the corresponding result obtained using program `tm4c123_loop_buf_intr.c`. The antialiasing filters in each of the codecs have characteristics similar to those of their corresponding reconstruction filters. Compare Figures 2.37 and 2.39 with Figures 2.23 and 2.25. The ac coupling of the LINE IN connections on both the Wolfson audio card and the audio booster pack is evident from the drooping of the signal level between transitions in Figures 2.37 and 2.39.
**Figure 2.38** Sample values read from the WM5102 ADC and stored in array `lbuffer` by program `stm32f4_loop_buf_intr.c`.
**Figure 2.37** Square wave input signal used with program `stm32f4_loop_buf_intr.c`.
**Figure 2.39** Sample values read from the WM5102 ADC and stored in array `lbuffer` by program `tm4c123_loop_buf_intr.c`.
* * *
# Example 2.25
**Demonstration of the Characteristics of the AIC3104 Codec Antialiasing Filter (`tm4c123_sine48_loop_intr.c`).**
* * *
Program `tm4c123_sine48_loop_intr.c` is similar to program `tm4c123_sine48_intr.c` in that it generates a 1-kHz sine wave output using sample values read from a lookup table. It differs in that it reads input samples from the ADC and stores the 128 most recent in array `buffer`. Connect the (black) LINE OUT connection on the audio booster card to the (blue) LINE IN connection using a 3.5-mm jack plug to 3.5-mm jack plug cable and run the program for a short length of time. Halt the program and save the contents of array `buffer` to a data file by typing
save <filename> <start address>, <start address + 0x200>
at the _Command_ line in the _MDK-ARM debugger_ , where `start address` is the address of array `buffer`. Plot the contents of the data file using MATLAB function `tm4c123_plot_real()`. You should see something similar to the plot shown in Figure 2.40. The discontinuity at time ms corresponds to the value of the index variable `bufptr` when the program was halted. At first sight, this figure may appear unremarkable. However, when you consider that the analog waveform output by the AIC3104 codec contains out-of-band-noise (readily visible on an oscilloscope as shown in Figure 2.19), it is apparent that the samples stored in array `buffer` are of a low-pass filtered version of that signal. That low-pass filtering operation has been carried out by the antialiasing filter in the codec.
**Figure 2.40** Sample values read from the AIC3104 ADC and stored in array `buffer` by program `tm4c123_sine48_loop_intr.c`.
* * *
# Example 2.26
**Demonstration of Aliasing (`tm4c123_aliasing_intr.c`).**
* * *
The analog and digital antialiasing filters in the AIC3104 and WM5120 codecs cannot be bypassed or disabled. However, aliasing can be demonstrated within a program by downsampling a digital signal _without_ taking appropriate antialiasing measures. Program `tm4c123_aliasing_intr.c`, shown in Listing 2.49 uses a sampling rate of 16 kHz for the codec but then resamples the sequence of samples produced by the ADC at the lower rate of 8 kHz (downsampling). The sequence of samples generated at a rate of 16 kHz by the ADC may contain frequency components at frequencies greater than 4 kHz, and therefore, if that sample sequence is downsampled to a rate of 8 kHz simply by discarding every second sample, aliasing may occur.
To avoid aliasing, the 16 kHz sample sequence output by the ADC must be passed through a digital antialiasing filter before downsampling. Program `tm4c123_aliasing_intr.c` uses an FIR filter with 65 coefficients defined in header file `lp6545.h` for this task. For the purposes of this example, it is unnecessary to understand the operation of the FIR filter. It is sufficient to consider simply that the program demonstrates the effect of sampling at a frequency of 8 kHz with and without using an antialiasing filter.
* * *
# Listing 2.23 Program `tm4c123_aliasing_intr.c`
_// tm4c123_aliasing_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "lp6545.h"
**#define** DISCARD 0
**#define** SAMPLE 1
**#define** BLOCKSIZE 1
**volatile** int16_t flag = DISCARD;
int16_t antialiasing = 0;
float32_t xin[BLOCKSIZE], yin[BLOCKSIZE];
float32_t xout[BLOCKSIZE], yout[BLOCKSIZE];
float32_t stateout[N+BLOCKSIZE-1];
float32_t statein[N+BLOCKSIZE-1];
arm_fir_instance_f32 Sin, Sout;
**void** SSI_interrupt_routine(void)
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
xin[0] = input_left;
arm_fir_f32(&Sin, xin, yin, BLOCKSIZE);
**if** (flag DISCARD)
{
flag = SAMPLE;
xout[0] = 0.0f;
}
**else**
{
flag = DISCARD;
**if** (antialiasing 0)
xout[0] = yin[0];
**else**
xout[0] = input_left;
}
arm_fir_f32(&Sout, xout, yout, BLOCKSIZE);
sample_data.bit32 = ((int16_t)(yout[0]));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(0));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
arm_fir_init_f32(&Sin, N, h, statein, BLOCKSIZE);
arm_fir_init_f32(&Sout, N, h, stateout, BLOCKSIZE);
tm4c123_aic3104_init(FS_16000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1)
{
ROM_SysCtlDelay(10000);
**if** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4))
{
ROM_SysCtlDelay(10000);
antialiasing = (antialiasing+1)
**while** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4)){}
}
}
}
* * *
### 2.8.1 Running the Program
Build, load, and run program `tm4c123_aliasing_intr.c`. Connect a signal generator to the (blue) LINE IN socket on the audio booster pack and either connect an oscilloscope to one of the scope hooks on the audio booster pack or use _GoldWave_ via the (black) LINE OUT socket. Vary the frequency of a sinusoidal input signal between 0 and 8 kHz. Press user switch SW1 on the TM4C123 LaunchPad to switch the antialiasing filter implemented by the program on and off.
With the antialiasing filter enabled, signals with frequencies greater than 4 kHz do not pass from LINE IN to LINE OUT. But with the antialiasing filter disabled, and by varying the frequency of the input signal, you should be able to verify that sinusoids with frequencies between 4 and 8 kHz are "folded back" into the frequency range 0–4 kHz.
## 2.9 Identifying The Frequency Response of the DAC Using An Adaptive Filter
* * *
# Example 2.27
**Identification of AIC3104 codec bandwidth using an adaptive filter (`tm4c123_sysid_CMSIS_intr.c`).**
* * *
Another way of observing the limited bandwidth of the codec is to measure its magnitude frequency response using program `tm4c123_sysid_CMSIS_intr.c`. This program, shown in Listing 2.51 uses an adaptive FIR filter and is described in more detail in Chapter 6. However, you need not understand exactly how program `tm4c123_sysid_CMSIS_intr.c` works in order to use it. Effectively, it identifies the characteristics of the path between its discrete-time output and its discrete-time input (points A and B in Figure 2.41).
**Figure 2.41** Connection diagram for program `tm4c123_sysid_CMSIS_intr.c`.
* * *
# Listing 2.24 Program `tm4c123_sysid_CMSIS_intr.c`
_// tm4c123_sysid_CMSIS_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#define** BETA 1E-11
**#define** NUM_TAPS 128
**#define** BLOCK_SIZE 1
float32_t firStateF32[BLOCK_SIZE + NUM_TAPS -1];
float32_t firCoeffs32[NUM_TAPS] = {0.0};
arm_lms_instance_f32 S;
**void** SSI_interrupt_routine(void)
{
AIC3104_data_type sample_data;
float32_t adapt_in, adapt_out, desired;
float32_t error, input_left, input_right;
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
adapt_in = (float32_t)(prbs(8000));
desired = input_left;
arm_lms_f32(&S, &adapt_in, &desired,
&adapt_out, &error, 1);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
sample_data.bit32 = ((int16_t)(adapt_in));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(adapt_in));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main()
{
arm_lms_init_f32(&S, NUM_TAPS, firCoeffs32,
firStateF32, BETA, BLOCK_SIZE);
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
### 2.9.1 Running the Program
Connect the (black) LINE OUT socket on the audio booster pack to the (blue) LINE IN socket input using a 3.5 mm jack plug to 3.5 mm jack plug cable as shown in Figure 2.41. The signal path that will be identified by the program comprises the series combination of the DAC and ADC and the ac-coupling circuits between the converters and the jack socket connections on the audio booster pack. Run the program for a few seconds and then halt it and plot the values of the weights of the adaptive filter (the identified impulse response of the signal path) by saving the 128 adaptive filter coefficients, stored in array `firCoeffs32`, and using MATLAB function `tm4c123_logfft()`.
Type
save <filename> <start address>, <start address + 0x200>
at the _Command_ line in the _MDK-ARM debugger_ , where `start address` is the address of array `firCoeffs32`, and plot using MATLAB function `tm4c123_logfft()`.
The adaptive filter coefficients used by the CMSIS function `arm_lms_f32()` are stored in memory in reverse order relative to the sense in which they represent the impulse response of the filter, and therefore, when using MATLAB function `stm32f4_logfft()`, respond to the prompt
forward (0) or reverse (1) order of time-domain samples?
by entering the value `1`.
The roll-off of the frequency response at very low frequencies evident in Figure 2.42 is due to the ac coupling between the codec and the 3.5 mm LINE IN and LINE OUT jack sockets. The roll-off of the frequency response at frequencies greater than 3200 Hz is due to the antialiasing and reconstruction filters in the AIC3104 ADC and DAC. A gain of approximately 6 dB due to the potential divider comprising two 5k6 ohm resistors (shown in Figure 2.04) between the (blue) LINE IN socket and LINEIN_L the codec is compensated for by the gain of +6 dB programmed into the PGA that immediately precedes the ADC in the AIC3014 (by passing parameter value `PGA_GAIN_6_DB` to function `tm4c123_aic3104_init()`).
**Figure 2.42** The impulse response and magnitude frequency identified using program `tm4c123_sysid_CMSIS_intr.c` with connections as shown in Figure 2.41, displayed using MATLAB function `tm4c123_logfft()`. Sampling frequency 8000 Hz, 128-coefficient adaptive filter.
Program `tm4c123_sysid_CMSIS_intr.c` may be used to identify the characteristics of another system (as opposed to just a connecting cable) connected between LINE OUT and LINE IN on the audio booster pack. Figure 2.43 shows the result when a first-order low-pass analog filter comprising a capacitor and resistor was used.
**Figure 2.43** The impulse response and magnitude frequency identified using program `tm4c123_sysid_CMSIS_intr.c` with a first-order low-pass analog filter connected between LINE IN and LINE OUT sockets, displayed using MATLAB function `tm4c123_logfft()`. Sampling frequency 8000 Hz, 128-coefficient adaptive filter.
Program `tm4c123_sysid_deemph_CMSIS_intr.c` is similar to `tm4c123_sysid_CMSIS_intr.c` but enables the digital de-emphasis filter located just before the DAC in the AIC3104 as in Example 2.45. Figure 2.44 shows the result of running the program. Compare this with Figure 2.33.
**Figure 2.44** The impulse response and magnitude frequency identified using program `tm4c123_sysid_CMSIS_intr.c` with connections as shown in Figure 2.41 and de-emphasis enabled, displayed using MATLAB function `tm4c123_logfft()`. Sampling frequency 8000 Hz, 128-coefficient adaptive filter.
Figure 2.45 shows the result of running program `stm32f4_sysid_CMSIS_intr.c` on the STM32F407 Discovery with a sampling frequency of 8 kHz.
**Figure 2.45** The impulse response and magnitude frequency identified using program `stm32f4_sysid_CMSIS_intr.c` with LINE OUT connected directly to LINE OUT, displayed using MATLAB function `stm32f4_logfft()`. Sampling frequency 8000 Hz, 128-coefficient adaptive filter.
The plots illustrating examples of the instantaneous frequency response of program `tm4c123_flanger_intr.c` in Example 2.18 were obtained using program `tm4c123_sysid_flange_intr.c`, a slightly modified version of program `tm4c123_sysid_intr.c` that includes a flanger (Figure 2.13) with a fixed delay in the signal path identified.
* * *
# Example 2.28
**Identification of AIC3104 Codec Bandwidth Using Two Audio Booster Packs (`tm4c123_sysid_CMSIS_intr.c`).**
* * *
Program `tm4c123_sysid_CMSIS_intr.c` can identify frequency response characteristics in the range 0 to half its sampling frequency (in the previous example, the sampling frequency was equal to 8 kHz) but the antialiasing and reconstruction filters in the codec have a bandwidth only slightly less than this. Hence, in Figures 2.42 through 2.45, only the passbands of those filters are displayed. The following example uses two sets of TM4C123 LaunchPads and audio booster packs, one running program `tm4c123_loop_intr.c` with a sampling frequency of 8 kHz and the other running program `tm4c123_sysid_CMSIS_intr.c` using a sampling frequency of 16 kHz. This allows it to identify frequency response characteristics in the range 0–8 kHz and to give a better idea of the passband, stopband, and transition band of the antialiasing and reconstruction filters on the system sampling at 8 kHz. In order to set the sampling frequency in program `tm4c123_sysid_CMSIS_intr.c` to 16 kHz, change the program statement that reads
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR
PGA_GAIN_6_DB);
to read
tm4c123_aic3104_init(FS_16000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR
PGA_GAIN_6_DB);
Additionally, change the number of adaptive filter coefficients used from 256 to 192 by changing the program statement that reads
#define NUM_TAPS 128
to read
#define NUM_TAPS 192
This is necessary due to the increased delay through two systems. Connect the two audio booster packs together as shown in Figure 2.46. Make sure that program `tm4c123_loop_intr.c` is running on one launchpad before running program `tm4c123_sysid_CMSIS_intr.c` for a short time on the other. Also, make sure that program `tm4c123_loop_intr.c` is using LINE IN (as opposed to MIC IN) as its input. After running and halting the program, save the 192 adaptive filter coefficients `firCoeffs32` used by program `tm4c123_sysid_CMSIS_intr.c` to a data file by typing
save filename <start address>, <start address + 0x300>
at the _Command_ line in the _MDK-ARM debugger_ , where `start address` is the address of array `firCoeffs32`, and plot using MATLAB function `tm4c123_logfft()`. You should see something similar to the plots shown in Figure 2.47.
**Figure 2.46** Connection diagram for program `tm4c123_sysid_CMSIS_intr.c`.
**Figure 2.47** The impulse response and magnitude frequency identified using program `tm4c123_sysid_CMSIS_intr.c` with connections as shown in Figure 2.46, displayed using MATLAB function `tm4c123_logfft()`. Sampling frequency 16,000 Hz, 192-coefficient adaptive filter.
The delay in the signal path identified (9 ms) is greater than that in Figure 2.42 (6 ms). This is consistent with the delay observed using program `tm4c123_loop_intr.c` in Example 2.6. Using 192 filter coefficients, the adaptive filter is able to identify an impulse response up to 192/16,000 = 12 ms long. Implementing a 192-coefficient adaptive filter at a sampling frequency of 16 kHz is just possible using a TM4C123 processor with a clock frequency of 84 MHz. This is evident from the oscilloscope trace shown in Figure 2.48, which shows the rectangular pulse output on GPIO pin PE2 by program `tm4c123_sysid_CMSIS_intr.c`. GPIO pin PE2 is held high during interrupt service routine function `SSI_interrupt_routine()`.
**Figure 2.48** Pulse output on GPIO pin PE2 by program `tm4c123_sysid_CMSIS_intr.c` running at a sampling rate of 16 kHz and using 192 adaptive filter coefficients.
## 2.10 Analog Output Using the STM32F407'S 12-BIT DAC
* * *
# Example 2.29
**Analog Waveform Generation Using a 12-Bit Instrumentation DAC (`stm32f4_sine8_DAC12_intr.c`).**
* * *
The STM32F407 processor features two 12-bit DACs that allow a comparison to be made with the DACs in the AIC3104 and WM5102 audio codecs. The analog output from one of the 12-bit DACs is routed to GPIO pin PA5 on the STM32F407 Discovery.
Programs `stm32f4_sine8_DAC12_intr.c`, `stm32f4_dimpulse_DAC12_intr.c`, `stm32f4_prbs_DAC12_intr.c`, and `stm32f4_square_DAC12_intr.c` are functionally equivalent to programs `stm32f4_sine8_intr.c`, `stm32f4_dimpulse_intr.c`, `stm32f4_prbs_intr.c`, and `stm32f4_square_intr.c` except in that they use the STM32F407's 12-bit DAC in place of that in the WM5102 codec. The resultant output waveforms are shown in Figures 2.49 through 2.50. Figure 2.49 shows the analog output signal generated by program stm32f4_sine8_DAC12_intr.c (Listing 2.54) writing eight sample values representing one cycle of a sinusoid to the 12-bit DAC. The frequency domain clearly shows frequency components at 1 kHz, 7 kHz, 9 kHz, 15 kHz, 23 kHz, and 25 kHz. The magnitudes of these components are modulated by a sinc function with nulls at integer multiples of 8 kHz, corresponding to the 125 µs duration, rectangular impulse response of the DAC. Note that the frequency-domain representation of a 1 kHz sinusoid sampled at a rate of 8 kHz is an infinite sequence of components of equal magnitudes at frequencies ( ) kHz, where is an integer .
**Figure 2.49** Output from program `stm32f4_sine8_dac12_intr.c` viewed using _Rigol DS1052 oscilloscope_.
**Figure 2.50** Output from program `stm32f4_dimpulse_dac12_intr.c` viewed using _Rigol DS1052 oscilloscope_.
The sinc function modulating the magnitudes of the discrete frequency components in Figure 2.49 is illustrated clearly in Figures 2.51 and 2.52. Compare the impulse response shown in Figure 2.50 with that in Figure 2.28 and the pseudorandom signal shown in Figure 2.51 with that in Figure 2.32. Both the DAC in the WM5102 codec and the DAC in the AIC3104 codec are close to ideal low-pass filters with cutoff frequencies of fs/2 (4 kHz). The low-pass characteristic of the 12-bit DAC in the STM32F407 is significantly less pronounced. Finally, compare the output waveform shown in Figure 2.52 with that in Figure 2.24. For comparison, the sample values written to the 12-bit DAC are written also to the WM5102 codec. Its analog output may be observed by connecting an oscilloscope to the (green) LINE OUT socket on the audio card.
**Figure 2.51** Output from program `stm32f4_prbs_dac12_intr.c` viewed using _Rigol DS1052 oscilloscope_.
**Figure 2.52** Output from program `stm32f4_square_dac12_intr.c` viewed using _Rigol DS1052 oscilloscope_.
* * *
# Listing 2.25 Program `stm32f4_sine8_DAC12bit_intr.c`
_// stm32f4_sine8_DAC12bit_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#define** LOOP_SIZE 8
int16_t sine_table[LOOP_SIZE] = {0, 7071, 10000, 7071,
0, -7071, -10000, -7071};
**static int** sine_ptr = 0;
**void** init_DAC12bit(void)
{
// _enable clock for DAC module and GPIO port A_
RCC->AHB1ENR|=RCC_AHB1ENR_GPIOAEN;
RCC->APB1ENR|=RCC_APB1ENR_DACEN;
// _configure GPIO pin PA5 as DAC output_
GPIOA->MODER|=GPIO_MODER_MODER5;
GPIOA->PUPDR&=∼(GPIO_PUPDR_PUPDR5);
// _enable DAC_
DAC->CR|=DAC_CR_EN2;
// _zero DAC output_
DAC->DHR12R2=0;
}
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, left_in_sample;
int16_t right_out_sample, right_in_sample;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
left_out_sample = sine_table[sine_ptr];
sine_ptr = (sine_ptr+1)
DAC->DHR12R2=(left_out_sample+10000)/7;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = 0;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
init_DAC12bit();
**while** (1){}
}
* * *
## References
1. 1 .Texas Instruments, Inc., "TLV320AIC3104 Low-Power Stereo Audio Codec for Portable Audio and Telephony", Literature no. SLAS510D, 2014.
2. 2 .Wolfson Microelectronics plc., "Audio Hub Codec with Voice Processor DSP", 2013.
3. 3 .Texas Instruments, Inc., "Dual-SPI Emulating I2S on TivaTM TM4C123x MCUs", Literature no. SPMA042B, 2013.
# Chapter 3
Finite Impulse Response Filters
## 3.1 Introduction to Digital Filters
Filtering is fundamental to digital signal processing. Commonly, it refers to processing a sequence of samples representing a time-domain signal so as to alter its frequency-domain characteristics, and often this consists of attenuating or filtering out selected frequency components. Digital filters are classified according to their structure as either nonrecursive, finite impulse response (FIR) filters, or as recursive, infinite impulse response (IIR) filters. This chapter is concerned with FIR filters. IIR filters are described in Chapter 4.
### 3.1.1 The FIR Filter
A generic FIR filter is shown in block diagram form in Figure 3.1. The component parts of the filter are follows:
1. A delay line, or buffer, in which a number of previous input samples are stored. At each sampling instant, the contents of the delay line are updated such that samples are shifted one position (to the right in the diagram) and a new input sample is introduced at the start of the delay line.
2. A number of blocks (multipliers) that multiply the samples stored in the delay line by a set of filter coefficients, .
3. A summing junction that sums the multiplier outputs to form the current filter output sample .
**Figure 3.1** Block diagram representation of a generic FIR filter.
In Figure 3.1, the delay line is represented by a series of blocks, each acting as a delay of one sampling period, that is, the output of each block in the delay line is its input, delayed by one sampling period. The _z_ -transfer function of a delay of one sample is . The multipliers and filter coefficients are represented by blocks, the outputs of which are their inputs multiplied by the filter coefficient with which they are labeled. At the th sampling instant, the samples stored in the delay line are , , ,..., and the output of the filter, is described by the difference equation
**3.1**
This equation is an example of a convolution sum representing the input-output relationship of a discrete-time, linear time-invariant (LTI) system having an FIR of length samples. The output of any LTI system (continuous- or discrete-time) is formed by convolving its input signal with its impulse response. For continuous-time LTI systems, there exists a corresponding convolution integral.
#### 3.1.1.1 Equivalence of FIR Filter Coefficients and Impulse Response
The impulse response of an FIR filter is equal to its coefficients. This is straightforward to visualize using the block diagram representation of the filter. Consider a unit impulse input sequence, that is, a sequence containing just one nonzero (unit) sample. That sample enters the delay line on the left-hand side of the block diagram shown in Figure 3.1 and is shifted right at each sampling instant. At any particular sampling instant, the output of the filter will comprise the unit sample multiplied by just one of the filter coefficients. All other filter coefficients will be multiplied by zero sample values from the delay line and will contribute nothing to the output at that sampling instant. Hence, the output sequence (the unit impulse response of the filter) will comprise the filter coefficients .
#### 3.1.1.2 Advantages and Disadvantages of FIR Filters
Although it is possible for FIR filters to approximate the characteristics of continuous-time analog filters, one of their advantages is that they may be used to implement arbitrary filter characteristics that are impossible to implement using analog circuits. For this reason, and unlike the IIR filters described in Chapter 4, their design is not based on the theory of analog filters. A disadvantage of FIR filtersis that their implementation may be computationally expensive. Obtaining an arbitrary filter characteristic to the required accuracy may require a large number of filter coefficients.
#### 3.1.1.3 FIR Filter Implementation
The structure and operation of an FIR filter are simple (and are a fundamental part of many DSP applications). Typically, the internal architecture of a digital signal processor is optimized (single instruction cycle multiply-accumulate units) for efficient computation of a sum of products or a convolution sum. For the convolution sum of Equation (3.1) to be computed directly, a DSP must have sufficient memory to store previous input samples and filter coefficients and have sufficient computational power to execute the required number of multiplications and additions within one sampling period. For large , the use of FFT-based fast convolution (described in Chapter 5) is computationally more efficient.
### 3.1.2 Introduction to the -Transform
The -transform is an important tool in the design and analysis of digital filters. It is the discrete-time counterpart of the Laplace transform. In the sense that the Laplace transform is a generalization of the continuous-time Fourier transform, the -transform is a generalization of the discrete-time Fourier transform (DTFT).
The Laplace transform is used to solve continuous-time, linear differential equations, representing them as algebraic expressions in the complex Laplace variable , and to represent continuous-time LTI systems as -transfer functions. The Laplace variable, , may also be viewed as an operator, representing differentiation with respect to time.
The -transform is used to solve discrete-time difference equations, representing them as algebraic expressions in the complex variable , and to represent discrete-time LTI systems as -transfer functions. The variable may also be viewed as an operator, representing a shift of one sample position in a sequence.
### 3.1.3 Definition of the -Transform
The -transform of a (discrete-time) sequence is defined as
**3.2**
where is a complex variable. This form of the -transform, applicable to a two-sided (noncausal) sequence, and hence also to left-sided (anticausal) and right-sided (causal) sequences, is referred to as the two-sided or bilateral -transform.
is a power series in containing as many terms as there are sample values in the sequence . For each term in , the coefficient corresponding to is equal to the _n_ th sample value in the sequence . In a discrete-time system, corresponds to the time , where is the sampling period. exists only for values of for which the power series converges, that is, values of for which .
#### 3.1.3.1 Relationship to the Discrete-Time Fourier Transform
The DTFT is the form of Fourier analysis applicable to a discrete-time sequence that is aperiodic and for which . The continuous, periodic representation of that signal in the frequency domain is given by
**3.3**
Sometimes, is represented as , emphasizing that it is evaluated for different values of the complex quantity , where .
Representing the complex variable in polar form , where and , and substituting for in Equation (3.2)
**3.4**
it is apparent that is the DTFT of . If (corresponding to a unit circle in the -plane), then the -transform of is equivalent to the DTFT of .
It is also apparent that the existence, or convergence, of is dependent upon the value of , that is, the magnitude of . If converges for a particular value of , it also converges for all other values of that lie on a circle of radius in the complex -plane.
* * *
# Example 3.1
**-Transform of Finite Sequence** .
* * *
From the definition of the -transform, the -transform of the right-sided (causal) sequence is
**3.5**
exists (converges) for all values of except .
* * *
# Example 3.2
**-Transform of Finite Sequence** .
* * *
From the definition of the -transform, the -transform of the two-sided (noncausal) sequence is
**3.6**
exists (converges) for all values of except and .
* * *
# Example 3.3
**-Transform of a Discrete Impulse Sequence** .
* * *
The -transform of the right-sided (causal) Kronecker delta sequence is
**3.7**
exists (converges) for all values of .
* * *
# Example 3.4
**-Transform of a Time-Shifted Discrete Impulse Sequence** , .
* * *
A time-shifted Kronecker delta sequence is described by
**3.8**
This is a left-sided (anticausal) sequence. From the definition of the -transform
**3.9**
exists (converges) for all values of except .
* * *
# Example 3.5
**-Transform of Exponential Function** .
* * *
The -transform of the right-sided (causal) sequence , where is the unit step sequence, is
**3.10**
Comparing this to the power series summation
**3.11**
Equation (3.10) may be written as
**3.12**
The inequality describes the range of values of for which exists, that is, its region of convergence (ROC). In this particular case, describes the part of the -plane that lies outside a circle of radius . exists (converges) for .
* * *
# Example 3.6
**-Transform of Exponential Function** .
* * *
This is a left-sided (anticausal) sequence that may appear to be of academic interest only but is included in order to make an important point. In this case,
**3.13**
Letting
**3.14**
The inequality describes the range of values of for which exists, that is, its ROC. In this particular case, describes the part of the -plane that lies inside a circle of radius . exists (converges) for .
Comparing (3.14) with (3.12), it is apparent that a similar algebraic expression for corresponds to two different sequences . Corresponding to each of these different sequences is a different ROC. The ROC is therefore an integral part of the representation of a signal in the -domain. In order to uniquely specify from , we must know its ROC.
* * *
# Example 3.7
**-Transform of the Unit Step Function** .
* * *
The unit step function may be viewed as an instance of Example 3.5, where , and hence, exists (converges) for .
**3.15**
The inequality describes the range of values of for which exists, that is, its ROC. In this particular case, describes the part of the -plane that lies outside a circle of radius .
* * *
# Example 3.8
**-Transform of a Sinusoidal Function** .
* * *
This function is right-sided or causal. A sinusoidal function may be represented by complex exponentials according to Euler's formula , that is,
**3.16**
and hence, the -transform of the sequence is given by
**3.17**
Using the result for with ,
**3.18**
exists (converges) for .
In the -plane, this function has a zero at the origin and two complex conjugate poles on the unit circle at angles . Its ROC is the entire -plane outside of, but not including, the unit circle.
Similarly, using Euler's formula to express as the sum of two complex exponentials, it can be shown that the -transform of the sequence is given by
**3.19**
#### 3.1.3.2 Regions of Convergence
The preceding examples illustrate some important properties of the -transform. Examples 3.5 and 3.6, for example, demonstrate that for a given -transform , more than one ROC may be possible, corresponding to more than one different time-domain sequence . In order to transform from the -domain back to the time domain, it is necessary to consider the ROC.
It is instructive to represent the poles and zeros of and the ROCs in Examples 3.5 and 3.6 graphically, as shown in Figures 3.2 and 3.3. In each case, has a zero at the origin and a pole at .
**Figure 3.2** Poles and zeros and region of convergence for causal sequence , , plotted in the -plane.
**Figure 3.3** Poles and zeros and region of convergence for anticausal sequence , , plotted in the -plane.
The two different ROCs for the -transform shown in the figures are consistent with the following ROC properties.
* An ROC is a single, connected region of the -plane.
* Since convergence of is dependent on the magnitude of , the boundaries of an ROC are circles centered on the origin of the -plane.
* Since regions of convergence correspond to , the poles of do not lie within its ROC.
* Right-sided (causal) sequences correspond to ROCs that extend outward from a circle drawn through the outermost pole of , that is, the pole with the greatest magnitude.
* Left-sided (anticausal) sequences correspond to ROCs that extend inward from a circle drawn through the innermost pole of , that is, the pole with the smallest magnitude.
* Two-sided (noncausal) sequences correspond to annular ROCs.
Examples 3.1 through 3.4 illustrate the property that if is finite in duration, then its ROC is the entire -plane except possibly or .
In Examples 3.5 and 3.6, has only one pole (at ) and, hence, the two possible ROCs (corresponding to causal and anticausal ) extend outward and inward from a circle of radius .
Figures 3.4 through 3.6 illustrate the case of a -transform that has more than one pole and for which more than two different ROCs, consistent with the properties listed earlier, are possible.
**Figure 3.4** Possible region of convergence, plotted in the -plane, corresponding to a right-sided causal sequence for a system with two real-valued poles.
**Figure 3.5** Possible region of convergence, plotted in the -plane, corresponding to a left-sided anticausal sequence for a system with two real-valued poles.
**Figure 3.6** Possible region of convergence, plotted in the -plane, corresponding to a two-sided noncausal sequence for a system with two real-valued poles.
#### 3.1.3.3 Regions of Convergence and Stability
An LTI system characterized by an impulse response is BIBO stable if is absolutely summable, that is, if
**3.20**
Given that the -transform of exists if
**3.21**
if exists for , then the DTFT of exists and the system is BIBO stable. In other words, if its ROC includes the unit circle, then the system represented by and is BIBO stable.
Consider again the example of the right-sided (causal) sequence for which the -transform converges if . Figures 3.7 through 3.9 show possible regions of convergence and corresponding sequences for , , and .
**Figure 3.7** Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is causal and stable.
**Figure 3.8** Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is causal and unstable.
**Figure 3.9** Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is causal and unstable.
For the left-sided (anticausal) sequence , the -transform converges if . Figures 3.10 through 3.12 show possible regions of convergence and corresponding sequences for , , and .
**Figure 3.10** Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is anticausal and stable.
Figure 3.11 Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is anticausal and unstable.
**Figure 3.12** Poles and zeros and region of convergence for plotted in the -plane, for . Corresponding sequence is anticausal and unstable.
#### 3.1.3.4 Poles and Zeros
In the case of LTI causal systems, may be expressed as a ratio of polynomials in and as such has poles and zeros (values of for which is equal to zero or ). The poles and zeros of are related to the region(s) of convergence of . In fact, we can deduce possible ROCs from the poles and zeros of according to the rules listed earlier. In most engineering applications, we are concerned with, and will encounter, causal sequences.
### 3.1.4 Properties of the -Transform
#### 3.1.4.1 Linearity
The -transform obeys the laws of superposition.
If and then , where and are arbitrary sequences and and are arbitrary constants.
#### 3.1.4.2 Shifting
For a time-shifted sequence where is any integer
**3.22**
From the definition of the z-transform,
**3.23**
Substituting ,
**3.24**
which is recognizable as
**3.25**
#### 3.1.4.3 Time Delay
Quantity in the -domain corresponds to a shift of sampling instants in the time domain. This is also known as the unit delay property of the -transform.
#### 3.1.4.4 Convolution
The forced output of an LTI system having impulse response and input is (as implemented explicitly by an FIR filter)
**3.26**
This is the _convolution sum_. Taking its -transform
**3.27**
Changing the order of summation
**3.28**
Letting ,
**3.29**
Hence,
**3.30**
that is, the -transform of the linear convolution of sequences and is equivalent to the product of the -transforms, and , of and (as shown in Figure 3.13).
**Figure 3.13** Time-domain and -domain block diagram representations of a discrete-time LTI system.
### 3.1.5 -Transfer Functions
The convolution property of the _z_ -transform is closely related to the concept of the -transfer function. The -transfer function of a discrete-time LTI system is defined as the ratio of the -transform of its output sequence, , to the -transform of its input sequence, . The -transform of a system output sequence is therefore the -transform of its input sequence multiplied by its -transfer function, that is, . Since the -transform of a unit impulse sequence is equal to unity, the -transfer function of a system is equal to the -transform of its impulse response.
### 3.1.6 Mapping from the -Plane to the -Plane
Consider the Laplace transform that is generally applied to causal systems. The Laplace transform can be used to determine the stability of a causal continuous-time, LTI system. If the poles of a system are to the left of the imaginary axis in the -plane, they correspond to exponentially decaying components of that system's response in the time domain and hence correspond to stability. Poles located in the right-hand half of the -plane correspond to components of that system's response in the time domain that increase exponentially and hence correspond to instability. Purely imaginary poles correspond to oscillatory (sinusoidal) system response components. The relationship between the -plane and the -plane is represented by the equation . Substituting for according to ,
**3.31**
The magnitude of is given by and its phase by . Consider the three regions of the -plane that determine system stability.
#### 3.1.6.1
The left-hand half of the -plane represents values of that have negative real parts, and this corresponds to values of that have magnitudes less than unity ( ). In other words, the left-hand half of the -plane maps to a region of the complex -plane inside the unit circle as shown in Figure 3.3. If the poles of a -transfer function lie inside that unit circle, then a causal system represented by that -transfer function will be stable.
#### 3.1.6.2
The right-hand half of the -plane represents values of that have positive real parts, and this corresponds to values of that have magnitudes greater than unity ( ). In other words, the right-hand half of the -plane maps to a region of the complex -plane outside the unit circle as shown in Figure 3.14. If the poles of a -transfer function lie outside that unit circle, then a causal system represented by that -transfer function will be unstable.
**Figure 3.14** Mapping from the -plane to the -plane.
#### 3.1.6.3
The imaginary axis in the -plane maps to the unit circle in the -plane. If the poles of a -transfer function lie on the unit circle in the -plane, then a causal system represented by that -transfer function will have an oscillatory response and is not considered stable.
This view of the relationship between the location of system poles in the -plane and system stability is, of course, consistent with consideration of whether or not the ROC includes the unit circle as described earlier. For causal systems, the ROC extends outward from the outermost pole, and for stability, the ROC must include the unit circle.
### 3.1.7 Difference Equations
A digital filter is represented by a difference equation in a way similar to that in which an analog filter is represented by a differential equation. A differential equation may be solved using Laplace transforms, whereas a difference equation may be solved using -transforms. In order to do this, the -transforms of a term , which corresponds to the th derivative with respect to time of analog signal , must be found. From its definition, the -transform of a right-sided, causal sequence is
**3.32**
The -transform of , which corresponds to a first-order derivative , is
**3.33**
where represents the initial condition associated with a first-order difference equation. Similarly, the -transform of , which corresponds to a second-order derivative , is
**3.34**
where and represent the two initial conditions associated with a second-order difference equation. In general,
**3.35**
If the initial conditions are all zero, then for and Equation (3.35) reduces to
**3.36**
### 3.1.8 Frequency Response and the -Transform
The frequency response of a discrete-time system can be found by evaluating its -transfer function for , where represents frequency in radians per second and represents sampling period in seconds. In other words, the frequency response of a system is found by evaluating of its -transfer function for values of that lie on the unit circle in the -plane and the result will be periodic in . It is common to express the frequency response of a discrete-time system as a function of normalized frequency over a range of radians. Evaluating a -transform for , that is, around the unit circle in the -plane corresponds to evaluating a Laplace transform for , that is, along the imaginary axis in the -plane. This was considered earlier where it was stated that the frequency response of a discrete-time system may be found by evaluating the DTFT of its impulse response. If represents the -transfer function of a discrete-time LTI system having an FIR of length , then evaluation of that expression using yields the system's frequency response.
**3.37**
### 3.1.9 The Inverse -Transform
In practice, the inverse -transform is best evaluated using tables of transform pairs, where first decomposed a complicated by partial fraction expansion (PFE).
## 3.2 Ideal Filter Response Classifications: LP, HP, BP, BS
Shown in Figure 3.15 are the magnitude frequency responses of ideal low-pass, high-pass, band-pass, and band-stop filters. These are some of the most common filter characteristics used in a range of applications.
**Figure 3.15** Ideal filter magnitude frequency responses. (a) Low-pass (LP). (b) High-pass (HP). (c) Band-pass (BP). (d) Band-stop (BS).
### 3.2.1 Window Method of FIR Filter Design
The window, or Fourier series, approach to FIR filter design comprises three basic steps.
1. Specify a desired frequency response.
2. Use inverse Fourier transformation to obtain a corresponding (discrete) impulse response.
3. Multiply that impulse response by a finite, tapered window function to obtain the FIR filter coefficients.
If the desired frequency response of the filter is specified as a continuous (periodic) function of frequency, the form of inverse Fourier analysis that will yield the discrete-time impulse response of the filter is the inverse discrete-time Fourier transform (IDTFT). In general, the inverse DTFT applied to a continuous frequency response will yield an infinite sequence in the time domain. Multiplication by a finite window function will truncate that sequence. A symmetrical tapered window function will reduce ripple (gain variation) in the resulting frequency response. Since the impulse response of an FIR filter is discrete, its frequency response will be periodic and therefore its desired frequency response needs to be specified over just one period ( radians of normalized frequency ).
Application of the inverse DTFT is relatively straightforward for some analytic frequency responses (expressed as algebraic functions of ) including the ideal filter characteristics shown in Figure 3.15, but for arbitrary frequency responses, applying the inverse DTFT may be problematic. In such cases, it is more practical to specify the desired frequency response of a filter as a discrete function of frequency and to compute a finite set of FIR filter coefficients using the inverse DFT.
### 3.2.2 Window Functions
A number of different tapered window functions are used in FIR filter design. All have the effect of reducing the magnitude of gain variations in the filter frequency response at the expense of a less sharp transition between pass and stop bands. These effects are related to the difference in magnitude between the peak and the first sidelobe, and the width of the central lobe, of the DTFT of the (discrete) window function itself.
#### 3.2.2.1 Indexing of Filter Coefficients
In a computer program, it is likely that FIR filter coefficients and window functions will be indexed . Alternatively, index may be considered over the range . The following examples involve type 1 FIR filters, that is, FIR filters having coefficients where is odd, , , and . The _order_ of such a filter is .
#### 3.2.2.2 Common Window Functions
The window functions described in what follows are among the most commonly used. A rectangular window simply truncates an IIR to yield a finite set of FIR filter coefficients.
##### Rectangular Window
The rectangular window function is
**3.38**
Compared with other window functions, a rectangular window has a narrow central lobe (corresponding to a sharp transition between pass and stop bands), but its first sidelobe is only 13 dB less than the peak of its central main lobe.
##### Hamming Window
The Hamming window function is
**3.39**
The magnitude of the first sidelobe is approximately 43 dB less than that of the main lobe.
##### Hanning Window
The Hanning window function is
**3.40**
The magnitude of the first sidelobe is approximately 31 dB less than that of the main lobe.
##### Blackman Window
The Blackman window function is
**3.41**
The magnitude of the first sidelobe is approximately 58 dB less than that of the main lobe. Although the Blackman window produces a greater reduction in sidelobe magnitude than does the Hamming or the Hanning window, it has a significantly wider main lobe. Used in the design of a filter, the Blackman window will reduce the ripple in the magnitude frequency response significantly but will result in a relatively gradual transition from pass band to stop band.
##### Kaiser Window
The Kaiser window is very popular for use in FIR filter design. It has a variable parameter to control the size of the sidelobe relative to the main lobe. The Kaiser window function is
**3.42**
where is an empirically determined variable and . is a modified Bessel function of the first kind defined by
**3.43**
which converges rapidly. A trade-off between the magnitude of the sidelobe and the width of the main lobe can be achieved by changing the length of the window, , and the value of the parameter .
The use of windows to reduce spectral leakage is discussed in Chapter 5.
* * *
# Example 3.9
**Design of an Ideal Low-Pass FIR Filter Using the Window Method.**
* * *
The ideal low-pass filter characteristic shown in Figure 3.16 is described by
**3.44**
and the inverse DTFT of Equation (3.44) is
**3.45**
for .
**Figure 3.16** Ideal low-pass frequency response defined over normalized frequency range .
This result is illustrated in Figure 3.17, for , over the range . In order to implement an FIR filter, impulse response must be truncated by multiplication with a window function of finite extent. Figure 3.18 shows the result of truncation using a rectangular window of length ( ). This has the effect of introducing gain variations (ripple) into the corresponding frequency response as shown in Figure 3.19. This continuous (periodic) frequency response is found by taking the (forward) DTFT of the truncated impulse response shown in Figure 3.18.
**Figure 3.17** Sixty-one of the infinite number of values in the discrete-time impulse response obtained by taking the inverse DTFT of the ideal low-pass frequency response of Figure 3.16.
**Figure 3.18** The discrete-time impulse response of Figure 3.17 truncated to values.
**Figure 3.19** The continuous, periodic magnitude frequency response obtained by taking the DTFT of the truncated impulse response shown in Figure 3.18 (plotted against normalized frequency ).
Multiplying the impulse response of Figure 3.17 by a tapered window function has the effect of reducing the ripple in the magnitude frequency response at the expense of making the transition from pass band to stop band less sharp. Figures 3.20–3.21 show a 33-point Hanning window function, the result of multiplying the impulse response (filter coefficients) of Figure 3.19 by that window function, and the magnitude frequency response corresponding to the filter coefficients shown in Figure 3.22, respectively.
**Figure 3.20** A 33-point Hanning window.
**Figure 3.21** The magnitude frequency response corresponding to the filter coefficients of Figure 3.22 (plotted against normalized frequency ).
**Figure 3.22** The filter coefficients of Figure 3.17 multiplied by the Hanning window of Figure 3.20.
Figure 3.23 shows the magnitude frequency responses of Figures 3.19 and 3.21 plotted together on a logarithmic scale. This emphasizes the wider main lobe and suppressed sidelobes associated with the Hanning window.
**Figure 3.23** The magnitude frequency responses of Figures 3.19 and 3.21 plotted on a logarithmic scale, against normalized frequency .
Finally, it is necessary to shift the time-domain filter coefficients. The preceding figures show magnitude frequency responses that are even functions of frequency and for which zero phase shift is specified. These correspond to real-valued filter coefficients that are even functions of time but are noncausal. This can be changed by introducing a delay and indexing the coefficients from 0 to 32 rather than from 16 to 16. This has no effect on the magnitude but introduces a linear phase shift to the frequency response of the filter.
### 3.2.3 Design of Ideal High-Pass, Band-Pass, and Band-Stop FIR Filters Using the Window Method
#### 3.2.3.1 Ideal High-Pass Filter
The ideal high-pass filter characteristic shown in Figure 3.24 is described by
**3.46**
in the range .
**Figure 3.24** Ideal high-pass filter magnitude frequency response.
and the inverse DTFT of Equation (3.46) is
**3.47**
for .
#### 3.2.3.2 Ideal Band-Pass Filter
The ideal band-pass filter characteristic shown in Figure 3.25 is described by
**3.48**
in the range .
**Figure 3.25** Ideal band-pass filter magnitude frequency response.
and the inverse DTFT of equation (3.48) is
**3.49**
for .
#### 3.2.3.3 Ideal band-stop filter
The ideal band-stop filter characteristic shown in Figure 3.26 is described by
**3.50**
in the range .
**Figure 3.26** Ideal band-stop filter magnitude frequency response.
and the inverse DTFT of Equation (3.50) is
**3.51**
for .
High-pass, band-pass, and band-stop filters may be designed using the window method described for the low-pass filter, but substituting Equations (3.47), (3.49), or (3.51) for Equation (3.45).
## 3.3 Programming Examples
The following examples illustrate the real-time implementation of FIR filters using C and functions from the CMSIS DSP library for the ARM Cortex-M4 processor. Several different methods of assessing the magnitude frequency response of a filter are presented.
* * *
# Example 3.10
**Moving Average Filter (`stm32f4_average_intr.c`).**
* * *
The moving average filter is widely used in DSP and arguably is the easiest of all digital filters to understand. It is particularly effective at removing (high-frequency) random noise from a signal or at smoothing a signal.
The moving average filter operates by taking the arithmetic mean of a number of past input samples in order to produce each output sample. This may be represented by the equation
**3.52**
where represents the th sample of an input signal and the th sample of the filter output. The moving average filter is an example of convolution using a very simple filter kernel, or impulse response, comprising coefficients each of which is equal to . Equation (3.52) may be thought of as a particularly simple case of the more general convolution sum implemented by an FIR filter and introduced in Section 3.1, that is,
**3.53**
where the FIR filter coefficients are samples of the filter impulse response, and in the case of the moving average filter, each is equal to . As far as implementation is concerned, at the th samplinginstant, we could either
1. multiply past input samples individually by and sum the products,
2. sum past input samples and multiply the sum by , or
3. maintain a moving average by adding a new input sample (multiplied by ) to and subtracting the th input sample (multiplied by ) from a running total.
The third method of implementation is recursive, that is, calculation of the output makes use of a previous output value . The recursive expression
**3.54**
is an instance of the general expression for a recursive or IIR filter
**3.55**
Program `stm32f4_average_intr.c`, shown in Listing 3.11, uses the first of these options, even though it may not be the most computationally efficient. The value of defined near the start of the source file determines the number of previous input samples to be averaged.
* * *
# Listing 3.1 Program `stm32f4_average_intr.c.`
_// stm32f4_average_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#define** N 5
float32_t h[N];
float32_t x[N];
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
int16_t i;
float32_t yn = 0.0;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
x[0] = (float32_t)(left_in_sample);
**for** (i=0 ; i<N ; i++) yn += h[i]*x[i];
**for** (i=(N-1) ; i>0 ; i--) x[i] = x[i-1];
left_out_sample = (int16_t)(yn);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = 0;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
**int** i;
**for** (i=0 ; i<N ; i++) h[i] = 1.0/N;
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1);
}
* * *
Several different methods exist by which the characteristics of the five-point moving average filter may be demonstrated. A test file `mefsin.wav` contains a recording of speech corrupted by the addition of a sinusoidal tone. Listen to this file using _Goldwave_ , _Windows Media Player_ , or similar. Then connect the PC soundcard line output to the (green) LINE IN socket on the Wolfson audio card and listen to the filtered test signal. With program `stm32f4_average_intr.c` running, you should find that the sinusoidal tone has been blocked and that the speech sounds muffled. Both observations are consistent with the filter having a low-pass frequency response.
A more rigorous method of assessing the magnitude frequency response of the filter is to use a signal generator and an oscilloscope or spectrum analyzer to measure its gain at different individual frequencies. Using this method, it is straightforward to identify two distinct notches in the magnitude frequency response at 1600 Hz (corresponding to the tone in test file `mefsin.wav`) and at 3200 Hz.
The theoretical frequency response of the filter can be found by taking the discrete-time Fourier transform (DTFT) of its coefficients.
**3.56**
Evaluated over the frequency range , where , is frequency in radians per second, and is the sampling period in seconds. In this case,
**3.57**
and hence
**3.58**
The theoretical magnitude frequency response of the filter is illustrated in Figure 3.27. This is the magnitude of a Dirichlet, or periodic sinc, function.
**Figure 3.27** Theoretical magnitude frequency response of the five-point moving average filter (sampling rate 8 kHz).
* * *
# Example 3.11
**Moving Average Filter with Internally Generated Pseudorandom Noise as Input (`stm32f4_average_prbs_intr.c`).**
* * *
An alternative method of assessing the magnitude frequency response of a filter is to use wideband noise as an input signal.
Program `stm32f4_average_prbs_intr.c` demonstrates this technique. A pseudorandom binary sequence (PRBS) is generated within the program (see program `tm4c123_prbs_intr.c` in Chapter 2) and used as an input to the filter in lieu of samples read from the ADC. The filtered noise can be viewed on a spectrum analyzer, and whereas the frequency content of the PRBS input is uniform across all frequencies, the frequency content of the filtered noise corresponds to the magnitude frequency response of the filter. Figure 3.28 shows the output of program `stm32f4_average_prbs_intr.c` displayed using the FFT function of a _Rigol DS1052E_ oscilloscope and using _Goldwave_. Compare these plots with the theoretical magnitude frequency response shown in Figure 3.27.
**Figure 3.28** Magnitude frequency response of the five-point moving average filter demonstrated using program `stm32f4_average_prbs_intr.c` and displayed using (a) _Rigol DS1052E_ oscilloscope (lower trace) and (b) _Goldwave_.
* * *
# Example 3.12
**Identification of Moving Average Filter Frequency Response Using an Adaptive Filter`(tm4c123_sysid_CMSIS_intr.c)`).**
* * *
In Chapter 2, program `tm4c123_sysid_CMSIS_intr.c` was used to identify the characteristics of the antialiasing and reconstruction filters of a codec. Here, the same program is used to identify the characteristics of a moving average filter. For this example, two sets of hardware connected as shown in Figure 3.29 are required. On one of the launchpads, run program `tm4c123_average_intr.c`, and on the other, run program `tm4c123_sysid_CMSIS_intr.c.` After program `tm4c123_sysid_CMSIS_intr.c` has run for a few seconds, halt the program and save the values of the 256 adaptive filter coefficients `firCoeffs32` to a file by typing
save <filename.dat> <start address>, <start address + 0x400>
at the _Command_ line in the _MDK-ARM debugger_ , where `start address` is the address of array `firCoeffs32`, and plot them using MATLAB® function `tm4c123_logfft()`.
**Figure 3.29** Connection diagram for use of program `tm4c123_sysid_CMSIS_intr.c` to identify the characteristics of a moving average filter implemented using two sets of hardware.
The number of adaptive filter coefficients used by the program is set by the preprocessor command
#define NUM_TAPS 256
You should see something similar to what is shown in Figures 3.30 and 3.31, that is, the impulse response and magnitude frequency response identified by the adaptive filter.
**Figure 3.30** Impulse response of the five-point moving average filter identified using two launchpads and booster packs and programs `tm4c123_sysid_CMSIS_intr.c` and `tm4c123_average_intr.c.`
**Figure 3.31** Magnitude frequency response of the five-point moving average filter identified using two sets of hardware and programs `tm4c123_sysid_CMSIS_intr.c` and `tm4c123_average_intr.c`.
The impulse response shown in Figure 3.30 differs from the theoretical (rectangular) impulse response of the moving average filter because it combines that with the responses of the reconstruction and antialiasing filters in two AIC3104 codecs and the ac coupling of the LINE IN and LINE OUT connections on the audio booster packs. The oscillations before and after transitions in the waveform are similar to those identified in Example 2.52 and shown in Figure 2.47.
In the magnitude frequency response shown in Figure 3.31, the discrepancies between theoretical and measured responses at frequencies greater than 3.5 kHz and at very low frequencies correspond to the characteristics of the antialiasing and reconstruction filters in the two AIC3104 codecs and to the ac coupling of the LINE IN and LINE OUT connections on the audio booster packs, respectively.
* * *
# Example 3.14
**Identification of Moving Average Filter Frequency Response Using a Single Audio Booster Pack (`tm4c123_sysid_average_CMSIS_intr.c`).**
* * *
Program `tm4c123_sysid_average_CMSIS_intr.c`, shown in Listing 3.15, collapses the signal path considered in the previous example onto just one set of hardware, as shown in Figure 3.32. Build and run the program, save the 256 adaptive filter coefficients `firCoeffs32` to a file, and plot them using MATLAB function `tm4c123_logfft()`. The results should differ only subtly from those shown in Figures 3.30 and 3.31, because the identified signal path contains just one antialiasing filter and one reconstruction filter (as opposed to two of each). However, the delay before the peak in the impulse response identified should be shorter than the 12 ms apparent in Figure 3.30.
**Figure 3.32** Connection diagram for program `tm4c123_sysid_average_CMSIS_intr.c`.
* * *
# Listing 3.2 Program `tm4c123_sysid_average_CMSIS_intr.c.,`
_// tm4c123_sysid_average_CMSIS_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#define** BETA 1E-11
**#define** NUM_TAPS 256
**#define** BLOCK_SIZE 1
**#define** N 5
float32_t x[N];
float32_t h[N];
float32_t firStateF32[BLOCK_SIZE + NUM_TAPS -1];
float32_t firCoeffs32[NUM_TAPS] = {0.0};
arm_lms_instance_f32 S;
**void** SSI_interrupt_routine(void)
{
AIC3104_data_type sample_data;
float32_t adapt_in, adapt_out, desired;
float32_t error, input_left, input_right;
float32_t yn = 0.0f;
int16_t i;
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
adapt_in = (float32_t)(prbs(8000));
arm_lms_f32(&S, &adapt_in, &input_left, &adapt_out,
&error, BLOCK_SIZE);
x[0] = adapt_in;
**for** (i=0 ; i<N ; i++) yn += h[i]*x[i];
**for** (i=(N-1) ; i>0 ; i--) x[i] = x[i-1];
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
sample_data.bit32 = ((int16_t)(yn));
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main()
{
int16_t i;
**for** (i=0 ; i<N ; i++) h[i] = 1.0/N;
arm_lms_init_f32(&S, NUM_TAPS, firCoeffs32,
firStateF32, BETA, BLOCK_SIZE);
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1);
}
* * *
### 3.3.1 Altering the Coefficients of the Moving Average Filter
The frequency response of the moving average filter can be changed by altering the number of previous input samples that are averaged. Modify program `tm4c123_average_prbs_intr.c` so that it implements an eleven-point moving average filter, by changing the preprocessor command that reads
#define N 5
to read
#define N 11
Build and run the program and verify that the frequency response of the filter has changed to that shown in Figure 3.33. Alternatively, you can make a similar change to the number of points in the moving average filter in program `tm4c123_sysid_average_CMSIS_intr.c`.
**Figure 3.33** Magnitude frequency response of an eleven-point moving average filter implemented using program `tm4c123_average_prbs_intr.c` and displayed using _Goldwave_.
The frequency response of the eleven-point moving average filter has the same form as that of the five-point moving average filter but the notches in the frequency response occur at integer multiples of (8000/11) Hz, that is at 727, 1455, 2182, and 2909 Hz.
The frequency response of the filter can also be changed by altering the relative values of the coefficients. Modify program `tm4c123_sysid_average_CMSIS_intr.c` again, changing the preprocessor command and program statements that read
#define N 11
float h[N];
to read
#define N 5
float h[N] = {0.0833, 0.2500, 0.3333. 0.2500, 0.0833};
and comment out the following program statement
for (i=0 ; i<N ; i++) h[i] = 1.0/N;
Build and run the program and observe the frequency response of the filter using _Goldwave_ (in the case of program `tm4c123_average_prbs_intr.c`) or by saving and plotting filter coefficients `firCoeffs32` (in the case of program `tm4c123_sysid_average_CMSIS_intr.c`). You should find that the high-frequency components of the input signal (pseudorandom noise) have been attenuated more than before and also that the notches at 1600 and 3200 Hz have disappeared as shown in Figure 3.34. You have effectively applied a Hanning window to the coefficients of the five-point moving average filter.
**Figure 3.34** Magnitude frequency response of a five-point moving average filter with Hanning window implemented using program `stm32f4_average_prbs_intr.c` and displayed using _Goldwave_.
The -point Hanning window is described by the equation
**3.59**
and hence, for and , . Since there is no point in including two zero-value coefficients in the FIR filtering operation, in this example, the five nonzero values of a seven-point Hanning window function, rather than the five values, including two zero values, of a five-point Hanning window function, have been used.
The important, if rather obvious, point illustrated by this example, however, is that a five-coefficient FIR filter may exhibit different frequency response characteristics, depending on the values of its coefficients. The theoretical magnitude frequency response of the filter may be found by taking the DTFT of its coefficients.
**3.60**
Hence,
**3.61**
The measured frequency responses of the five-point moving average filter and of its windowed version may be interpreted as demonstrating the frequency-domain characteristics of rectangular and Hanning windows as discussed in Section 3.2.2. Specifically, the Hanning window has a wider main lobe and relatively smaller sidelobes than a rectangular window.
* * *
# Example 3.14
**FIR Filter with Filter Coefficients Specified in Separate Header Files (`stm32f4_fir_intr.c` and `tm4c123_fir_intr.c`).**
* * *
The algorithm used by programs `stm32f4_fir_intr.c` and `tm4c123_fir_intr.c` to calculate each output sample are identical to those employed by programs `stm32f4_average_intr.c` and `tm4c123_average_intr.c`. The interrupt service routine functions `SPI2_IRQHandler()` and `SSI_interrupt_routine()` have exactly the same definitions in each program. However, programs `stm32f4_average_intr.c` and `tm4c123_average_intr.c` calculated the values of their filter coefficients in function `main()`, whereas programs `stm32f4_fir_intr.c` (shown in Listing 3.17) and `tm4c123_fir_intr.c` read the values of their filter coefficients from separate header files.
* * *
# Listing 3.3 Program `stm32f4_fir_intr.c`
_// stm32f4_fir_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#include** "maf5.h"
float32_t x[N];
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
int16_t i;
float32_t yn = 0.0;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
x[0] = (float32_t)(prbs(8000));
**for** (i=0 ; i<N ; i++) yn += h[i]*x[i];
**for** (i=(N-1) ; i>0 ; i--) x[i] = x[i-1];
left_out_sample = (int16_t)(yn);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = 0;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
#### 3.3.1.1 Five-Point Moving Average (`maf5.h`)
Coefficient file `maf5.h` is shown in Listing 3.18. Using that header file, programs `stm32f4_fir_intr.c` and `tm4c123_fir_intr.c` implement the same five-point moving average filter implemented by program `stm32f4_average_intr.c` in Example 3.10. The number of filter coefficients is specified by the value of the constant `N`, defined in the header file, and the coefficients are specified as the initial values in an `N` element array, `h`, of type `float32_t`. Build and run program `stm32f4_fir_intr.c` and verify that it implements a five-point moving average filter.
* * *
# Listing 3.4 Coefficient header file `maf5.h`
_// maf5.h_
_// this file was generated using function stm32f4_fir_coeffs.m_
**#define** N 5
float32_t h[N] = {
2.0000E-001,2.0000E-001,2.0000E-001,2.0000E-001,2.0000E-001
};
* * *
#### 3.3.1.2 Low-Pass Filter, Cutoff at 2000 Hz (`lp55.h`)
Edit source file `stm32f4_fir_intr.c` or `tm4c123_fir_intr.c`, changing the preprocessor command that reads
#include ave5.h
to read
#include lp55.h
Build and run the program. Use a signal generator connected to the (pink) LINE IN socket on the Wolfson audio card to input a sinusoidal signal and verify that this is attenuated significantly at the (green) LINE OUT socket if its frequency is greater than 2 kHz.
#### 3.3.1.3 Band-Stop Filter, Centered at 2700 Hz (`bs2700.h`)
Edit source file `stm32f4_fir_intr.c`, changing the line that reads
#include ave5.h
to read
#include bs2700.h
Build and run program `stm32f4_fir_intr.c` or `tm4c123_fir_intr.c`. Input a sinusoidal signal and vary the input frequency slightly below and above 2700 Hz. Verify that the magnitude of the output is a minimum at 2700 Hz. The values of the coefficients for this filter were calculated using the MATLAB filter design and analysis tool, `fdatool`, as shown in Figure 3.35.
**Figure 3.35** MATLAB `fdatool` window corresponding to design the of an FIR band-stop filter centered at 2700 Hz.
#### 3.3.1.4 Band-Pass Filter, Centered at 1750 Hz (`bp1750.h`)
Edit source file `stm32f4_fir_intr.c` or `tm4c123_fir_intr.c` again to include the coefficient file `bp1750.h` in place of `bs2700.h`. File `bp1750.h` represents an FIR band-pass filter (81 coefficients) centered at 1750 Hz, as shown in Figure 3.36. Again, this filter was designed using `fdatool`. Build and run the program again and verify that it implements a band-pass filter centered at 1750 Hz.
**Figure 3.36** MATLAB `fdatool` window corresponding to design of FIR band-pass filter centered at 1750 Hz.
### 3.3.2 Generating FIR Filter Coefficient Header Files Using MATLAB
If the number of filter coefficients is small, the coefficient header file may be edited by hand. To be compatible with programs `stm32f4_fir_intr.c` and `tm4c123_fir_intr.c`, a coefficient file must define constant `N` and declare and initialize the contents of an array `h`, containing `N` floating point values. For larger numbers of coefficients, the MATLAB function `stm32f4_fir_coeffs()`, supplied as file `stm32f4_fir_coeffs.m`, or the MATLAB function `tm4c123_fir_coeffs()`, supplied as file `tm4c123_fir_coeffs.m`, can be used. Function `stm32f4_fir_coeffs()`, shown in Listing 3.19, should be passed a MATLAB vector of coefficient values and will prompt the user for an output filename. For example, the coefficient file `maf5.h`, shown in Listing 3.18, was created by typing the following at the MATLAB command prompt:
>> x = [0.2, 0.2, 0.2, 0.2, 0.2];
>> stm32f4_fir_coeffs(x)
enter filename for coefficients maf5.h
Note that the coefficient filename must be entered in full, including the suffix `.h`. Alternatively, the MATLAB filter design and analysis tool `fdatool` can be used to calculate FIR filter coefficients and to export them to the MATLAB workspace. Then function `stm32f4_fir_coeffs()` or `tm4c123_fir_coeffs()` can be used to create a coefficient header file compatible with programs `stm32f4_fir_intr.c` and `tm4c123_fir_intr.c`.
* * *
# Listing 3.5 MATLAB m-file `stm32f4_fir_coeffs.m`
% STM32F4_FIR_COEFFS.M
% MATLAB function to write FIR filter coefficients
% in format suitable for use in STM32F407 Discovery programs
% stm32f4_fir_intr.c and stm32f4_fir_prbs_intr.c
% written by Donald Reay
%
function stm32f4_fir_coeffs(coeff)
coefflen=length(coeff);
fname = input('enter filename for coefficients ','s');
fid = fopen(fname,'wt');
fprintf(fid,'// %s\n',fname);
fprintf(fid,'// this file was generated using ');
fprintf(fid,'function stm32f4_fir_coeffs.m\n');
fprintf(fid,'\n#define N %d\n',coefflen);
% j is used to count coefficients written to current line
% in output file
fprintf(fid,'\nfloat32_t h[N] = { \n');
j=0;
% i is used to count through coefficients
**for** i=1:coefflen
% **if** six coeffs have been written to current line
% then start new line
**if** j>5
j=0;
fprintf(fid,'\n');
end
% **if** this is the last coefficient then simply write
% its value to the current line
% **else** write coefficient value, followed by comma
**if** icoefflen
fprintf(fid,'%2.4E',coeff(i));
**else**
fprintf(fid,'%2.4E,',coeff(i))
j=j+1;
end
end
fprintf(fid,'\n};\n');
fclose(fid);
}
* * *
* * *
# Example 3.15
**FIR Implementation with Pseudorandom Noise as Input (`tm4c123_fir_prbs_intr.c`).**
* * *
Program `tm4c123_fir_prbs_intr.c`, shown in Listing 3.21, implements an FIR filter and uses an internally generated pseudorandom noise sequence as input. In all other respects, it is similar to program `tm4c123_fir_intr.c`. The coefficient file `bs2700.h` is used initially.
* * *
# Listing 3.6 Program `tm4c123_fir_prbs_intr.c`
_// tm4c123_fir_prbs_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "bs2700.h"
float32_t x[N];
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
int16_t i;
float32_t yn = 0.0f;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
x[0] = (float32_t)(prbs(8000));
**for** (i=0 ; i<N ; i++) yn += h[i]*x[i];
**for** (i=N-1 ; i>0 ; i--) x[i] = x[i-1];
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
sample_data.bit32 = ((int16_t)(yn));
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIDataPut(SSI0_BASE,sample_data.bit32);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
#### 3.3.2.1 Running the Program
Build and run the program and verify that the output signal is pseudorandom noise filtered by an FIR band-stop filter centered at 2700 Hz. This output signal is shown using _GoldWave_ and using the FFT function of a _Rigol DS1052E_ oscilloscope in Figure 3.37.
**Figure 3.37** Output generated using program `tm4c123_fir_prbs_intr.c` and coefficient file `bs2700.h` displayed using (a) _Rigol DS1052E_ oscilloscope and (b) _GoldWave_.
##### Testing Different FIR Filters
Edit the C source file `tm4c123_fir_prbs_intr.c` to include and test different coefficient files representing different FIR filters. Each of the following coefficient files, except `comb14.h`, contains 55 coefficients.
1. `bp55.h`: band-pass with center frequency
2. `bs55.h`: band-stop with center frequency
3. `lp55.h`: low-pass with cutoff frequency
4. `hp55.h`: high-pass with cutoff frequency
5. `pass2b.h`: band-pass with two pass bands
6. `pass3b.h`: band-pass with three pass bands
7. `pass4b.h`: band-pass with four pass bands
8. `comb14.h`: multiple notches (comb filter)
Figure 3.38(a) shows the filtered noise output by an FIR filter with two pass bands, using the coefficient file `pass2b.h`. Figure 3.38(b) shows the filtered noise output by a high-pass FIR filter using the coefficient file `hp55.h`. In the cases of high-pass and band-stop filters in particular, the low-pass characteristic of the reconstruction filter in the AIC3104 codec is apparent.
**Figure 3.38** Output generated using program `tm4c123_fir_prbs_intr.c` using coefficient files (a) `pass2b.h` and (b) `hp55.h`.
* * *
# Example 3.16
**FIR Filter with Internally Generated Pseudorandom Noise as Input and Output Stored in Memory (`stm32f4_fir_prbs_buf_intr.c`).**
* * *
This example extends the previous one by storing the 256 most recent output samples in memory. Program `stm32f4_fir_prbs_buf_intr.c` is shown in Listing 3.23. The coefficient file `bp1750.h` represents an 81-coefficient FIR band-pass filter centered at 1750 Hz.
* * *
# Listing 3.7 Program `stm32f4_fir_prbs_buf_intr.c`
_// stm32f4_fir_prbs_buf_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#include** "bp1750.h"
**#define** YNBUFLENGTH 256
float32_t ynbuffer[YNBUFLENGTH];
int16_t ynbufptr = 0;
float32_t x[N];
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, right_out_sample;
int16_t left_in_sample, right_in_sample;
int16_t i;
float32_t yn = 0.0;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
x[0] = (float32_t)(prbs(8000));
**for** (i=0 ; i<N ; i++) yn += h[i]*x[i];
**for** (i=(N-1) ; i>0 ; i--) x[i] = x[i-1];
left_out_sample = (int16_t)(yn);
ynbuffer[ynbufptr] = yn;
ynbufptr = (ynbufptr+1) % YNBUFLENGTH;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
right_out_sample = 0;
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
#### 3.3.2.2 Running the Program
Build and run the program. Verify that the output signal is bandlimited noise. Then halt the program and save the contents of array `ynbuffer` to a data file by typing
save <filename.dat> <start address>, <start address + 0x400>
where `start` address is the address of array `ynbuffer`. Use MATLAB function `stm32f4_logfft()` in order to display the frequency content of the 256 stored output samples, as shown in Figure 3.39 (Figure 3.40).
**Figure 3.39** Magnitude of the FFT of the output from program `stm32f4_fir_prbs_buf_intr.c` using coefficient header file `bp1750.h`.
**Figure 3.40** Filter coefficients used in program `stm32f4_fir_prbs_buf_intr.c` (`bp1750.h`).
Figure 3.41 shows the magnitude of the FFT of the `bp1750.h` filter coefficients for comparison.
**Figure 3.41** Magnitude of the FFT of the filter coefficients used in program `stm32f4_fir_prbs_buf_intr.c`.
Program `stm32f4_fir_prbs_buf_intr.c` allows the user to switch the signal written to the WM5102 DAC between filtered and unfiltered noise so as to emphasize the action of the filter. The filter is toggled on and off by pressing the (blue) user pushbutton on the Discovery board.
* * *
# Example 3.17
**Effects on Voice or Music Using Three FIR Low-Pass Filters (`tm4c123_fir3lp_intr.c`).**
* * *
Listing 3.25 show program `stm32f4_fir3lp_intr.c`, which implements three different FIR low-pass filters with cutoff frequencies at 600, 1500, and 3000 Hz. Filter coefficients designed using MATLAB are read from file `fir3lp_coeffs.h` and, during initialization, copied into a single, two-dimensional array `h`. While the program is running, variable `FIR_number` selects the desired low-pass filter to be implemented. For example, if `FIR_number` is set to 0, `h[0][i]` is set equal to `hlp600[i]`, that is, the set of coefficients representing a low-pass filter with a cutoff frequency of 600 Hz. The value of `FIR_number` can be cycled through the values 0 through 2 to implement the 600, 1500, or 3000 Hz low pass filter, using switch SW1 on the launchpad while the program is running.
* * *
# Listing 3.8 Program `tm4c123_fir3lp_intr.c`
_// tm4c123_fir3lp_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "L138_fir3lp_coeffs.h"
float32_t x[N];
float32_t h[3][N];
int16_t FIR_number = 0;
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
float32_t input_left, input_right;
int16_t i;
float32_t yn = 0.0f;
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
x[0] = input_left;
**for** (i=0 ; i<N ; i++) yn += h[FIR_number][i]*x[i];
**for** (i=(N-1) ; i>0 ; i--) x[i] = x[i-1];
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
sample_data.bit32 = ((int16_t)(yn));
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main( **void** )
{
int16_t i;
**for** (i=0; i<N; i++)
{
x[i] = 0.0;
h[0][i] = hlp600[i];
h[1][i] = hlp1500[i];
h[2][i] = hlp3000[i];
}
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1)
}
ROM_SysCtlDelay(10000);
**if** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4))
{
ROM_SysCtlDelay(10000);
FIR_number = (FIR_number+1) % 3;
**while** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4)){}
}
}
}
* * *
As supplied, the program configures the AIC3104 codec to accept input from the (blue) LINE IN socket on the audio booster pack. In order to test the effect of the filters using a microphone as an input device, change the program statement that reads
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
to read
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_MIC_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
The effect of the filters is particularly striking if applied to musical input. Alternatively, the effects of the filters can be illustrated using an oscilloscope and a signal generator. Figure 3.42 shows a 200 Hz square wave that has been passed through the three different low-pass filters. The slope on the sections of the waveforms between transitions is due to the ac coupling of the LINE OUT and LINE IN connections on the audio booster pack.
**Figure 3.42** A 200 Hz square wave passed through three different low-pass filters implemented using program `tm4c123_fir3lp_intr.c`.
The magnitude frequency response of the three different filters may be observed using _Goldwave_ and by changing the program statement that reads
x[0] = input_left;
to read
x[0] = (float32_t)(prbs(8000));
or, alternatively, by blowing gently on the microphone.
* * *
# Example 3.18
**Implementation of Four Different Filters: Low-Pass, High-Pass, Band-Pass, and Band-Stop (`tm4c123_fir4types_intr.c`).**
* * *
This example is very similar to the previous one but illustrates the effects of low-pass, high-pass, band-pass, and band-stop FIR filters. The filter type may be changed while program `tm4c123_fir4types_intr.c` is running using switch SW1 on the launchpad. All four 81-coefficient filters were designed using MATLAB. They are
1. Low-pass filter, with bandwidth of 1500 Hz.
2. High-pass filter, with bandwidth of 2200 Hz.
3. Band-pass filter, with center frequency at 1750 Hz.
4. Band-stop filter, with center frequency at 790 Hz.
As in the previous example, the effects of the four different filters on musical input are particularly striking. Figure 3.43 shows the magnitude frequency response of the FIR band stop filter centered at 790 Hz, tested using the file `stereonoise.wav` played through a PC sound card as input.
**Figure 3.43** Output generated using program `tm4c123_fir_4types_intr.c`.
* * *
# Example 3.19
**Two Notch Filters to Recover a Corrupted Speech Recording (`tm4c123_notch2_intr.c`).**
* * *
This example illustrates the use of two notch (band-stop) FIR filters in series to recover a speech recording corrupted by the addition of two sinusoidal signals at frequencies of 900 and 2700 Hz. Program `tm4c123_notch2_intr.c` is shown in Listing 3.28. Header file `notch2_coeffs.h` contains the coefficients for two FIR notch (band-stop) filters in arrays `h900` and `h2700`. The output of the first notch filter, centered at 900 Hz, is used as the input to the second notch filter, centered at 2700 Hz. Build and run the program. The file `corrupt.wav` contains a recording of speech corrupted by the addition of 900 and 2700 Hz sinusoidal tones. Listen to this file using _GoldWave_ , _Windows Media Player_ , or similar. Then connect the PC sound card output to the (blue) LINE IN socket on the audio booster pack and listen to the filtered test signal on (black) LINE OUT or (green) HP OUT connections. Switch SW1 on the launchpad can be used to select the output of either the first or the second of the notch filters. Compare the results of this example with those obtained in Example 3.10 in which a notch in the magnitude frequency response of a moving average filter was exploited in order to filter out an unwanted sinusoidal tone. In this case, the filtered speech may sound brighter because the notch filters used here do not have an overall low-pass characteristic. Figure 3.44 shows the output of the filter using pseudorandom noise as an input signal.
**Figure 3.44** Pseudorandom noise filtered using program `tm4c123_notch2_intr.c`.
* * *
# Listing 3.9 Program `tm4c123_notch2_intr.c`
_// tm4c123_notch2_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "notch2_coeffs.h"
float32_t x[N][2]; // filter delay lines
int16_t out_type = 0;
AIC3104_data_type sample_data;
**void** SSI_interrupt_routine(void)
{
float32_t input_left, input_right;
int16_t i;
float32_t yn[2];
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
x[0][0] = input_left;
yn[0] = 0.0; // _compute filter 1 output_
**for** (i = 0; i< N; i++) yn[0] += h900[i]*x[i][0];
x[0][1] = (yn[0]);
yn[1] = 0.0; // _compute filter 2 output_
**for** (i = 0; i< N; i++) yn[1] += h2700[i]*x[i][1];
**for** (i = N-1; i > 0; i--) // shift delay lines
{
x[i][0] = x[i-1][0];
x[i][1] = x[i-1][1];
}
sample_data.bit32 = ((int16_t)(yn[out_type]));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1)
{
ROM_SysCtlDelay(10000);
**if** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4))
{
ROM_SysCtlDelay(10000);
out_type = (out_type+1) %2;
**while** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4)){}
}
}
}
* * *
* * *
# Example 3.20
**Voice Scrambling Using Filtering and Modulation (`tm4c123_scrambler_intr.c`).**
* * *
This example illustrates a voice scrambling and descrambling scheme. The approach makes use of basic algorithms for filtering and modulation. Modulation was introduced in the AM example in Chapter 2. With voice as input, the resulting output is scrambled voice. The original descrambled voice is recovered when the scrambled voice is used as the input to a second system running the same program. The scrambling method used is commonly referred to as frequency inversion. It takes an audio range, in this case 300 Hz to 3 kHz, and "folds" it about a 3.3 kHz carrier signal. The frequency inversion is achieved by multiplying (modulating) the audio input by a carrier signal, causing a shift in the frequency spectrum with upper and lower sidebands. In the lower sideband, which represents the audible speech range, the low tones are high tones, and vice versa.
Figure 3.45 shows a block diagram of the scrambling scheme. At point A, the input signal has been bandlimited (low pass filtered) to 3 kHz. At point B, a double-sideband signal with suppressed carrier has been formed. At point C, the upper sideband and the section of the lower sideband between 3 and 3.3 kHz are filtered out. The scheme is attractive because of its simplicity. Only simple DSP algorithms, namely filtering, sine wave generation and amplitude modulation are required for its implementation. Listing 3.30 is of program `tm4c123_scrambler_intr.c`, which operates at a sampling rate of 16 kHz. The input signal is first low-pass filtered using an FIR filter with 65 coefficients, stored in array `h`, and defined in the file `lp3k64.h`. The filtering algorithm used is identical to that used in, for example, programs `tm4c123_fir_intr.c` and `stm32f4_fir_intr.c`. The filter delay line is implemented using array `x1` and the output is assigned to variable `yn1`. The filter output (at point A in Figure 3.45) is multiplied (modulated) by a 3.3 kHz sinusoid stored as 160 samples (exactly 33 cycles) in array `sine160` (read from file `sine160.h`) . Finally, the modulated signal (at point B) is low-pass filtered again, using the same set of filter coefficients `h` (`lp3k64.h`) but a different filter delay line implemented using array `x2` and the output variable `yn2`. The output is a scrambled signal (at point C). Using this scrambled signal as the input to a second system running the same algorithm, the original descrambled input may be recovered.
**Figure 3.45** Block diagram representation of scrambler implemented using program `tm4c123_scrambler_intr.c`.
#### 3.3.2.3 Running the Program
Build and run the program. First, test the program using a 2 kHz sine wave as input. The resulting output is a lower sideband signal at 1.3 kHz. The upper sideband signal at 5.3 kHz is filtered out by the second low-pass filter. By varying the frequency of the sinusoidal input, you should be able to verify that input frequencies in the range 300–3000 Hz appear as output frequencies in the inverted range 3000–300 Hz.
* * *
# Listing 3.10 Program `tm4c123_scrambler_intr.c`
_// tm4c123_scrambler_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "sine160.h" // 3300 Hz sinusoid
**#include** "lp3k64.cof" // low-pass filter coefficients
**float** xa[N],xb[N]; // filter delay lines
**int** sine_ptr = 0; // pointer to sinusoid samples
AIC3104_data_type sample_data;
**void** SSI_interrupt_routine(void)
{
float32_t input_left, input_right;
float32_t yn;
int16_t i;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input_left = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input_right = (float32_t)(sample_data.bit16[0]);
xa[0] = (input_left); // filter a
yn = 0.0;
**for** (i=0 ; i<N ; i++) yn += h[i]*xa[i];
**for** (i=(N-1) ; i>0 ; i--) xa[i] = xa[i-1];
yn *= sine160[sine_ptr]; // _mix with 3300 Hz_
sine_ptr = (sine_ptr+1) % NSINE;
xb[0] = yn; // _filter b_
yn = 0.0;
**for** (i=0 ; i<N ; i++) yn += h[i]*xb[i];
**for** (i=(N-1) ; i>0 ; i--) xb[i] = xb[i-1];
sample_data.bit32 = ((int16_t)(yn));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
A second hardware system running the same program can be used to recover the original signal (simulating the receiving end). Use the output of the first audio card as the input to the second. In order to test the scrambler and descrambler using speech from a microphone as the input, change the program statement that reads
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
to read
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_MIC_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
at the transmitting end.
Connect LINE OUT (black) on the transmitting end system (scrambler) to LINE IN (blue) on the receiving end system (descrambler). Interception and descrambling of the scrambled speech signal could be made more difficult by changing the modulation frequency dynamically and by including (or omitting) the carrier frequency according to a predefined sequence.
* * *
# Example 3.21
**FIR filter implemented using DMA-based i/o (`tm4c123_fir_dma.c` and `stm32f4_fir_dma.c`).**
* * *
Programs `tm4c123_fir_dma.c`, `stm32f4_fir_dma.c`, `tm4c123_fir_prbs_dma.c` and `stm32f4_fir_prbs_dma.c` have similar functionality to programs `tm4c123_fir_intr.c`, `stm32f4_fir_intr.c`, `tm4c123_fir_prbs_intr.c` and `stm32f4_fir_prbs_intr.c` but use DMA-based as opposed to interrupt-based i/o (as illustrated previously in Examples 2.5 and 2.6). As supplied, they implement band-pass filters centered on 1750 Hz. The filter characteristics implemented by the programs can be changed by including different coefficient header files.
* * *
# Example 3.22
**FIR Filter Implemented Using a CMSIS DSP Library Function (`tm4c123_fir_prbs_CMSIS_dma.c` and `stm32f4_fir_prbs_CMSIS_dma.c`).**
* * *
Function `arm_fir_f32()` supplied as part of the CMSIS DSP library is an optimized floating-point implementation of an FIR filter. The function is passed a block of input samples and computes a corresponding block of output samples, and hence, it is suited to DMA-based i/o (although it is possible to set the size of the block of samples to one and to call the function in a program using interrupt-based i/o). Apart from using the CMSIS DSP library function, programs `tm4c123_fir_prbs_CMSIS_dma.c` and `stm32f4_fir_prbs_CMSIS_dma.c` (shown in Listing 3.33) are similar to programs `tm4c123_fir_prbs_dma.c` and `stm32f4_fir_prbs_dma.c`.
#### 3.3.2.4 Number of Sample Values in Each DMA Transfer
The number of sample values in each DMA transfer is set in header files `stm32f4_wm5102_init.h` and `tm4c123_aic3104_init.h` by the value of the constant `BUFSIZE`. However, in the example programs in this book and as described in Chapter 2, whereas the TM4C123 is configured so that four DMA transfers take place concurrently (one in each direction for each of the two audio channels L and R), whereas STM32F4 is configured so that two DMA transfers take place concurrently (one in each direction, but each one transferring both L and R channel sample values). In each case, the value of the constant `BUFSIZE` determines the number of 16-bit values per DMA transfer.
In the case of TM4C123, each DMA transfer block processed by function `Lprocess_buffer()` contains `BUFSIZE` 16-bit L channel samples and one call to function `arm_fir_f32()` processes these `BUFSIZE` sample values.
In the case of STM32F4, each DMA transfer block processed by function `process_buffer()` contains `BUFSIZE/2` 16-bit L channel samples interleaved with `BUFSIZE/2` 16-bit R channel samples and one call to function `arm_fir_f32()` is used to process `BUFSIZE/2` L channel sample values.
* * *
# Listing 3.11 Program `stm32f4_fir_prbs_CMSIS_dma.c`
_// stm32f4_fir_prbs_CMSIS_dma.c_
**#include** "stm32f4_wm5102_init.h"
**#include** "bp1750.h"
**extern** uint16_t pingIN[BUFSIZE], pingOUT[BUFSIZE];
**extern** uint16_t pongIN[BUFSIZE], pongOUT[BUFSIZE];
**int** rx_proc_buffer, tx_proc_buffer;
**volatile int** RX_buffer_full = 0;
**volatile int** TX_buffer_empty = 0;
float32_t x[BUFSIZE/2], y[BUFSIZE/2], state[N+(BUFSIZE/2)-1];
arm_fir_instance_f32 S;
**void** DMA1_Stream3_IRQHandler()
{
**if** (DMA_GetITStatus(DMA1_Stream3,DMA_IT_TCIF3))
{
DMA_ClearITPendingBit(DMA1_Stream3,DMA_IT_TCIF3);
**if** (DMA_GetCurrentMemoryTarget(DMA1_Stream3))
rx_proc_buffer = PING;
**else**
rx_proc_buffer = PONG;
RX_buffer_full = 1;
}
}
**void** DMA1_Stream4_IRQHandler()
{
**if** (DMA_GetITStatus(DMA1_Stream4,DMA_IT_TCIF4))
{
DMA_ClearITPendingBit(DMA1_Stream4,DMA_IT_TCIF4);
**if** (DMA_GetCurrentMemoryTarget(DMA1_Stream4))
tx_proc_buffer = PING;
**else**
tx_proc_buffer = PONG;
TX_buffer_empty = 1;
}
}
**void** process_buffer()
{
**int** i;
uint16_t *rxbuf, *txbuf;
**if** (rx_proc_buffer PING)
rxbuf = pingIN;
**else**
rxbuf = pongIN;
**if** (tx_proc_buffer PING)
txbuf = pingOUT;
**else**
txbuf = pongOUT;
_// place BUFSIZE/2 prbs values in x[]_
**for** (i=0 ; i<(BUFSIZE/2) ; i++)
{
x[i] = (float32_t)(prbs(8000));
}
_// compute BUFSIZE/2 filter output values in y[]_
arm_fir_f32(&S,x,y,BUFSIZE/2);
_// write BUFSIZE/2 samples to output channels_
**for** (i=0 ; i<(BUFSIZE/2) ; i++)
{
*txbuf++ = (int16_t)(y[i]);
*txbuf++ = (int16_t)(y[i]);
}
TX_buffer_empty = 0;
RX_buffer_full = 0;
}
**int** main( **void** )
{
arm_fir_init_f32(&S, N, h, state, BUFSIZE/2);
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_DMA);
**while** (1)
{
**while** (!(RX_buffer_full && TX_buffer_empty)){}
GPIO_SetBits(GPIOD, GPIO_Pin_15);
process_buffer();
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
}
}
* * *
* * *
# Example 3.23
**Comparison of Execution Times for Three Different FIR Filter Implementations (`tm4c123_fir3ways_intr.c`).**
* * *
A straightforward method of measuring the time taken to compute each FIR filter output sample is to toggle a GPIO output pin setting it high in a program statement immediately preceding computation and resetting it low in a program statement immediately following computation. Most of the example programs in this chapter do this. On the TM4C123 Launchpad, GPIO pin PE2 is used, and on the STM32F407 Discovery, GPIO pin PD15 is used.
Figure 3.46 shows the signal output by program `tm4c123_fir_prbs_intr.c` on GPIO pin PE2. This program uses interrupt-based i/o and the rectangular pulse is repeated every , reflecting the 8-kHz sampling frequency. The duration of the pulse, that is , indicates that the program takes that time in order to compute the value of each output sample value. The higher the order of the FIR implemented by this program (as determined by the coefficient header file used), the longer it will take to compute each output sample value. In order for the program to work, that computation time must be less than the sampling period.
**Figure 3.46** Pulses output on GPIO pin PE2 by programs `tm4c123_fir_prbs_intr.c` and `tm4c123_fir_prbs_dma.c`.
The duration of the pulses output on GPIO pin PE2 by program `tm4c123_fir_prbs_dma.c`, which uses DMA-based i/o, indicates the time taken to compute a block of `BUFSIZE` output sample values. These pulses are repeated every `BUFSIZE*125` µs. The higher the order of the FIR implemented by this program (as determined by the coefficient header file used), the longer it will take to compute `BUFSIZE` output sample values. In order for the program to work, that computation time must be less than `BUFSIZE` times the sampling period. The duration of the pulse shown in Figure 3.46 is 3.52 ms, which, given that the value of `BUFSIZE` in this example was equal to 256, represents a time of to compute the value of each output sample.
The program statements used to implement the FIR filtering operation affect its execution time. Program `tm4c123_fir3ways_intr.c`, shown in Listing 3.35, gives the user the option of switching between different FIR filter implementations while the program is running. Using user switch SW1 on the TM4C123 LaunchPad, the user can cycle through three alternatives.
* * *
# Listing 3.12 Program `tm4c123_fir3ways_intr.c`
_// tm4c123_fir3ways_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "bp1750.h"
**#define** NUM_METHODS 3
float32_t x[2*N];
int16_t k = 0;
int16_t METHOD_number = 0;
AIC3104_data_type sample_data;
float32_t inputl, inputr;
**void** SSI_interrupt_routine(void)
{
int16_t i;
float32_t yn = 0.0;
SSIDataGet(SSI1_BASE,&sample_data.bit32);
inputl = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
inputr = (float32_t)(sample_data.bit16[0]);
**switch** (METHOD_number)
{
**case** 0:
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
x[0] = (float32_t)(prbs(8000));
**for** (i=0 ; i<N ; i++) yn += h[i]*x[i];
**for** (i=N-1 ; i>0 ; i--) x[i] = x[i-1];
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
**break** ;
**case** 1:
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
x[k++] = (float32_t)(prbs(8000));
**if** (k>= N) k = 0;
**for** (i=0 ; i<N ; i++)
{
yn += h[i]*x[k++];
**if** (k>= N) k = 0;
}
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
**break** ;
**case** 2:
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
x[k] = (float32_t)(prbs(8000));
x[k+N] = x[k];
k = (k+1) % N;
**for** (i=0 ; i<N ; i++) yn += h[i]*x[k+i];
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
**break** ;
}
sample_data.bit32 = ((int16_t)(yn));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main( **void** )
}
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1)
{
ROM_SysCtlDelay(10000);
**if** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4))
{
ROM_SysCtlDelay(10000);
METHOD_number = (METHOD_number+1) % NUM_METHODS;
**while** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4)){}
}
}
}
* * *
The first implementation method is straightforward and uses two separate loops. The first loop
for (i=0 ; i< N ; i++) yn += h[i]*x[i];
is used in order to compute the convolution sum of the `N` previous input samples stored in the filter delay line `x` and its `N` filter coefficients `h`, placing the result in `yn`. The second loop
for (i=N-1 ; i>0 ; i--) x[i] = x[i-1];
is used to shift the contents of the filter delay line `x` by one. Intuitively, it is wasteful of computational effort to repeatedly move each input sample from one memory location to another. On the other hand, the computational effort involved in that straightforward operation is unlikely to be great.
The second implementation method
for (i=0 ; i<N ; i++)
{
yn += h[i]*x[k++];
if (k>= N) k = 0;
}
involves treating array `x` as a circular buffer in which to store input sample values. Once a sample has been stored in array `x`, it is not moved. Variable `k` is used to keep track of where in array `x` the most recent input sample is stored. The value of `k` is incremented once per sampling instant. Each time the value of `k` is incremented, its value is tested, and if greater than or equal to `N`, it is reset to zero. The value of `k` is also incremented `N` times during computation of the convolution sum returning to the same value it started at (before computation of the convolution sum). This implementation method uses just one loop but requires that the value of `k` is tested `(N+1)` times in total.
The third implementation method
for (i=0 ; i<N ; i++) yn += h[i]*x[k+i];
eliminates the need to test the value of `k` (`N` times) during computation of the convolution sum, at the expense of requiring twice as much memory to store input sample values. Each input sample value is stored in two different locations, `x[k]` and `x[k+N]`, in an array `x` of length `2`. Effectively, this is an alternative method of implementing circular buffering.
#### 3.3.2.5 Running the Program
Build and run the program and observe the pulses output on GPIO pin PE2 using an oscilloscope. Press user switch SW1 on the launchpad to cycle through the three different implementation methods. In the case of an 81-coefficient FIR filter, defined in header file `bp1750.h`, the three different implementation methods take 13.7, 16.0, and to compute each output sample value.
* * *
# Example 3.24
**Comparison of Execution Times for FIR Filters Implemented in C and Using CMSIS DSP library function`arm_fir_f32()`.**
* * *
CMSIS DSP library function `arm_fir_f32()` is an efficient method of implementing an FIR filter and was demonstrated in Example 3.32. The duration of the pulse output on GPIO pin PE2 by program `tm4c123_fir_prbs_CMSIS_dma.c` is 936 µs (`BUFSIZE = 256`), indicating that it takes approximately 3.6 µs to compute the value of each output sample. It is most computationally efficient to implement an FIR filter using DMA-based i/o to provide blocks of input data to the CMSIS library function `arm_fir_f32()`. However, this approach incurs a greater real-time delay (latency) than a sample-by-sample interrupt-based approach.
# Chapter 4
Infinite Impulse Response Filters
The FIR filter discussed in Chapter 3 has no analog counterpart. In this chapter, we discuss the infinite impulse response (IIR) filter that, typically, makes use of the vast knowledge that exists concerning analog filters. The design procedure described in this chapter involves the conversion of an analog filter into an equivalent discrete filter. Either the impulse invariance or bilinear transformation (BLT) technique may be used to effect that conversion. Both procedures convert the transfer function of an analog filter in the -domain into an equivalent discrete-time transfer function in the -domain.
## 4.1 Introduction
Consider a general input–output equation of the form
**4.1**
or, equivalently,
**4.2**
This recursive difference equation represents an IIR filter. The output , at instant , depends not only on the current input , at instant , and on past inputs , ,..., , but also on past outputs , ,..., . If we assume all initial conditions to be zero in Equation (4.2), its -transform is
**4.3**
Letting in (4.3), the transfer function of the IIR filter is
**4.4**
where and represent the numerator and denominator polynomials, respectively. Multiplying and dividing by , becomes
**4.5**
where is a constant is a transfer function with zeros and poles. If all of the coefficients in Equation (4.5) are equal to zero, this transfer function reduces to a transfer function with poles at the origin in the -plane representing the FIR filter discussed in Chapter 3. For a causal discrete-time system to be stable, all the poles of its -transfer function must lie inside the unit circle, as discussed in Chapter 3. Hence, for an IIR filter to be stable, the magnitude of each of its poles must be less than 1, or
1. If , then , as , yielding a stable system.
2. If , then , as , yielding an unstable system.
3. If , the system is marginally stable, yielding an oscillatory response.
## 4.2 IIR Filter Structures
Several different structures may be used to represent an IIR filter.
### 4.2.1 Direct Form I Structure
Using the direct form I structure shown in Figure 4.1, the filter in Equation (4.2) can be realized. For an th-order filter, this structure contains delay elements, each represented by a block labeled . For example, a second-order filter with will contain four delay elements.
**Figure 4.1** Direct form I IIR filter structure.
### 4.2.2 Direct Form II Structure
The direct form II structure shown in Figure 4.2 is one of the structures most commonly used to represent an IIR filter. It requires half as many delay elements as direct form I. For example, a second-order filter requires two delay elements, as opposed to four with the direct form I structure. From the block diagram of Figure 4.2, it can be seen that
**4.6**
and that
**4.7**
Taking -transforms of Equations (4.6) and (4.7)
**4.8**
and hence,
**4.9**
and
**4.10**
Thus
**4.11**
which is similar to Equation (4.5).
**Figure 4.2** Direct form II IIR filter structure.
The direct form II structure can be represented by difference Equations (4.6) and (4.7) taking the place of Equation (4.2). Equations (4.6) and (4.7) may be used to implement an IIR filter in a computer program. Initially, are set to zero. At instant , a new sample is acquired. Equation (4.6) is used to solve for and then the output is calculated using Equation (4.7).
### 4.2.3 Direct Form II Transpose
The direct form II transpose structure shown in Figure 4.3 is a modified version of the direct form II structure and requires the same number of delay elements.
**Figure 4.3** Direct form II transpose IIR filter structure.
From inspection of the block diagram, it is apparent that the filter output can be computed using
**4.12**
Subsequently, the contents of the delay line can be updated using
**4.13**
and
**4.14**
and so on until finally
**4.15**
Using Equation (4.13) to find ,
**4.16**
Equation (4.12) becomes
**4.17**
Similarly, using Equation (4.14) to find ,
**4.18**
Equation (4.12) becomes
**4.19**
Continuing this procedure until Equation (4.15) has been used, it can be shown that Equation (4.12) is equivalent to Equation (4.2) and hence that the block diagram of Figure 4.3 is equivalent to those of Figures 4.1 and 4.2. The transposed structure implements the zeros of the filter first and then the poles, whereas the direct form II structure implements the poles first.
### 4.2.4 Cascade Structure
The transfer function in Equation (4.5) can be factorized as
**4.20**
in terms of first- or second-order transfer functions, . This cascade (or series) structure is shown in Figure 4.4. An overall transfer function can be represented with cascaded transfer functions. For each section, either the direct form II structure or its transpose version can be used. Figure 4.5 shows a fourth-order IIR structure in terms of two direct form II second-order sections in cascade. The transfer function , in terms of cascaded second-order transfer functions, can in this case be written as
**4.21**
**Figure 4.4** Cascade form IIR filter structure.
**Figure 4.5** Fourth-order IIR filter with two direct form II sections in cascade.
where the constant in Equation (4.20) is incorporated into the coefficients. For example, if for a fourth-order transfer function, then Equation (4.18) becomes
**4.22**
as can be verified in Figure 4.5. From a mathematical standpoint, proper ordering of the numerator and denominator factors does not affect the output result. However, from a practical standpoint, proper ordering of each second-order section can minimize quantization noise. Note that the output of the first section, , becomes the input to the second section. With an intermediate output result stored in one of the registers, a premature truncation of the intermediate output becomes negligible. A programming example later in this chapter will illustrate the implementation of an IIR filter using cascaded second-order direct form II sections.
### 4.2.5 Parallel Form Structure
The transfer function in Equation (4.11) can be represented as
**4.23**
which can be obtained using a partial fraction expansion (PFE) of Equation (4.11). This parallel form structure is shown in Figure 4.6. Each of the transfer functions can be either first- or second-order function.
**Figure 4.6** Parallel form IIR filter structure.
As with the cascade structure, the parallel form can efficiently be represented in terms of second-order direct form II structure sections. can be expressed as
**4.24**
For example, for a fourth-order transfer function, in Equation (4.24) becomes
**4.25**
This fourth-order parallel structure is represented in terms of two direct form II sections as shown in Figure 4.7. From that figure, the output can be expressed in terms of the output of each section, or
**4.26**
Typically, th-order IIR filters are implemented as cascaded second-order sections.
**Figure 4.7** Fourth-order IIR filter with two direct form II sections in parallel.
## 4.3 Impulse Invariance
This method of IIR filter design is based on the concept of mapping each -plane pole of a continuous-time filter to a corresponding -plane pole using the substitution for in . This can be achieved by several different means. PFE of and substitution for can involve a lot of algebraic manipulation. An equivalent method of making the transformation is to use tables of Laplace and -transforms. Generally, tables of Laplace transforms list -domain transfer functions and their corresponding impulse responses. Tables of -transforms may be used to find the -transfer function corresponding to an impulse response. The method is referred to as impulse invariance because of the equivalence of the impulse responses of the digital filter (described by -transfer function) and of the analog prototype (described by -transfer function). The specific relationship between the two impulse responses is that one comprises samples of a scaled version of the other. The performance of the two filters may differ, however, depending on how well the detail of the continuous impulse response of the analog prototype is represented by its sampled form. As will be illustrated in Section 4.5, if the sampling rate of the digital filter is not sufficiently high to capture the detail of continuous-time impulse response, then the high-frequency characteristics of the prototype filter may not be reproduced in the digital implementation.
## 4.4 BILINEAR TRANSFORMATION
The BLT is the most commonly used technique for transforming an analog filter into a digital filter. It provides one-to-one mapping from the analog -plane to the digital -plane, using the substitution
**4.27**
The constant in Equation (4.27) is commonly chosen as , where represents the sampling period in seconds, of the digital filter. Other values for can be selected, as described in Section 4.4.1. The BLT allows the following:
1. The left region in the -plane, corresponding to , maps _inside_ the unit circle in the -plane.
2. The right region in the -plane, corresponding to , maps _outside_ the unit circle in the -plane.
3. The imaginary axis in the -plane maps _on_ the unit circle in the -plane.
Let and represent analog and digital frequencies, respectively. With and , Equation (4.27) becomes
**4.28**
Using Euler's formulae for sine and cosine in terms of complex exponential functions, in Equation (4.28) becomes
**4.29**
which relates the analog frequency to the digital frequency . This relationship is plotted in Figure 4.8 for positive values of . The nonlinear compression of the entire analog frequency range into the digital frequency range from zero to is referred to as frequency warping ( ).
**Figure 4.8** Relationship between analog and digital frequencies, and , due to frequency warping in the bilinear transform.
### 4.4.1 Bilinear Transform Design Procedure
The BLT design procedure for transforming an analog filter design expressed as a transfer function into a -transfer function representing a discrete-time IIR filter is described by
**4.30**
can be chosen according to well-documented analog filter design theory, for example, Butterworth, Chebyshev, Bessel, or elliptic. It is common to choose . Alternatively, it is possible to prewarp the analog filter frequency response in such a way that the bilinear transform maps an analog frequency , in the range 0– , to exactly the same digital frequency . This is achieved by choosing
**4.31**
## 4.5 Programming Examples
The examples in this section introduce and illustrate the implementation of IIR filtering. Many different approaches to the design of IIR filters are possible, and most often, IIR filters are designed with the aid of software tools. Before using such a design package, and in order to appreciate better what such design packages do, a simple example will be used to illustrate some of the basic principles of IIR filter design.
### 4.5.1 Design of a Simple IIR Low-Pass Filter
Traditionally, IIR filter design is based on the concept of transforming a continuous-time, or analog, design into the discrete-time domain. Butterworth, Chebyshev, Bessel, and elliptic classes of analog filters are widely used. In this example, a second-order, type 1 Chebyshev, low-pass filter with 2 dB of pass-band ripple and a cutoff frequency of 1500 Hz (9425 rad/s) is used.
The continuous-time transfer function of this filter is
**4.32**
and its frequency response is shown in Figure 4.9.
**Figure 4.9** (a) Magnitude frequency response of filter . (b) Phase response of filter .
Using MATLAB®, the coefficients of this -transfer function may be generated by typing
>> [b,a] = cheby1(2,2,2*pi*1500,'s');
at the command line. Our task is to transform this design into the discrete-time domain. One method of achieving this is the impulse invariance method.
#### 4.5.1.1 Impulse Invariance Method
Starting with the filter transfer function of Equation (4.32), we can make use of the Laplace transform pair
**4.33**
(the -transfer function of the filter is equal to the Laplace transform of its impulse response) and use the values
Hence, the impulse response of the filter in this example is given by
**4.34**
The -transform pair
**4.35**
yields the following discrete-time transfer function when we substitute for , , and set in Equation (4.35).
**4.36**
From , the following difference equation may be derived.
**4.37**
With reference to Equation (4.2), we can see that , , , and .
In order to apply the impulse invariant method using MATLAB, type
>> [b,a] = cheby1(2,2,2*pi*1500,'s');
>> [bz,az] = impinvar(b,a,8000);
This discrete-time filter has the property that its discrete-time impulse response is equal to samples of the continuous-time impulse response , (scaled by the sampling period, ), as shown in Figure 4.10. Although it is evident from Figure 4.10 that the discrete-time impulse response decays almost to zero, this sequence is not finite. It is perhaps worth noting that, counterintuitively, the definition of an IIR filter is not that its impulse response is infinite in duration but rather that it makes use of previous output sample values in order to calculate its current output. In theory, it is possible for an IIR filter to have a finite impulse response. Whereas the impulse response of an FIR filter is given explicitly by its finite set of coefficients, the coefficients of an IIR filter are used in a recursive equation (4.1) to determine its impulse response .
**Figure 4.10** Impulse responses (scaled by sampling period ) and of continuous-time filter and its impulse-invariant digital implementation.
* * *
# Example 4.1
**Implementation of an IIR Filter Using Cascaded Second-Order Direct Form II Sections (`stm32f4_iirsos_intr.c`).**
* * *
Program `stm32f4_iirsos_intr.c`, shown in Listing 4.1, implements a generic IIR filter using cascaded direct form II second-order sections, and coefficient values stored in a separate header file. Each section of the filter is implemented using the following two program statements.
wn = input - a[section][1]*w[section][0]
- a[section][2]*w[section][1];
yn = b[section][0]*wn + b[section][1]*w[section][0]
+ b[section][2]*w[section][1];
which correspond to the equations
**4.38**
and
**4.39**
With reference to Figure 4.5 and to (4.18), the coefficients are stored by the program as `a[i][0]`, `a[i][1]`, `a[i][2]`, `b[i][0]`, `b[i][1]`, and `b[i][2]`, respectively. `w[i][0]` and `w[i][1]` correspond to and in Equations (4.38) and (4.39).
* * *
# Listing 4.1 IIR filter program using second-order sections in cascade (`stm32f4_iirsos_intr.c`)
_// stm32f4_iirsos_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#include** "elliptic.h"
**float** w[NUM_SECTIONS][2] = {0};
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, left_in_sample;
int16_t right_out_sample, right_in_sample;
int16_t section; // _second order section number_
float32_t input; // _input to each section_
float32_t wn, yn; // _intermediate and output values_
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
input =(float32_t)(left_in_sample);
**for** (section=0 ; section< NUM_SECTIONS ; section++)
{
wn = input - a[section][1]*w[section][0]
- a[section][2]*w[section][1];
yn = b[section][0]*wn + b[section][1]*w[section][0]
+ b[section][2]*w[section][1];
w[section][1] = w[section][0];
w[section][0] = wn;
input = yn;
}
left_out_sample = (int16_t)(yn);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
right_out_sample = 0;
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
The impulse invariant filter may be implemented using program `stm32f4_iirsos_intr.c` by including the coefficient header file `impinv.h`, shown in Listing 4.2. The number of cascaded second-order sections is defined as `NUM_SECTIONS` in that file.
* * *
# Listing 4.2 Coefficient header file `impinv.h`
_// impinv.h_
_// second-order type 1 Chebyshev LPF with 2 dB pass-band ripple_
_// and cutoff frequency 1500 Hz_
**#define** NUM_SECTIONS 1
**float** b[NUM_SECTIONS][3]={ {0.0, 0.48255, 0.0} };
**float** a[NUM_SECTIONS][3]={ {1.0, -0.71624, 0.387913} };
* * *
Build and run the program. Using a signal generator and oscilloscope to measure the magnitude frequency response of the filter, you should find that the attenuation of frequencies above 2500 Hz is not very pronounced. This is due to both the low order of the filter and the inherent shortcomings of the impulse-invariant design method. A number of alternative methods of assessing the magnitude frequency response of the filter will be described in the next few examples. In common with most of the example programs described in this chapter, program `stm32f4_iirsos_intr.c` uses interrupt-based i/o. A DMA-based i/o version of the program, `stm32f4_iirsos_dma.c`, is also provided. It can be used by removing program `stm32f4_iirsos_intr.c` from the project and adding program `stm32f4_iirsos_dma.c` before rebuilding the project.
* * *
# Example 4.2
**Implementation of IIR Filter Using Cascaded Second-Order Transposed Direct Form II Sections (`stm32f4_iirsostr_intr.c`).**
* * *
A transposed direct form II structure can be implemented using program `stm32f4_iirsos_intr.c` simply by replacing the program statements
wn = input - a[section][1]*w[section][0]
- a[section][2]*w[section][1];
yn = b[section][0]*wn + b[section][1]*w[section][0]
+ b[section][2]*w[section][1];
w[section][1] = w[section][0];
w[section][0] = wn;
with the following program statements
yn = b[section][0]*input + w[section][0];
w[section][0] = b[section][1]*input + w[section][1]
- a[section][1]*yn;
w[section][1] = b[section][2]*input - a[section][2]*yn;
(variable `wn` is not required in the latter case).
This substitution has been made already in program `stm32f4_iirsostr_intr.c`. You should not notice any difference in the characteristics of the filters implemented using programs `stm32f4_iirsos_intr.c` and `stm32f4_iirsostr_intr.c`.
* * *
# Example 4.3
**Estimating the Frequency Response of an IIR Filter Using Pseudorandom Noise as Input (`tm4c123_iirsos_prbs_intr.c`).**
* * *
Program `tm4c123_iirsos_prbs_intr.c` is closely related to program `tm4c123_fir_prbs_intr.c`, described in Chapter 3. In real time, it generates a pseudorandom binary sequence and uses this wideband noise signal as the input to an IIR filter. The output of the filter is written to the DAC in the AIC3104 codec and the resulting analog signal (filtered noise) may be analyzed using an oscilloscope, spectrum analyzer, or _Goldwave_. The frequency content of the filter output gives a good indication of the filter's magnitude frequency response. Figures 4.11 and 4.12 show the output of the example filter (using coefficient file `impinv.h`) displayed using the FFT function of a _Rigol DS1052E_ oscilloscope and using _Goldwave_.
**Figure 4.11** Output from program `tm4c123_iirsos_prbs_intr.c` using coefficient file `impinv.h`, viewed using the FFT function of a _Rigol DS1052E_ oscilloscope.
**Figure 4.12** Output from program `tm4c123_iirsos_prbs_intr.c` using coefficient file `impinv.h`, viewed using _Goldwave_.
In Figure 4.11, the vertical scale is 5 dB per division and the horizontal scale is 625 Hz per division. The low-pass characteristic of the example filter is evident in the left-hand half of the figures between 0 and 2500 Hz. Between 2500 and 4000 Hz, the low-pass characteristic is less pronounced and the steeper roll-off beyond 4000 Hz is due not to the IIR filter but to the reconstruction filter in the AIC3104 codec.
* * *
# Example 4.4
**Estimating the Frequency Response of an IIR Filter Using a Sequence of Impulses as Input (`tm4c123_iirsos_delta_intr.c`).**
* * *
Instead of a pseudorandom binary sequence, program `tm4c123_iirsos_delta_intr.c`, shown in Listing 4.3, uses a sequence of discrete-time impulses as the input to an IIR filter. The resultant output is an approximation to a repetitive sequence of filter impulse responses. This relies on the filter impulse response decaying practically to zero within the period between successive input impulses. The filter output is written to the DAC in the AIC3104 codec and the resulting analog signal may be analyzed using an oscilloscope, spectrum analyzer, or `Goldwave`. In addition, program `tm4c123_iirsos_delta_intr.c` stores the `BUFFERSIZE` most recent samples of the filter output `yn` in array `response`, and by saving the contents of that array to a data file and using the MATLAB function `tm4c123_logfft()`, the response of the filter may be viewed in both time and frequency domains.
* * *
# Listing 4.3 Program `tm4c123_iirsos_delta_intr.c`
_// tm4c123_iirsos_delta_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "elliptic.h"
**#define** BUFFERSIZE 256
**#define** AMPLITUDE 10000.0f
float32_t w[NUM_SECTIONS][2] = {0};
float32_t dimpulse[BUFFERSIZE];
float32_t response[BUFFERSIZE];
int16_t bufptr = 0;
AIC3104_data_type sample_data;
**void** SSI_interrupt_routine(void)
{
float32_t inputl, inputr;
int16_t i;
int16_t section; // _index for section number_
float32_t input; // _input to each section_
float32_t wn,yn; // _intermediate and output values_
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
inputl = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI0_BASE,&sample_data.bit32);
inputr = (float32_t)(sample_data.bit16[0]);
input = dimpulse[bufptr];
**for** (section=0 ; section< NUM_SECTIONS ; section++)
{
wn = input - a[section][1]*w[section][0]
- a[section][2]*w[section][1];
yn = b[section][0]*wn + b[section][1]*w[section][0]
+ b[section][2]*w[section][1];
w[section][1] = w[section][0];
w[section][0] = wn;
input = yn;
}
response[bufptr++] = yn;
**if** (bufptr >= BUFFERSIZE) bufptr = 0;
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
sample_data.bit32 = ((int16_t)(yn*AMPLITUDE));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main( **void** )
{
**int** i;
**for** (i=0 ; i< BUFSIZE ; i++) dimpulse[i] = 0.0;
dimpulse[0] = 10.0;
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
Figure 4.13 shows the analog output signal generated by the program, captured using a _Rigol DS1052E_ oscilloscope connected to one of the scope hooks on the audio booster pack. The upper trace shows the time-domain impulse response of the filter ( per division) and the lower trace shows the FFT of that impulse response over a frequency range of 0–12 kHz. The output waveform is shaped both by the IIR filter and by the AIC3104 codec reconstruction filter. The codec reconstruction filter is responsible for the steep roll-off of gain at frequencies above 4 kHz. Below that frequency, but at frequencies higher than 1.5 kHz, less pronounced roll-off of gain due to the IIR filter is discernible. In the upper trace, the characteristics of the codec reconstruction filter are evident in the slight ringing that precedes the greater part of the impulse response waveform. Halt the program and save the contents of array `response`. Figure 4.14 shows the magnitude of the FFT of the contents of that array plotted using MATLAB function `tm4c123_logfft()`.
**Figure 4.13** Output from program `tm4c123_iirsos_delta_intr.c` using coefficient file `impinv.h`, viewed using the FFT function of a _Rigol DS1052E_ oscilloscope.
**Figure 4.14** The magnitude frequency response of the filter implemented by program `tm4c123_iirsos_delta_intr.c` using coefficient file `impinv.h`, plotted using MATLAB function `tm4c123_logfft()`.
#### 4.5.1.2 Aliasing in the Impulse Invariant Method
There are significant differences between the magnitude frequency response of the analog prototype filter used in this example (Figure 4.9) and that of its impulse-invariant digital implementation (Figure 4.14). The gain of the analog prototype has a magnitude of dB at 3000 Hz, whereas, according to Figure 4.14, the gain of the digital filter at that frequency has a magnitude closer to 11 dB. This difference is due to aliasing. Whenever a signal is sampled, the problem of aliasing should be addressed, and in order to avoid aliasing, the signal to be sampled should not contain any frequency components at frequencies greater than or equal to half the sampling frequency. The impulse invariant transformation yields a discrete-time impulse response equivalent to the continuous-time impulse response of the analog prototype at the sampling instants, but this is not sufficient to ensure that the continuous-time response of a discrete-time implementation of the filter is equivalent to that of the analog prototype. The impulse invariant method will be completely free of aliasing effects only if the continuous-time impulse response contains no frequency components at frequencies greater than or equal to half the sampling frequency.
In this example, the magnitude frequency response of the analog prototype filter will be folded back on itself about the 4000 Hz point, and this can be verified using MATLAB function `freqz()`, which assesses the frequency response of a digital filter. Type
>> [b,a] = cheby1(2,2,2*pi*1500,'s');
>> [bz,az] = impinvar(b,a,8000);
>> freqz(bz,az);
at the MATLAB command line in order to view the theoretical frequency response of the filter, and compare this with Figure 4.14.
An alternative method of transforming an analog filter design to a discrete-time implementation, which eliminates this effect, is the use of the bilinear transform.
#### 4.5.1.3 Bilinear Transform Method of Digital Filter Implementation
The bilinear transform method of converting an analog filter design into discrete time is relatively straightforward, often involving less algebraic manipulation than the impulse invariant method. It is achieved by making the substitution
**4.40**
in , where is the sampling period of the digital filter, that is,
**4.41**
Applying this to the -transfer function of (4.32) results in the following -transfer function.
**4.42**
From Equation (4.42), the following difference equation may be derived.
**4.43**
This can be achieved in MATLAB by typing
>> [bd,ad] = bilinear(b,a,8000);
The characteristics of the filter can be examined by changing the coefficient file used by programs `stm32f4_iirsos_intr.c`, `tm4c123_iirsos_prbs_intr.c`, and `tm4c123_iirsos_delta_intr.c` from `impinv.h` to `bilinear.h`. In each case, change the line that reads
#include "impinv.h"
to read
#include "bilinear.h"
before building, loading, and running the programs. Figures 4.15 through 4.18 show results obtained using programs `tm4c123_iirsos_prbs_intr.c` and `tm4c123_iirsos_delta_intr.c` with coefficient file `bilinear.h`. The attenuation provided by this filter at high frequencies is much greater than in the impulse invariant case. In fact, the attenuation at frequencies higher than 2000 Hz is significantly greater than that of the analog prototype filter.
**Figure 4.15** Output from program `tm4c123_iirsos_prbs_intr.c` using coefficient file `bilinear.h`, viewed using the FFT function of a _Rigol DS1052E_ oscilloscope.
**Figure 4.16** Output from program `tm4c123_iirsos_prbs_intr.c` using coefficient file `bilinear.h`, viewed using _Goldwave_.
Figure 4.17 Output from program `tm4c123_iirsos_delta_intr.c` using coefficient file `bilinear.h`, viewed using the FFT function of a _Rigol DS1052E_ oscilloscope.
**Figure 4.18** The magnitude frequency response of the filter implemented by program `tm4c123_iirsos_delta_intr.c` using coefficient file `bilinear.h`, plotted using MATLAB function `tm4c123_logfft()`.
#### 4.5.1.4 Frequency Warping in the Bilinear Transform
The concept behind the bilinear transform is that of compressing the frequency response of an analog filter design such that its response over the entire range of frequencies from zero to infinity is mapped into the frequency range from zero to half the sampling frequency of the digital filter. This may be represented by
**4.44**
and
**4.45**
where is the frequency at which the complex gain of the digital filter is equal to the complex gain of the analog filter at frequency . This relationship between and is illustrated in Figure 4.19. Consequently, there is no problem with aliasing, as seen in the case of impulse invariant transformation. However, as a result of the frequency warping inherent in the bilinear transform, in this example, the cutoff frequency of the discrete-time filter obtained is not 1500 Hz but 1356 Hz. Figure 4.19 also shows that the gain of the analog filter at a frequency of 4500 Hz is equal to the gain of the digital filter at a frequency of 2428 Hz and that the digital frequency 1500 Hz corresponds to an analog frequency of 1702 Hz. If we had wished to create a digital filter having a cutoff frequency of 1500 Hz, we could have applied the bilinear transform of Equation (4.35) to an analog prototype having a cutoff frequency of 1702 Hz.
**Figure 4.19** The effect of the bilinear transform on the magnitude frequency response of the example filter.
This technique is referred to as prewarping the prototype analog design and is used by default in the MATLAB filter design and analysis tool `fdatool`, described in the next section. A digital filter with a cutoff frequency of 1500 Hz may be obtained by applying the bilinear transform to the analog filter.
**4.46**
that is
**4.47**
The analog filter represented by Equation (4.46) can be produced using the MATLAB command
>> [bb,aa] = cheby1(2,2,2*pi*1702,`s');
and the BLT applied by typing
>> [bbd,aad] = bilinear(bb,aa,8000);
to yield the result given by Equation (4.47). Alternatively, prewarping of the analog filter design considered previously can be combined with application of the bilinear transform by typing
>> [bbd,aad]=bilinear(b,a,8000,1500);
at the MATLAB command line. Coefficient file `bilinearw.h` contains the coefficients obtained as described earlier.
#### 4.5.1.5 Using MATLAB's Filter Design and Analysis Tool
MATLAB provides a filter design and analysis tool, `fdatool`, which makes the calculation of IIR filter coefficient values simple. Coefficients can be exported to the MATLAB workspace in direct form II, second-order section format, and MATLAB function `stm32f4_iirsos_coeffs()` or `tm4c123_iirsos_coeffs()`, supplied with this book as files `stm32f4_iirsos_coeffs.m` and `tm4c123_iirsos_coeffs.m` can be used to generate coefficient files compatible with the programs in this chapter.
* * *
# Example 4.5
**Fourth-Order Elliptic Low-Pass IIR Filter Designed Using`fdatool`.**
* * *
To invoke the _Filter Design and Analysis Tool_ window, type
>> fdatool
in the MATLAB command window. Enter the parameters for a fourth-order elliptic low-pass IIR filter with a cutoff frequency of 800 Hz, 1 dB of ripple in the pass band, and 50 dB of stop-band attenuation. Click on _Design Filter_ and then look at the characteristics of the filter using options from the _Analysis_ menu (Figure 4.20).
**Figure 4.20** MATLAB `fdatool` window showing the magnitude frequency response of a fourth-order elliptic low-pass filter.
This example illustrates the steep transition from pass to stop bands of an IIR filter possible even with relatively few filter coefficients. Select _Filter Coefficients_ from the _Analysis_ menu in order to list the coefficient values designed. `fdatool` automatically designs filters as cascaded second-order sections. Each section is similar to those shown in block diagram form in Figure 4.5, and each section is characterized by six parameter values , , , , , and .
By default, `fdatool` uses the bilinear transform method of designing a digital filter starting from an analog prototype. Figure 4.21 shows the use of `fdatool` to design the Chebyshev filter considered in the preceding examples. Notice that the magnitude frequency response decreases more and more rapidly with frequency approaching half the sampling frequency, and compare this with Figure 4.16. This is characteristic of filters designed using the bilinear transform.
**Figure 4.21** MATLAB `fdatool` window showing the magnitude frequency response of a second-order Chebyshev low-pass filter.
#### 4.5.1.6 Implementing a Filter Designed Using `fdatool`
In order to implement a filter designed using `fdatool`, carry out the following steps:
1. Design the IIR filter using `fdatool`.
2. Click _Export_ in the `fdatool` _File_ menu.
3. Select _Workspace_ , _Coefficients_ , _SOS_ , and _G_ and click _Export_.
4. At the MATLAB command line, type either `stm32f4_iirsos_coeffs(SOS,G)` or `tm4c123_iirsos_coeffs(SOS,G)` and enter a filename, for example, `elliptic.h`.
Listing 4.4 shows an example of a coefficient file produced using MATLAB function `stm32f4_iirsos_coeffs()` (Listing 4.5).
* * *
# Listing 4.4 Coefficient header file `elliptic.h`
_// elliptic.h_
_// this file was generated automatically using function stm32f4_iirsos_coeffs.m_
**#define** NUM_SECTIONS 2
**float** b[NUM_SECTIONS][3] = {
{3.46359750E-002, 2.72500874E-002, 3.46359750E-002},
{2.90182959E-001, -2.25444662E-001, 2.90182959E-001} };
**float** a[NUM_SECTIONS][3] = {
{1.00000000E+000, -1.52872987E+000, 6.37029381E-001},
{1.00000000E+000, -1.51375731E+000, 8.68678568E-001} };
* * *
* * *
# Listing 4.5 MATLAB function `stm32f4_iirsos_coeffs()`
% STM32F4_IIRSOS_COEFFS.M
%
% MATLAB function to write SOS IIR filter coefficients
% in format suitable **for** use in STM32F4 Discovery programs
% including stm32f4_iirsos_intr.c,
% stm32f4_iirsos_prbs_intr.c and stm32f4_iirsosdelta_intr.c
% assumes that coefficients have been exported from
% fdatool as two matrices
% first matrix has format
% [ b10 b11 b12 a10 a11 a12
% b20 b21 b22 a20 a21 a22
% ...
% ]
% where bij is the bj coefficient in the ith stage
% second matrix contains gains **for** each stage
%
function STM32F4_iirsos_coeffs(coeff,gain)
%
num_sections=length(gain)-1;
fname = input('enter filename for coefficients ','s');
fid = fopen(fname,'wt');
fprintf(fid,'// %s\n',fname);
fprintf(fid,'// this file was generated using');
fprintf(fid,'\n// function STM32F4_iirsos_coeffs.m\n',fname);
fprintf(fid,'\n#define NUM_SECTIONS %d\n',num_sections);
% first write the numerator coefficients b
% i is used to count through sections
fprintf(fid,'\nfloat b[NUM_SECTIONS][3] = { \n');
**for** i=1:num_sections
**if** inum_sections
fprintf(fid,'{%2.8E, %2.8E, %2.8E} }\n',...
coeff(i,1)*gain(i),coeff(i,2)*gain(i),coeff(i,3)*gain(i));
**else**
fprintf(fid,'{%2.8E, %2.8E, %2.8E},\n',...
coeff(i,1)*gain(i),coeff(i,2)*gain(i),coeff(i,3)*gain(i));
end
end
% then write the denominator coefficients a
% i is used to count through sections
fprintf(fid,'\nfloat a[NUM_SECTIONS][3] = { \n');
**for** i=1:num_sections
**if** inum_sections
fprintf(fid,'{%2.8E, %2.8E, %2.8E} };\n',...
coeff(i,4),coeff(i,5),coeff(i,6));
**else**
fprintf(fid,'{%2.8E, %2.8E, %2.8E} };\n',...
coeff(i,4),coeff(i,5),coeff(i,6));
end
end
fclose(fid);
* * *
Program `tm4c123_iirsos_intr.c`, introduced in Example 4.1, can be used to implement the filter. Edit the line in the program that reads
#include "bilinear.h"
to read
#include "elliptic.h"
and build and run the program. The coefficient header file is also compatible with programs `tm4c123_iirsos_prbs_intr.c` and `tm4c123_iirsos_delta_intr.c`. Figures 4.22 and 4.23 show results obtained using program `tm4c123_iirsos_delta_intr.c` and coefficient file `elliptic.h`.
**Figure 4.22** Impulse response and magnitude frequency response of the filter implemented by program `tm4c123_iirsos_delta_intr.c`, using coefficient file `elliptic.h`, plotted using MATLAB function `tm4c123_logfft()`.
**Figure 4.23** Output from program `tm4c123_iirsos_delta_intr.c`, using coefficient file `elliptic.h` viewed using a _Rigol DS1052E_ oscilloscope.
* * *
# Example 4.6
**Band-Pass Filter Design Using`fdatool`.**
* * *
Figure 4.24 shows `fdatool` used to design an 18th-order Chebyshev type 2 IIR band-pass filter centered at 2000 Hz. The filter coefficient file `bp2000.h` is compatible with programs `tm4c123_iirsos_intr.c`, `tm4c123_iirsos_delta_intr.c`, and `tm4c123_iirsos_prbs_intr.c`. Figures 4.25 and 4.26 show the output from program `tm4c123_iirsos_prbs_intr.c` using these coefficients.
**Figure 4.24** MATLAB `fdatool` window showing the magnitude frequency response of an 18th-order band-pass filter centered on 2000 Hz.
**Figure 4.25** Output from program `tm4c123_iirsos_prbs_intr.c`, using coefficient file `bp2000.h` viewed using a _Rigol DS1052E_ oscilloscope.
**Figure 4.26** Output from program `tm4c123_iirsos_prbs_intr.c`, using coefficient file `bp2000.h` viewed using _Goldwave_.
* * *
# Example 4.7
**Implementation of IIR Filter Using CMSIS Function arm_biquad_cascade_f32() (`stm32f4_iirsos_CMSIS_intr.c`).**
* * *
This example demonstrates the use of the CMSIS DSP library IIR filtering function `arm_biquad_cascade_df1_f32()`.
Function `arm_biquad_cascade_df1_f32()` implements a second-order IIR filter section (a biquad) using single precision (32-bit) floating point arithmetic. As the function name suggests, the filter is implemented as a direct form I structure. The function processes a block of input samples to produce a corresponding block of output samples and is therefore suited to the use of DMA-based i/o. However, program `stm32f4_iirsos_CMSIS_intr.c` uses sample-by-sample interrupt-based i/o and a block size of one sample (Listing 4.6).
* * *
# Listing 4.6 Program `stm32f4_iirsos_CMSIS_intr.c`
_// stm32f4_iirsos_CMSIS_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#include** "elliptic.h"
float32_t coeffs[5*NUM_SECTIONS] = {0};
float32_t state[4*NUM_SECTIONS] = {0};
arm_biquad_casd_df1_inst_f32 S;
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, left_in_sample;
int16_t right_out_sample, right_in_sample;
float32_t xn, yn;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
xn =(float32_t)(left_in_sample);
arm_biquad_cascade_df1_f32(&S, &xn, &yn, 1);
left_out_sample = (int16_t)(yn);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
right_out_sample = 0;
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
**int** i,k;
k = 0;
**for** (i=0; i<NUM_SECTIONS ; i++)
{
coeffs[k++] = b[i][0];
coeffs[k++] = b[i][1];
coeffs[k++] = b[i][2];
coeffs[k++] = -a[i][1];
coeffs[k++] = -a[i][2];
}
arm_biquad_cascade_df1_init_f32(&S, NUM_SECTIONS,
coeffs, state);
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){{
}
* * *
As supplied, the program implements the fourth-order elliptic low-pass filter used in Example 4.5, reading filter coefficients from the header file `elliptic.h`.
Within function `SPI2_IRQHandler()`, the value of a new left channel input sample is copied to `float32_t` variable `xn`.
Function `arm_biquad_cascade_df1_f32()` is passed pointers to
1. An instance of an IIR filter structure of type `arm_biquad_casd_inst_df1_f32`.
2. An array containing a sequence of input sample values of type `float32_t`.
3. An array in which to place a sequence of output sample values of type `float32_t`.
4. The number of input and output sample values.
An IIR filter structure `S` is declared in program statement
arm_biquad_casd_inst_df1_f32 S;
and, after the filter coefficients specified in header file `elliptic.h` as arrays `a` and `b` have been copied into the array `coeffs` used by function `arm_biquad_cascade_df1_f32()`, it is initialized in program statement
arm_biquad_cascade_df1_init_f32(&S, NUM_SECTIONS, coeffs, state);
Each second-order stage of a filter is represented by five coefficient values, of type `float32_t`, stored in array `coeffs` in the order . These values correspond to a transfer function of the form
**4.48**
The `arm_biquad_casd_inst_df1_f32` filter structure keeps track of the internal state of each of the `NUM_SECTIONS` second-order IIR filter stages, that is, it stores and updates previous input and output sample values , , , and .
#### 4.5.1.7 Testing the Filter Using a Pseudorandom Input Signal
In program `stm32f4_iirsos_prbs_CMSIS_intr.c`, the statement in program `stm32f4_iirsos_CMSIS_intr.c` that reads
xn =(float32_t)(left_in_sample);
is replaced by
xn = (float32_t)(prbs(8000));
in order to use internally generated pseudorandom noise as an input and enable the filter characteristics to be observed using an oscilloscope or _Goldwave_ without the need for an externally applied input signal.
In program `stm32f4_iirsos_delta_CMSIS_intr.c`, the input signal applied to the filter is a sequence of discrete impulses read from array `dimpulse`.
* * *
# Example 4.8
**Implementation of a Fourth-Order IIR Filter Using the AIC3104 Digital Effects Filter (`tm4c123_sysid_biquad_intr.c`).**
* * *
The AIC3104 codec contains two fourth-order IIR filters (one for each channel) just before the DAC. Their coefficients can be programmed using page 1 control registers 1 through 20 ( _Left Channel Audio Effects Filter Coefficient Registers_ ) and 27 through 46 ( _Right Channel Audio Effects Filter Coefficient Registers_ ). They are enabled by setting bit 3 (left channel) and/or bit 1 (right channel) in page 0 control register 12 ( _Audio Codec Digital Filter Control Register_ ). Each filter is implemented as two second-order (biquad) sections with an overall -transfer function
**4.49**
where coefficients and are 16-bit signed integers. Full details of these filters are given in the AIC3104 data sheet [1].
Program `tm4c123_sysid_biquad_intr.c` is almost identical to program `tm4c123_sysid_intr.c`, introduced in Chapter 2. It uses an adaptive FIR filter in order to measure the response of a signal path including the codec. It differs only in that the codec is programmed to include the fourth-order IIR filter described earlier.
Function `I2CRegWrite()` may be used to program the 8-bit control registers of the AIC3104 and each of the 16-bit coefficients of the filters must therefore be split into two 8-bit bytes. MATLAB function `tm4c123_aic3104_biquad()`, shown in Listing 4.7, has been provided to automate the generation of these program statements following calculation of filter coefficients using `fdatool`.
* * *
# Listing 4.7 MATLAB function `tm4c123_aic3104_biquad()`
% TM4C123_AIC3104_BIQUAD.M
%
% MATLAB function to write C program statements
% to program left and right channel biquads in AIC3104 codec.
% Assumes that coefficients of a fourth order IIR filter
% have been designed using fdatool and exported to workspace
% as two matrices. These are passed to function as coeff and
% gain.
%
% First matrix coeff has format
%
% [ b10 b11 b12 a10 a11 a12
% b20 b21 b22 a20 a21 a22
% ]
%
% where bij is the bj coefficient in the ith stage.
%
% Second matrix gain contains gains **for** the two stages of the
% fourth order filter. fdatool generates three gains - one **for**
% each second order stage and an output gain.
%
% This function calls function tm4c123_make_hex_str() defined in
% file TM4C123_MAKE_HEX_STR.M.
%
% Details of AIC3104 registers in TI document SLAS509E.
%
function tm4c123_aic310_biquad(coeff,gain)
%
fname = input('enter filename for C program statements ','s');
fid = fopen(fname,'wt');
fprintf(fid,'// %s\n',fname);
fprintf(fid,'// this file was generated automatically using');
fprintf(fid,' function tm4c123_aic3104_biquad.m\n',fname);
fn_name = 'I2CRegWrite';
parameters = 'I2C1_BASE, AIC3104_SLAVE_ADDRESS';
fsref divisors% left channel audio effects filter coefficients
a = tm4c123_make_hex_str(round(coeff(1,1)*gain(1)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s, 1,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s, 2,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(1,2)*gain(1)*2ˆ14));
fprintf(fid,'%s(%s, 3,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s, 4,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(1,3)*gain(1)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s, 5,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s, 6,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(2,1)*gain(2)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s, 7,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s, 8,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(2,2)*gain(2)*2ˆ14));
fprintf(fid,'%s(%s, 9,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,10,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(2,3)*gain(2)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,11,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,12,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(-coeff(1,5)*2ˆ14));
fprintf(fid,'%s(%s,13,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,14,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(-coeff(1,6)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,15,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,16,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(-coeff(2,5)*2ˆ14));
fprintf(fid,'%s(%s,17,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,18,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(-coeff(2,6)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,19,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,20,0x%s%s);\n',fn_name,parameters,a(1),a(2));
% right channel audio effects filter coefficients
a = tm4c123_make_hex_str(round(coeff(1,1)*gain(1)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,27,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,28,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(1,2)*gain(1)*2ˆ14));
fprintf(fid,'%s(%s,29,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,30,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(1,3)*gain(1)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,31,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,32,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(2,1)*gain(2)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,33,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,34,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(2,2)*gain(2)*2ˆ14));
fprintf(fid,'%s(%s,35,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,36,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(coeff(2,3)*gain(2)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,37,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,38,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(-coeff(1,5)*2ˆ14));
fprintf(fid,'%s(%s,39,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,40,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(-coeff(1,6)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,41,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,42,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(-coeff(2,5)*2ˆ14));
fprintf(fid,'%s(%s,43,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,44,0x%s%s);\n',fn_name,parameters,a(1),a(2));
a = tm4c123_make_hex_str(round(-coeff(2,6)*(2ˆ15 - 1)));
fprintf(fid,'%s(%s,45,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fprintf(fid,'%s(%s,46,0x%s%s);\n',fn_name,parameters,a(1),a(2));
fclose(fid);
* * *
Connect LINE OUT (black) on the audio booster pack to LINE IN (blue) as shown in Figure 4.27 and build and run the program `tm4c123_sysid_biquad_intr.c` as supplied. Initially, the AIC3104 biquad filters are neither programmed nor enabled. Halt the program after a few seconds and save the 256 adaptive filter coefficients to a data file by typing
save <filename> start address, (start address + 0x400)
in the _Command_ window of the _MDK-ARM debugger_ , where `start address` is the address of array `firCoeffs32`. Plot the contents of the data file (the impulse response identified by the adaptive filter) using MATLAB function `tm4c123_logfft()`. You should see something similar to the graph shown in Figure 4.28.
**Figure 4.27** Connection diagram for program `tm4c123_sysid_biquad_intr.c`.
**Figure 4.28** Frequency response of signal path through DAC, connecting cable, and ADC shown in Figure 4.27 with biquad filters disabled.
* * *
# Listing 4.8 File `elliptic_coeffs_biquad.h`
_// elliptic_coeffs_biquad.h_
_//_
_// this file was generated automatically using m-file_
_// tm4c123_aic3106_biquad.m_
//
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 1,0x01);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 2,0x49);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 3,0x00);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 4,0x82);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 5,0x01);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 6,0x49);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 7,0x7f);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 8,0xff);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 9,0xce);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 10,0x47);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 11,0x7f);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 12,0xff);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 13,0x61);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 14,0xd7);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 15,0xae);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 16,0x76);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 17,0x60);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 18,0xe1);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 19,0x90);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 20,0xd0);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 27,0x01);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 28,0x49);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 29,0x00);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 30,0x82);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 31,0x01);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 32,0x49);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 33,0x7f);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 34,0xff);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 35,0xce);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 36,0x47);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 37,0x7f);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 38,0xff);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 39,0x61);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 40,0xd7);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 41,0xae);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 42,0x76);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 43,0x60);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 44,0xe1);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 45,0x90);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 46,0xd0);
* * *
Listing 4.8 shows the contents of file `elliptic_coeffs_biquad.h`. This file was generated using MATLAB function `aic3104_biquad()` to process filter coefficients of a fourth-order elliptic low-pass filter designed using `fdatool`. Cut and paste these statements into program `tm4c123_sysid_biquad_intr.c` just after the program statement
tm4c123_aic3104_init(FS_8000_HZ,
INPUT_LINE,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
Add the statement
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 0, 0x01);
immediately preceding the statements cut and pasted from file `elliptic_coeffs_biquad.h` and add the statements
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 0, 0x00);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 12, 0x0A);
immediately following the previously pasted statements. The last of these statements will enable the biquad filters on both left- and right-hand channels. Once again, build and load the program and run it. Halt the program after a few seconds and save the coefficients and plot using MATLAB. You should now see the magnitude frequency response of the biquad filter, as shown in Figure 4.29.
**Figure 4.29** Frequency response of signal path through DAC, connecting cable, and ADC shown in Figure 4.27 with biquad filters programmed as a fourth-order elliptic low-pass filter and enabled.
#### 4.5.1.8 Changing the Response of the AIC3104 Digital Effects Filter
In order to program an alternative filter response into the digital effects filter,
1. Design an alternative fourth-order IIR filter using fdatool. Figure 4.30 shows the design of a fourth-order elliptic band pass filter.
2. Export the filter coefficients from `fdatool` to the MATLAB workspace as variables _SOS_ and _G_.
3. At the MATLAB command line, type `aic3104_biquad(SOS,G)` and enter a filename, for example, `bandpass_coeffs_biquad.h`.
4. Cut and paste the statements contained in file `bandpass_coeffs_biquad.h` into program `tm4c123_sysid_biquad_intr.c` (in place of those used in the previous example) immediately following the call to function `tm4c123_aic3104_init()` and immediately preceding the program statements
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 0, 0x00);
I2CRegWrite(I2C1_BASE, AIC3104_SLAVE_ADDRESS, 12, 0x0A);
replacing the previous calls to function `I2CRegWrite()`.
5. Build and run the program as before.
6. Observe the response identified using MATLAB function `tm4c123_logfft()` to plot the values stored in array `firCoeffs32`.
**Figure 4.30** `fdatool` used to design a fourth-order elliptic band-pass filter.
Figure 4.31 shows the identified frequency response for the coefficients contained in file `bandpass_coeffs_biquad`.h using MATLAB function `tm4c123_logfft()`.
**Figure 4.31** Frequency response of signal path through DAC, connecting cable, and ADC shown in Figure 4.27 with biquad filters programmed as a fourth-order elliptic band-pass filter and enabled.
* * *
# Example 4.9
**Generation of a Sine Wave Using a Difference Equation (`stm32f4_sinegenDE_intr.c`).**
* * *
In Chapter 3, it was shown that the -transform of a sinusoidal sequence is given by
**4.50**
Comparing this with the -transfer function of the second-order filter of Example 4.1
**4.51**
It is apparent that by appropriate choice of filter coefficients, we can configure the filter to act as a sine wave generator, that is, to have a sinusoidal impulse response. Choosing and , the denominator of the transfer function becomes , which corresponds to a pair of complex conjugate poles located on the unit circle in the -plane. The filter can be set oscillating by applying an impulse to its input. Rearranging Equation (4.51) and setting , ( ), and
**4.52**
Equation (4.52) is equivalent to Equation (4.50), implying that the filter impulse response is . Equation (4.51) corresponds to the difference equation
**4.53**
which is illustrated in block diagram form in Figure 4.32.
**Figure 4.32** Block diagram representation of Equation (4.53).
Since the input, , to the filter is nonzero only at sampling instant , the difference equation is equal to
**4.54**
for all other and hence the sine wave generator may be implemented as shown in Figure 4.33, using no input signal but using nonzero initial values for and . These initial values determine the amplitude of the sinusoidal output.
**Figure 4.33** Block diagram representation of Equation (4.54).
Since the frequency of oscillation is fixed by the choice of and , the initial values chosen for and represent two samples of a sinusoid of frequency , which are one sampling period, or seconds, apart in time, that is,
The initial values of and determine the amplitude of the sine wave generated. A simple solution to the equations, implemented in program `tm4c123_sinegenDE_intr.c` (Listing 4.9), is
Build and run this program as supplied (`FREQ = 2000`) and verify that the output is a 2000 Hz tone. Change the value of the constant `FREQ`, build and run the program, and verify the generation of a tone of the frequency selected.
* * *
# Listing 4.9 Program `stm32f4_sinegenDE_intr.c`
_// stm32f4_sinegenDE_intr.c_
**#include** "stm32f4_wm5102_init.h"
float32_t y[3]; // _filter states - previous output values_
float32_t a1; // _filter coefficient_
**const** float32_t AMPLITUDE = 8000.0;
**const** float32_t FREQ = 2000.0;
**const** float32_t SAMPLING_FREQ = 8000.0;
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, left_in_sample;
int16_t right_out_sample, right_in_sample;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
left_in_sample = (float32_t)(SPI_I2S_ReceiveData(I2Sx));
y[0] = -(y[1]*a1)-y[2]; // _new y(n)_
y[2] = y[1]; // _update y(n-2)_
y[1] = y[0]; // _update y(n-1)_
left_out_sample = (int16_t)(y[0]);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
}
**else**
{
right_in_sample = SPI_I2S_ReceiveData(I2Sx);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
right_out_sample = 0;
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
y[1] = 0.0;
y[2] = AMPLITUDE*sin(2.0*PI*FREQ/SAMPLING_FREQ);
a1 = -2.0*cos(2.0*PI*FREQ/SAMPLING_FREQ);
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
* * *
# Example 4.10
**Generation of DTMF Signal Using Difference Equations (`stm32f4_sinegenDTMF_intr.c`).**
* * *
Program `stm32f4_sinegenDTMF_intr.c`, shown in Listing 4.10, uses the same difference equation method as program `tm4c123_sinegenDE_intr` to generate two sinusoidal signals of different frequencies, which, added together, form a DTMF tone (see also Example 2.12, which used a table lookup method). The program also incorporates a buffer (array `out_buffer`) that is used to store the 256 most recent output samples. Figure 4.34 shows the contents of that buffer in time and frequency domains, plotted using MATLAB function `stm32f4_logfft()` after halting the program and saving the contents of `out_buffer` to a file. Figure 4.35 shows the analog output signal generated by the program captured using an oscilloscope. Unlike the FFT function in the oscilloscope, MATLAB function `stm32f4_logfft()` has not applied a Hamming window to the sample values.
**Figure 4.34** Output samples generated by program `stm32f4_sinegenDTMF_intr.c` plotted using MATLAB function `stm32f4_logfft()`.
**Figure 4.35** Output signal generated by program `stm32f4_sinegenDTMF_intr.c` viewed using a _Rigol DS1052E_ oscilloscope.
* * *
# Listing 4.10 Program `stm32f4_sinegenDTMF_intr.c`
_// stm32f4_sinegenDTMF_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#define** FREQLO 770
**#define** FREQHI 1336
**#define** SAMPLING_FREQ 8000
**#define** AMPLITUDE 6000
**#define** BUFFER_SIZE 256
**float** ylo[3];
**float** yhi[3];
**float** a1lo, a1hi;
**float** out_buffer[BUFFER_SIZE];
**int** bufptr = 0;
**void** SPI2_IRQHandler()
{
int16_t left_out_sample, left_in_sample;
int16_t right_out_sample, right_in_sample;
float32_t output;
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) SET)
{
GPIO_SetBits(GPIOD, GPIO_Pin_15);
left_in_sample = SPI_I2S_ReceiveData(I2Sx);
ylo[0] = -(ylo[1]*a1lo)-ylo[2];
ylo[2] = ylo[1]; // _update y1(n-2)_
ylo[1] = ylo[0]; // _update y1(n-1)_
yhi[0] = -(yhi[1]*a1hi)-yhi[2];
yhi[2] = yhi[1]; // _update y1(n-2)_
yhi[1] = yhi[0]; // _update y1(n-1)_
output = (yhi[0]+ylo[0]);
out_buffer[bufptr++] = output;
**if** (bufptr>= BUFSIZE) bufptr = 0;
left_out_sample = (int16_t)(output);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
}
**else**
{
right_out_sample = SPI_I2S_ReceiveData(I2Sx);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
ylo[1] = 0.0;
ylo[2] = AMPLITUDE*sin(2.0*PI*FREQLO/SAMPLING_FREQ);
a1lo = -2.0*cos(2.0*PI*FREQLO/SAMPLING_FREQ);
yhi[1] = 0.0;
yhi[2] = AMPLITUDE*sin(2.0*PI*FREQHI/SAMPLING_FREQ);
a1hi = -2.0*cos(2.0*PI*FREQHI/SAMPLING_FREQ);
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
* * *
# Example 4.11
**Generation of a Swept Sinusoid Using a Difference Equation (`stm32f4_sweepDE_intr.c`).**
* * *
Listing 4.11 is of program `stm32f4_sweepDE_intr.c`, which generates a sinusoidal signal, sweeping repeatedly from low to high frequency. The program implements the difference equation
**4.55**
where and the initial conditions are and . Example 4.9 illustrated the generation of a sine wave using this difference equation.
Compared with the lookup table method of Example 2.15, making step changes in the frequency of the output signal generated using a difference equation is slightly more problematic. Each time program `stm32f4_sweepDE_intr.c` changes its output frequency it reinitializes the stored values of previous output samples and . These values determine the amplitude of the sinusoidal output at the new frequency and must be chosen appropriately. Using the existing values, leftover from the generation of a sinusoid at the previous frequency might cause the amplitude of the output sinusoid to change. In order to avoid discontinuities, or glitches, in the output waveform, a further constraint on the parameters of the program must be observed. Since at each change in frequency, the output waveform starts at the same phase in its cycle, it is necessary to ensure that each different frequency segment is output for an integer number of cycles. This can be achieved by making the number of samples output between step changes in frequency equal to the sampling frequency divided by the frequency increment.
As shown in Listing 4.11, the frequency increment is 20 Hz and the sampling frequency is 8000 Hz. Hence, the number of samples output at each different frequency is equal to 8000/20 = 400. Different choices for the values of the constants `STEP_FREQ` and `SWEEP_PERIOD` are possible.
Build and run this program. Verify that the output is a swept sinusoidal signal starting at frequency 200 Hz and taking (`SWEEP_PERIOD/SAMPLING_FREQ)*(MAX_FREQ-MIN_FREQ)/STEP_FREQ` seconds to increase in frequency to 3800 Hz. Change the values of`START_FREQ` and `STOP_FREQ` to 2000 and 3000, respectively. Build the project again, load and run the program, and verify that the frequency sweep is from 2000 to 3000 Hz.
* * *
# Listing 4.11 Program `stm32f4_sweepDE_intr.c`
_// stm32f4_sweepDE_intr.c_
**#include** "stm32f4_wm5102_init.h"
**#define** MIN_FREQ 200
**#define** MAX_FREQ 3800
**#define** STEP_FREQ 20
**#define** SWEEP_PERIOD 400
**#define** SAMPLING_FREQ 8000.0f
**#define** AMPLITUDE 4000.0f
**#define** PI 3.14159265358979f
float32_t y[3] = {0.0, 0.0, 0.0};
float32_t a1;
float32_t freq = MIN_FREQ;
int16_t sweep_count = 0;
;
**void** coeff_gen( **float** freq)
{
float32_t kk;
kk = 2.0*PI*freq/SAMPLING_FREQ;
a1 = -2.0*arm_cos_f32(kk);
y[0] = 0.0;
y[2] = AMPLITUDE*arm_sin_f32(kk);
y[1] = 0.0;
**return** ;
}
**void** SPI2_IRQHandler()
{
int16_t left_out_sample = 0;
int16_t right_out_sample = 0
**if** (SPI_I2S_GetFlagStatus(I2Sx, I2S_FLAG_CHSIDE) != SET)
{
GPIO_SetBits(GPIOD, GPIO_Pin_15);
left_out_sample = SPI_I2S_ReceiveData(I2Sx);
sweep_count++;
**if** (sweep_count>= SWEEP_PERIOD)
{
**if** (freq>= MAX_FREQ)
freq = MIN_FREQ;
**else**
freq += STEP_FREQ;
coeff_gen(freq);
sweep_count = 0;
}
y[0] = -(y[1]*a1)-y[2];
y[2] = y[1]; // _update_ y1(n-2)
y[1] = y[0]; // _update_ y1(n-1)
left_out_sample = (int16_t)(y[0]);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, left_out_sample);
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
}
**else**
{
right_out_sample = SPI_I2S_ReceiveData(I2Sx);
**while** (SPI_I2S_GetFlagStatus(I2Sxext,
SPI_I2S_FLAG_TXE ) != SET){}
SPI_I2S_SendData(I2Sxext, right_out_sample);
}
}
**int** main( **void** )
{
coeff_gen(freq);
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_INTR);
**while** (1){}
}
* * *
* * *
# Example 4.12
**Cascaded Second-Order Notch Filters (`tm4c123_iirsos_intr`).**
* * *
In Chapter 3, two 89-coefficient FIR notch filters were used to remove unwanted tones from a signal. In this example, the use of simple second-order IIR notch filters to achieve a similar result is demonstrated. A second-order IIR notch filter has the form
**4.56**
corresponding, in the -plane, to two complex conjugate zeros on the unit circle at angles from the real axis and two complex conjugate poles of magnitude , at similar angles. This is illustrated in Figure 4.36.
**Figure 4.36** Pole-zero map for notch filter described by Equation (4.56) for and .
The magnitude frequency response of this filter contains a deep notch at frequency radians with 3 dB cutoff frequencies spaced radians apart. In other words, the parameter determines the width of the notch shown in Figure 4.37.
**Figure 4.37** Frequency response of notch filter described by Equation (4.56) for and .
Two cascaded second-order IIR notch filters with notches at 900 and 2700 Hz programs may be implemented using either program `tm4c123_iirsos_intr.c` or `tmc123_iirsos_prbs_intr.c` simply by including the header file `iir_notch_coeffs.h` (shown in Listing 4.12).
* * *
# Listing 4.12 Coefficient header file `iir_notch_coeffs.h`
_// iir_notch_coeffs.h_
_// cascaded second-order notch filters 900 Hz and 2700 Hz_
**#define** NUM_SECTIONS 2
**float** b[NUM_SECTIONS][3] = {
{1.00000000, 1.04499713, 1.00000000},
{1.00000000, -1.5208, 1.00000000} };
_float_ a[NUM_SECTIONS][3] = {
{1.00000000, 0.94049741, 0.9025},
{1.00000000, -1.44476, 0.9025} };
* * *
Run program `tmc123_iirsos_intr.c` using that coefficient header file, and test its response to the input signal stored in file `corrupt.wav`. Play the test signal using _Goldwave_ , _Windows Media Player_ , or similar, and connect the PC sound card output to the (blue) LINE IN connection on the audio booster card.
Figure 4.38 shows pseudorandom noise filtered by program `tmc123_iirsos_prbs_intr.c` using header file `iir_notch_coeffs.h`.
**Figure 4.38** Pseudorandom noise filtered by program `tmc123_iirsos_prbs_intr.c` using header file `iir_notch_coeffs.h`.
## Reference
1. 1. Texas Instruments, Inc., "TLV320AIC3104 Low-Power Stereo Audio Codec for Portable Audio and Telephony", Literature no. SLAS510D, 2014.
# Chapter 5
Fast Fourier Transform
## 5.1 Introduction
Fourier analysis describes the transformations between time- and frequency-domain representations of signals. Four different forms of Fourier transformation (the Fourier transform (FT), Fourier Series (FS), Discrete-time Fourier transform (DTFT), and discrete Fourier transform (DFT)) are applicable to different classes of signal according to whether, in either domain, they are discrete or continuous and whether they are periodic or aperiodic. The DFT is the form of Fourier analysis applicable to signals that are discrete and periodic in both domains, that is, it transforms a discrete, periodic, time-domain sequence into a discrete, periodic, frequency-domain representation. A periodic signal may be characterized entirely by just one cycle, and if that signal is discrete, then one cycle comprises a finite number of samples. The DFT transforms complex time-domain samples into complex frequency-domain values. Hence, both forward and inverse DFTs are described by finite summations as opposed to either infinite summations or integrals. This is very important in digital signal processing since it means that it is practical to compute the DFT using a digital signal processor or digital hardware.
The fast Fourier transform (FFT) is a computationally efficient algorithm for computing the DFT. It requires fewer multiplications than a more straightforward programming implementation of the DFT and its relative advantage in this respect increases with the lengths of the sample sequences involved. The FFT makes use of the periodic nature, and of symmetry, in the _twiddle factors_ used in the DFT. Applicable to spectrum analysis and to filtering, the FFT is one of the most commonly used operations in digital signal processing. Various, slightly different, versions of the FFT can be derived from the DFT, and in this chapter, the decimation-in-time (DIT) and decimation-in-frequency (DIF) radix-2 and radix-4 versions are described in detail. These versions of the FFT differ in the exact form of the intermediate computations that make them up. However, ignoring rounding errors, they each produce exactly the same results as the DFT. In this respect, the terms DFT and FFT are interchangeable.
## 5.2 Development of the FFT Algorithm with RADIX-2
The -point complex DFT of a discrete-time signal is given by
**5.1**
The constants are referred to as _twiddle constants_ or _twiddle factors_ , where
**5.2**
Computing all values of ( ) involves the evaluation of product terms of the form , each of which (aside from the requirement of computing ) requires a complex multiplication. For larger , the computational requirements ( complex multiplications) of the DFT can be very great. The FFT algorithm takes advantage of the periodicity
**5.3**
and symmetry
**5.4**
of (where is even).
Figure 5.1 illustrates the twiddle factors for plotted as vectors in the complex plane. Due to the periodicity of , the different combinations of and used in evaluation of Equation (5.1) result in only distinct values for . The FFT makes use of this small number of precomputed and stored values of rather than computing each one as it is required. Furthermore, due to the symmetry of , only distinct numerical values need actually be precomputed and stored.
**Figure 5.1** Twiddle factors for represented as vectors in the complex plane.
A second, important, way in which the radix-2 FFT saves computational effort is by decomposing an -point DFT into a combination of -point DFTs. In the case of radix-2, that is, where is an integer power of 2, further decomposition of -point DFTs into combinations of -point DFTs and so on can be carried out until 2-point DFTs have been reached. Computation of the 2-point DFT does not involve multiplication since the twiddle factors involved are equal to yielding and .
## 5.3 Decimation-in-Frequency FFT Algorithm with RADIX-2
Consider the -point DFT
**5.5**
where
**5.6**
and let be an integer power of 2.
Decompose the length input sequence into two length sequences, one containing the first values and the other containing the remaining values . Splitting the DFT summation into two parts
**5.7**
The term is placed outside the second summation since it is not a function of . Making use of
**5.8**
Equation (5.7) becomes
**5.9**
Because for even and for odd , Equation (5.9) can be split into two parts. For even ,
**5.10**
and for odd ,
**5.11**
For , that is, for an -point sequence, and making use of
**5.12**
**5.13**
and
**5.14**
Letting
**5.15**
and
**5.16**
Equations (5.13) and (5.14) may be written as
**5.17**
and
**5.18**
In other words, the even elements of are given by the -point DFT of , where are combinations of the elements of the -point input sequence . The odd elements of are given by the -point DFT of , where are different combinations of the elements of the -point input sequence . This structure is illustrated graphically, for , in Figure 5.2.
**Figure 5.2** Decomposition of 8-point DFT into two 4-point DFTs using decimation-in-frequency with radix-2.
Consider next that each of the 4-point DFTs in Figure 5.2 may further be decomposed into two 2-point DFTs (Figure 5.3). Each of those 2-point DFTs may further be decomposed into two 1-point DFTs. However, the 1-point DFT of a single value is equal to that value itself, and for this reason, the 2-point DFT _butterfly_ structure shown in Figure 5.4 is conventionally treated as the smallest component of the FFT structure.
**Figure 5.3** Decomposition of 4-point DFT into two 2-point DFTs using decimation-in-frequency with radix-2.
**Figure 5.4** 2-point FFT butterfly structure.
The 8-point DFT has thus been decomposed into a structure (Figure 5.5) that comprises only a small number of multiplications (by twiddle factors other than ).
**Figure 5.5** Block diagram representation of 8-point FFT using decimation-in-frequency with radix-2.
The FFT is not an approximation of the DFT. It yields the same result as the DFT with fewer computations required. This reduction becomes more and more important, and advantageous, with higher order FFTs.
The DIF process may be considered as taking the -point input sequence in sequence and reordering the output sequence in pairs, corresponding to the outputs of the final stage of 2-point DFT blocks.
## 5.4 Decimation-in-Time FFT Algorithm with RADIX-2
The DIF process decomposes the DFT output sequence into a set of shorter subsequences, whereas DIT is a process that decomposes the DFT input sequence into a set of shorter subsequences.
Consider again the -point DFT
**5.19**
where
**5.20**
and let be an integer power of 2.
Decompose the length input sequence into two length sequences one containing the even-indexed values and the other containing the odd-indexed values . Splitting the DFT summation into two parts
**5.21**
since
**5.22**
and
**5.23**
Letting
**5.24**
and
**5.25**
Equation (5.21) may be written as
**5.26**
However, -point DFTs and are defined only for , whereas -point DFT is defined for . and must be evaluated for , and and must also be evaluated for . Substituting for in the definition of
**5.27**
Since
**5.28**
and
**5.29**
Equation (5.26) becomes
**5.30**
evaluated for .
In other words, the -point DFT of input sequence is decomposed into two -point DFTs ( and ), of the even- and odd-indexed elements of , the results of which are combined in weighted sums to yield -point output sequence . This is illustrated graphically, for , in Figure 5.6.
**Figure 5.6** Decomposition of 8-point DFT into two 4-point DFTs using decimation-in-time with radix-2.
Consider next that each of the 4-point DFTs in that figure may further be decomposed into two 2-point DFTs (Figure 5.7) and that each of those 2-point DFTs is the 2-point FFT _butterfly_ structure shown in Figure 5.4 and used in the decimation in frequency approach.
**Figure 5.7** Decomposition of 4-point DFT into two 2-point DFTs using decimation-in-time with radix-2.
The 8-point DFT has thus been decomposed into a structure (Figure 5.8) that comprises only a small number of multiplications (by twiddle factors other than ). The DIT approach may be considered as using pairs of elements from a reordered -point input sequence as inputs to 2-point DFT blocks and producing a correctly ordered -point output sequence .
**Figure 5.8** Block diagram representation of 8-point FFT using decimation-in-time with radix-2.
### 5.4.1 Reordered Sequences in the Radix-2 FFT and Bit-Reversed Addressing
The reordered input sequence in the case of the DIT approach and the reordered output sequence in the case of DIF can be described with reference to _bit-reversed addressing_.
Taking as an example the reordered length sequence in the case of DIT, the index of each sample may be represented by a log2( ) bit binary number (recall that, in the foregoing examples, is an integer power of 2). If the binary representations of the index values 0 to have the order of their bits reversed, for example, 001 becomes 100, 110 becomes 011, and so on, then the resulting values represent the indices of the input sequence in the order that they appear at the input to the FFT structure. In the case of (Figure 5.6), the input values are ordered . The binary representations of these indices are 000, 100, 010, 110, 001, 101, 011, 111. These are the bit-reversed versions of the sequence 000, 001, 010, 011, 100, 101, 110, 111. The bit-reversed interpretation of the reordering holds for all (that are integer powers of 2).
## 5.5 Decimation-in-Frequency FFT Algorithm with RADIX-4
Radix-4 decomposition of the DFT is possible if is an integer power of 4. If , then the decomposition will comprise stages. The smallest significant DFT block that will appear in the structure is a 4-point DFT. Both DIF and DIT approaches are possible.
In the DIF approach, the input sequence and the -point DFT are split into four sections such that
**5.31**
which may be interpreted as four ( )-point DFTs. (Compare this with Equation (5.7) in which an -point DFT was split into two -point DFTs.) Using
Equation (5.31) becomes
**5.32**
Letting ,
**5.33**
**5.34**
**5.35**
**5.36**
for Equations (5.33) through (5.36) represent four -point DFTs that in combination yield one -point DFT.
## 5.6 Inverse Fast Fourier Transform
The inverse discrete Fourier transform (IDFT) converts a discrete frequency-domain sequence into a corresponding discrete time-domain sequence . It is defined as
**5.37**
Comparing this with the DFT Equation (5.5), we see that the forward FFT algorithms described previously can be used to compute the inverse DFT if the following two changes are made:
1. Replace twiddle factors by their complex conjugates .
2. Scale the result by .
Program examples illustrating this technique are presented later in this chapter.
## 5.7 Programming Examples
* * *
# Example 5.1
**DFT of a Sequence of Complex Numbers with Output Displayed Using MATLAB® (`stm32f4_dft.c`).**
* * *
This example illustrates the implementation of an -point complex DFT. Program `stm32f4_dft.c`, shown in Listing 5.2, calculates the complex DFT described by
**5.38**
Using Euler's formula to represent a complex exponential, that is,
**5.39**
the real and imaginary parts of are given by
**5.40**
and
**5.41**
* * *
# Listing 5.1 Program `stm32f4_dft.c`
_// stm32f4_dft.c_
**#include** <math.h>
**#define** PI 3.14159265358979
**#define** N 100
**#define** TESTFREQ 800.0
**#define** SAMPLING_FREQ 8000.0
**typedef struct**
{
**float** 32_t real;
**float** 32_t imag;
} COMPLEX;
COMPLEX samples[N];
**void** dft(COMPLEX *x)
{
COMPLEX result[N];
**int** k,n;
**for** (k=0 ; k<N ; k++)
{
result[k].real = 0.0;
result[k].imag = 0.0;
**for** (n=0 ; n<N ; n++)
{
result[k].real += x[n].real*cosf(2*PI*k*n/N)
+ x[n].imag*sinf(2*PI*k*n/N);
result[k].imag += x[n].imag*cosf(2*PI*k*n/N)
- x[n].real*sinf(2*PI*k*n/N);
}
}
**for** (k=0 ; k<N ; k++)
{
x[k] = result[k];
}
}
**int** main()
{
**int** n;
**for** (n=0 ; n<N ; n++)
{
samples[n].real = cos(2*PI*TESTFREQ*n/SAMPLING_FREQ);
samples[n].imag = 0.0;
}
dft(samples);
**while** (1){}
}
* * *
A structured data type `COMPLEX`, comprising two `float32_t` values, is used by the program to represent complex values.
Function `dft()` has been written so that it replaces the time-domain input samples , stored in array `x`, with their frequency-domain representation , although it requires an array, `result`, of `COMPLEX` values for temporary intermediate storage.
As supplied, the time-domain sequence consists of exactly 10 cycles of a real-valued sinusoid. Assuming a sampling frequency of 8 kHz, the frequency of the sinusoid is 800 Hz. The DFT of this sequence is equal to 0 for all except and . These two real values correspond to frequency components at 800 Hz.
It is good practice to test DFT or FFT functions using simple input sequences precisely because the results are straightforward to interpret. Different time-domain input sequences can be used to test function `dft()`, most readily by changing the value of the constant `TESTFREQ` and/or by editing program statements
samples[n].real = cos(2*PI*TESTFREQ*n/SAMPLING_FREQ);
samples[n].imag = 0.0;
In order to test the program, assuming that it has compiled and linked successfully and that you have launched the debugger,
1. Place breakpoints at the following two program statements
dft(samples);
and
while(1){}
2. Run the program to the first breakpoint. At this point, the array `samples` should contain a real-valued time-domain input sequence. The contents of the array `samples` may be viewed in a _Memory_ window in the _MDK-ARM debugger_ as shown in Figure 5.9.
3. Save the contents of array samples (100 values of type `COMPLEX`) to a file by typing
SAVE <filename> <start address>, <end address>
in the _MDK-ARM debugger Command_ window. `start address` is the address in memory of array `samples`, and `end address` is equal to (`start address + 0x190`).
4. The contents of the data file you have created may be viewed using MATLAB function `stm32f4_plot_complex()`. You should see something similar to Figure 5.10.
5. Run the program again. It should halt at the second breakpoint. At this point, function `dft()` has been called, and array `samples` should contain the complex DFT of the time-domain input sequence.
6. Save the contents of array samples to a second data file and plot the complex frequency-domain data using MATLAB function `stm32f4_plot_complex()`. You should see something similar to Figure 5.11.
**Figure 5.9** Complex contents of array `samples` (`TESTFREQ` = 800.0) before calling function `dft()`, viewed in a _Memory_ window in the _MDK-ARM debugger_.
**Figure 5.10** Complex contents of array `samples` (`TESTFREQ` = 800.0) before calling function `dft()`, plotted using MATLAB function `stm32f4_plot_complex()`.
**Figure 5.11** Complex contents of array `samples` (`TESTFREQ` = 800.0) after calling function `dft()`, plotted using MATLAB function `stm32f4_plot_complex()`.
Note the very small magnitude of the imaginary part of . Theoretically, this should be equal to zero, but function `dft()` introduces small arithmetic rounding errors.
Change the frequency of the time-domain input sequence to 900 Hz by editing the definition of the constant `TESTFREQ` to read
#define TESTFREQ 900.0
and repeat the previous steps. You should see a number of nonzero values in the frequency-domain sequence, as shown in Figure 5.12. This effect is referred to as spectral leakage and is due to the fact that the -sample time-domain sequence stored in array `samples` does not now represent an integer number of cycles of a sinusoid. Correspondingly, the frequency of the sinusoid is not exactly equal to one of the discrete frequency components, spaced at intervals of ( ) Hz in the frequency-domain representation of .
**Figure 5.12** Complex contents of array `samples` (`TESTFREQ` = 900.0) after calling function `dft()`, plotted using MATLAB function `stm32f4_plot_complex()`.
Change the frequency of the time-domain input sequence back to 800 Hz and change the program statement
samples[n].real = cos(2*PI*TESTFREQ*n/SAMPLING_FREQ);
to read
samples[n].real = sin(2*PI*TESTFREQ*n/SAMPLING_FREQ);
Repeat the previous steps and you should see that the frequency-domain representation of an odd (as opposed to even) real-valued function is purely imaginary.
Whereas the radix-2 FFT is applicable only if is an integer power of two, the DFT can be applied to an arbitrary length sequence, as illustrated by program `stm32f4_dft.c` (`N` = 100).
### 5.7.1 Twiddle Factors
Part of the efficiency of the FFT is due to the use of precalculated twiddle factors, stored in a lookup table, rather than the repeated evaluation of `sinf()` and `cosf()` functions as implemented in function `dft()` in program `stm32f4_dft.c`. The use of precalculated twiddle factors can be applied to the function `dft()` to give significant computational efficiency improvements. In program `stm32f4_dftw.c`, shown in Listing 5.4, these function calls are replaced by reading precalculated twiddle factors from array `twiddle`. Build and run program `stm32f4_dftw.c` and verify that it gives results similar to those of program `stm32f4_dft.c`.
* * *
# Listing 5.2 Program `stm32f4_dftw.c`
_// stm32f4_dftw.c_
**#include** <math.h>
**#define** PI 3.14159265358979
**#define** N 128
**#define** TESTFREQ 800.0
**#define** SAMPLING_FREQ 8000.0
**typedef struct**
{
**float** 32_t real;
**float** 32_t imag;
} COMPLEX;
COMPLEX samples[N];
COMPLEX twiddle[N];
**void** dftw(COMPLEX *x, COMPLEX *w)
{
COMPLEX result[N];
**int** k,n;
**for** (k=0 ; k<N ; k++)
{
result[k].real=0.0;
result[k].imag = 0.0;
**for** (n=0 ; n<N ; n++)
{
result[k].real += x[n].real*w[(n*k)%N].real
- x[n].imag*w[(n*k)%N].imag;
result[k].imag += x[n].imag*w[(n*k)%N].real
+ x[n].real*w[(n*k)%N].imag;
}
}
**for** (k=0 ; k<N ; k++)
{
x[k] = result[k];
}
}
**int** main()
{
**int** n;
**for** (n=0 ; n<N ; n++)
{
twiddle[n].real = cos(2*PI*n/N);
twiddle[n].imag = -sin(2*PI*n/N);
}
**for** (n=0 ; n<N ; n++)
{
samples[n].real = cos(2*PI*TESTFREQ*n/SAMPLING_FREQ);
samples[n].imag = 0.0;
}
dftw(samples,twiddle);
**while** (1){}
}
* * *
* * *
# Example 5.2
**Comparing Execution Times for Different DFT Functions (`stm32f4_dft.c`, `stm32f4_dftw.c`, `stm32f4_fft.c` and `stm32f4_fft_CMSIS.c`).**
* * *
The execution times of different DFT functions can be estimated using the _Sec_ item in the _Register_ window of the _MDK-ARM debugger_ (Figure 5.13). Edit the preprocessor command
#define N 100
to read
#define N 128
in programs `stm32f4_dft.c` and `stm32f4_dftw.c` so that similar length input sequences will be passed to functions `dft()`, `dftw()`, `fft()`, and `arm_fft_f32()`. The last two functions will work only if the number of points, , is equal to an integer power of 2. Function `fft()` is written in C and is defined in header file `fft.h` (Listing 5.10) and shown in Listing. Function `arm_fft_f32()` is a CMSIS DSP library function.
**Figure 5.13** _MDK-ARM Register_ window showing _Sec_ item.
* * *
# Listing 5.3 Program `stm32f4_fft.c`
_// stm32f4_fft.c_
**#include** <math.h>
**#define** PI 3.14159265358979
**#define** N 128
**#define** TESTFREQ 800.0
**#define** SAMPLING_FREQ 8000.0
**typedef struct**
{
**float** 32_t real;
**float** 32_t imag;
} COMPLEX;
**#include** "fft.h"
COMPLEX samples[N];
COMPLEX twiddle[N];
**int** main()
{
**int** n;
**for** (n=0 ; n< N ; n++)
{
twiddle[n].real = cos(PI*n/N);
twiddle[n].imag = -sin(PI*n/N);
}
**for** (n=0 ; n<N ; n++)
{
samples[n].real = cos(2*PI*TESTFREQ*n/SAMPLING_FREQ);
samples[n].imag = 0.0;
}
fft(samples,N,twiddle);
**while** (1){}
}
* * *
* * *
# Listing 5.4 Function `fft()`
_//fft.h complex FFT function taken from Rulph's C31 book_
**void** fft(COMPLEX *Y, **int** M, COMPLEX *w)
{
COMPLEX temp1,temp2;
**int** i,j,k;
**int** upper_leg, lower_leg;
**int** leg_diff;
**int** num_stages=0;
**int** index, step;
i=1;
**do**
{
num_stages+=1;
i=i*2;
} **while** (i!=M);
leg_diff=M/2;
step=2;
**for** (i=0;i<num_stages;i++)
{
index=0;
**for** (j=0;j<leg_diff;j++)
{
**for** (upper_leg=j;upper_leg<M;upper_leg+=(2*leg_diff))
{
lower_leg=upper_leg+leg_diff;
temp1.real=(Y[upper_leg]).real + (Y[lower_leg]).real;
temp1.imag=(Y[upper_leg]).imag + (Y[lower_leg]).imag;
temp2.real=(Y[upper_leg]).real - (Y[lower_leg]).real;
temp2.imag=(Y[upper_leg]).imag - (Y[lower_leg]).imag;
(Y[lower_leg]).real=temp2.real*(w[index]).real
-temp2.imag*(w[index]).imag;
(Y[lower_leg]).imag=temp2.real*(w[index]).imag
+temp2.imag*(w[index]).real;
(Y[upper_leg]).real=temp1.real;
(Y[upper_leg]).imag=temp1.imag;
}
index+=step;
}
leg_diff=leg_diff/2;
step*=2;
}
j=0;
**for** (i=1;i<(M-1);i++)
{
k=M/2;
**while** (k<=j)
{
j=j-k;
k=k/2;
}
j=j+k;
**if** (i<j)
{
temp1.real=(Y[j]).real;
temp1.imag=(Y[j]).imag;
(Y[j]).real=(Y[i]).real;
(Y[j]).imag=(Y[i]).imag;
(Y[i]).real=temp1.real;
(Y[i]).imag=temp1.imag;
}
}
**return** ;
}
* * *
* * *
# Listing 5.5 Program `stm32f4_fft_CMSIS.c`
_// stm32f4_fft_CMSIS.c_
**#define** ARM_MATH_CM4
**#include** "stm32f4xx.h"
**#include** "arm_math.h"
**#include** "arm_const_structs.h"
**#define** N 128
**#define** TESTFREQ 800.0
**#define** SAMPLING_FREQ 8000.0
float32_t samples[2*N];
**int** main()
{
**int** n;
**for** (n=0 ; n<N ; n++)
{
samples[2*n] = arm_cos_f32(2*PI*TESTFREQ*n/SAMPLING_FREQ);
samples[2*n+1] = 0.0;
}
arm_cfft_f32(&arm_cfft_sR_f32_len128, samples, 0, 1);
**while** (1){}
}
* * *
Then, carry out the following steps for each of the programs `stm32f4_dft.c`, `stm32f4_dftw.c`, `stm32f4_fft.c` (Listing 5.8), and `stm32f4_cfft_CMSIS.c` (Listing 5.11).
1. Place breakpoints at the program statement calling the DFT function and at the next program statement, that is, at program statements
dft(samples);
dftw(samples,twiddle);
fft(samples,N,twiddle);
or
arm_cfft_f32(&arm_cfft_sR_f32_len128, samples, 0, 1);
and
while(1){}
2. Run the program to the first breakpoint and record the value of the _Sec_ item.
3. Run the program again. It should halt at the second breakpoint. At this point, function `dft()`, `dftw()`, `fft()`, or `arm_cfft_f32()` will have been executed.
4. Subtract the previous value of the _Sec_ item from its current value. This will tell you the time in seconds taken to execute function `dft()`, `dftw()`, `fft()`, or `arm_cfft_f32()`.
The results that you should see are summarized in Table 5.1.
**Table 5.1** Execution Times for Functions `dft()`, `dftw()`, `fft()` and `arm_cfft_f32()`
Function Name | _N_ | Execution Time (ms)
---|---|---
`dft()` | 128 | 324.79
`dftw()` | 128 | 3.3307
`fft()` | 128 | 0.1448
`arm_cfft_f32()` | 128 | 0.0622
Even using function `sinf()` and `cosf()` in function `dft()`, the use of twiddle factors very greatly reduces the computational effort expended computing the DFT. The FFT is more than an order of magnitude more efficient than the DFT in this example, and not unexpectedly, the CMSIS DSP library function `arm_cfft_f32()` is even more efficient than function `fft()`.
## 5.8 Frame- or Block-Based Programming
Rather than processing one sample at a time, the DFT algorithm is applicable to blocks, or frames, of samples. Using the DFT in a real-time program, therefore, requires a slightly different approach to that used for input and output in most of the previous lab exercises (interrupt-based i/o). It is possible to implement buffering, and to process blocks of samples, using interrupt-based i/o. However, DMA-based i/o is a more intuitive method for frame-based processing and will be used here.
DMA-based i/o on the TM4C123 and STM32F4 processors was described in Chapter 2.
* * *
# Example 5.3
**DFT of a Signal in Real-Time Using a DFT Function with Precalculated Twiddle Factors (`tm4c123_dft128_dma.c`).**
* * *
Program `tm4c123_dft128_dma.c`, shown in Listing 5.13, combines the DFT function `dftw()` from program `tm4c123_dftw.c` and real-time DMA-based i/o in order to implement a basic form of spectrum analyzer. In spite of its inefficiency compared with the FFT, the DFT implemented using function `dftw()` is capable of execution in real time (for `N` = 128 and a sampling frequency of 8 kHz) on a TM4C123 LaunchPad with a processor clock frequency of 84 MHz. The number of samples in a block is set by the constant `BUFSIZE`, defined in header file `tm4c123_aic3106_init.h`. `BUFSIZE` sets the number of 16-bit sample values that make up one DMA transfer block. Recall that in the TM4C123 processor, separate DMA transfers are carried out for left and right channels, and thus, `BUFSIZE` is equal to the number of sampling instants represented in one DMA transfer. Function `dftw()` makes use of a global constant `N` to represent the number of samples it processes and so inprogram `tm4c123_dft128_dma.c`, `N` is set equal to `BUFSIZE`. In function `Lprocess_buffer()`, local pointers `inBuf` and `outBuf` are used to point to the `LpingIN`, `LpingOUT`, `LpongIN`, or `LpongOUT` buffers as determined by reading the `Lprocbuffer` flag set in interrupt service routine `SSI1IRQHandler()`. Real-valued input samples are copied into `COMPLEX` array `cbuf` before it is passed to function `dftw()`. The complex DFT of each block of real-valued input samples is computed using function `dftw()` and the magnitude of the frequency-domain representation of that block of samples is computed using function `arm_cmplx_mag_f32()`. The magnitude values are returned by that function in `float32_t` array `outbuffer` and are written to the buffer pointed to by `outBuf`.
* * *
# Listing 5.6 Program `tm4c123_dft128_dma.c`
_// tm4c123_dft128_dma.c_
**#include** "tm4c123_aic3104_init.h"
**extern** int16_t LpingIN[BUFSIZE], LpingOUT[BUFSIZE];
**extern** int16_t LpongIN[BUFSIZE], LpongOUT[BUFSIZE];
**extern** int16_t RpingIN[BUFSIZE], RpingOUT[BUFSIZE];
**extern** int16_t RpongIN[BUFSIZE], RpongOUT[BUFSIZE];
**extern** int16_t Lprocbuffer, Rprocbuffer;
**extern volatile** int16_t LTxcomplete, LRxcomplete;
**extern volatile** int16_t RTxcomplete, RRxcomplete;
**#include** "hamm128.h"
**#define** N BUFSIZE
**#define** TRIGGER 28000
**#define** MAGNITUDE_SCALING_FACTOR 32
**typedef struct**
{
**float** real;
**float** imag;
} COMPLEX;
COMPLEX twiddle[BUFSIZE];
COMPLEX cbuf[BUFSIZE];
float32_t outbuffer[BUFSIZE];
**void** dftw(COMPLEX *x, COMPLEX *w)
{
COMPLEX result[N];
**int** k,n;
**for** (k=0 ; k<N ; k++)
{
result[k].real=0.0;
result[k].imag = 0.0;
**for** (n=0 ; n<N ; n++)
{
result[k].real += x[n].real*w[(n*k)%N].real
- x[n].imag*w[(n*k)%N].imag;
result[k].imag += x[n].imag*w[(n*k)%N].real
+ x[n].real*w[(n*k)%N].imag;
}
}
**for** (k=0 ; k<N ; k++)
{
x[k] = result[k];
}
}
**void** Lprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Lprocbuffer PING)
{ inBuf = LpingIN; outBuf = LpingOUT; }
**if** (Lprocbuffer PONG)
{ inBuf = LpongIN; outBuf = LpongOUT; }
**for** (i = 0; i < (BUFSIZE) ; i++)
{
cbuf[i].real = (float32_t)(*inBuf++);
cbuf[i].imag = 0.0;
}
dftw(cbuf,twiddle);
arm_cmplx_mag_f32((float32_t *)(cbuf),outbuffer,BUFSIZE);
**for** (i = 0; i < (BUFSIZE) ; i++)
{
**if** (i0)
*outBuf++ = TRIGGER;
**else**
*outBuf++ = (int16_t)(outbuffer[i]/MAGNITUDE_SCALING_FACTOR);
}
LTxcomplete = 0;
LRxcomplete = 0;
**return** ;
}
**void** Rprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Rprocbuffer PING)
{ inBuf = RpingIN; outBuf = RpingOUT; }
**if** (Rprocbuffer PONG)
{ inBuf = RpongIN; outBuf = RpongOUT; }
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = 0;
}
RTxcomplete = 0;
RRxcomplete = 0;
**return** ;
}
**void** SSI_interrupt_routine( **void** ){ **while** (1){}}
**int** main( **void** )
{
**int** n;
**for** (n=0 ; n< BUFSIZE ; n++)
{
twiddle[n].real = cos(2*PI*n/BUFSIZE);
twiddle[n].imag = -sin(2*PI*n/BUFSIZE);
}
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_DMA,
PGA_GAIN_6_DB);
**while** (1)
{
**while** ((!LTxcomplete)|(!LRxcomplete));
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
Lprocess_buffer();
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
**while** ((!RTxcomplete)|(!RRxcomplete));
Rprocess_buffer();
}
}
* * *
### 5.8.1 Running the Program
The value of constant `BUFSIZE` is defined in file `tm4c123_aic3104_init.h` and may be edited prior to building a project. Check that the value of `BUFSIZE` is equal to 128 for this program example. Build and run the program. Use a signal generator connected to the left channel of the (blue) LINE IN connector on the audio booster pack to input a sinusoidal signal with a peak-to-peak magnitude of approximately 200 mV and connect an oscilloscope to the left channel scope hook. Vary the frequency of the input signal between 100 and 3500 Hz. Figure 5.14 shows an example of what you should see on the oscilloscope screen. In this case, `BUFSIZE` was equal to 128. The two smaller pulses correspond to the magnitudes of the positive and negative frequency components of the sinusoidal input signal computed using the DFT. The larger pulses correspond to impulses added to the output signal every 128 samples by program `tm4c123_dft128_dma.c`, replacing the magnitude of sample , for the purpose of triggering the oscilloscope.
**Figure 5.14** Output signal from program `tm4c123_dft128_dma.c` viewed using an oscilloscope.
For comparison, Figure 5.15 shows the corresponding output signal from program `stm32f4_dft128_dma.c`. The difference between this and the output from program `tm4c123_dft128_dma.c` is the shape of the pulses, and as explored in Chapter 2, this is due to subtle differences in the reconstruction filters in the WM5102 and AIC3104 DACs. In this particular application, it is probably true to say that the results are more readily interpreted using the TMC123 LaunchPad and AIC3104 audio booster pack than using the STM32F407 Discovery and Wolfson audio card.
**Figure 5.15** Output signal from program `stm32f4_dft128_dma.c` viewed using an oscilloscope.
The data in the output buffer is ordered such that the first value corresponds to a frequency of 0 Hz. The next 64 values correspond to frequencies 62.5 Hz (fs/N) to 4 kHz (fs/2) inclusive in steps of 62.5 Hz. The following 63 values correspond to frequencies of 3937.5 Hz to 62.5 Hz inclusive, in steps of 62.5 Hz.
Increase the frequency of the input signal and you should see the two smaller pulses move toward a point halfway between the larger trigger pulses. As the frequency of the input signal approaches 4 kHz, the magnitude of the two smaller pulses should diminish, ideally reaching zero at a frequency of 4 kHz. In fact, a slight degree of aliasing may be evident as the input signal frequency is increased past 4 kHz, and the magnitude of the smaller pulses diminishes, because the magnitude frequency response of the AIC3104 DAC reconstruction filter is only 3 dB down at half the sampling frequency.
### 5.8.2 Spectral Leakage
If the frequency of the sinusoidal input signal is equal to 1750 Hz, then the magnitude of the DFT of a frame of 128 input samples should be zero except at two points, corresponding to frequencies of 1750 Hz. Each block of data output via the DAC will contain one other nonzero value – the trigger pulse inserted at . The three impulses contained in each frame of samples appear on the oscilloscope as three pulses, each with the form of the impulse response of the DAC reconstruction filter. Compare the shapes of the pulses shown in Figure 5.14 with the shape of the pulse shown in Figure 2.45 (output by program `tm4c123_dimpulse_intr.c`). Figure 5.16 shows the output signal corresponding to a 1750 Hz input signal in more detail.
**Figure 5.16** Partial contents of array `outbuffer`, plotted using MATLAB function `tm4c123_plot_real()`, for input sinusoid of frequency 1750 Hz.
As the frequency of the sinusoidal input signal is changed, the shape and the position (relative to the trigger pulses) of the smaller pulses will change. The precise shape of the pulses is due to the characteristics of the reconstruction filter in the AIC3104 codec, as discussed in Chapter 2. The fact that the pulse shape changes with input signal frequency in this example is due to the phenomenon of spectral leakage. Change the frequency of the input signal to 1781 Hz and you should see an output waveform similar to that shown in Figure 5.17.
**Figure 5.17** Detail of output signal from program `tm4c123_dft128_dma.c` for input sinusoid of frequency 1781 Hz.
Program `tm4c123_dft128_dma.c` uses CMSIS DSP library function `arm_cmplx_mag_f32()` in order to compute the magnitude of the complex DFT result returned by function `dftw()`. This is done because function `sqrt()` is very computationally expensive. In addition to copying blocks of data (alternately) to buffers `LpingOUT` and `LpingOUT`, function `Lprocess_buffer()` copies that data to buffer `outbuffer`. This enables the most recent block of output data to be examined after the program has been halted.
After halting the program, type
SAVE <filename> <start address>, <end address>
in the _MDK-ARM debugger Command_ window. `start address` is the address in memory of array `outbuffer`, and `end address` is equal to (`start address + 0x100`). Plot the contents of the data file using MATLAB function `tm4c123_plot_real()`.
Figure 5.16 shows the DFT magnitude (output) data corresponding to the oscilloscope trace of Figure 5.18. The trigger pulse (not shown in Figure 5.16) added to the start of the block of data causes the impulse response of the reconstruction filter to appear on the oscilloscope. It can be deduced from Figure 5.16 that the frequency of the sinusoidal input signal was exactly equal to 1750 Hz, corresponding to 28 , where = 62.5 Hz is the fundamental frequency associated with a block of 128 samples at a sampling rate of 8 kHz. The solitary nonzero frequency-domain value produces an output pulse shape in Figure 5.18 similar to that of the trigger pulse.
**Figure 5.18** Detail of output signal from program `tm4c123_dft128_dma.c` for input sinusoid of frequency 1750 Hz.
In contrast, it may be deduced from Figure 5.19 that the frequency of the sinusoidal input that produced the DFT magnitude data and hence the oscilloscope trace of Figure 5.17 was in between 28 and 29 , that is, between 1750 and 1812.5 Hz. Figure 5.19 illustrates spectral leakage, and Figure 5.17 shows the result of the data shown in Figure 5.19, regarded as time-domain samples, filtered by the reconstruction filter in the AIC3104 codec. The shape of the smaller pulse in Figure 5.17 is different to that of the trigger pulse.
**Figure 5.19** Partial contents of array `outbuffer`, plotted using MATLAB function `tm4c123_plot_real()`, for input sinusoid of frequency 1781 Hz.
#### 5.8.2.1 Modifying Program `tm4c123_dft128_dma.c` to Reduce Spectral Leakage
One method of reducing spectral leakage is to multiply the frames of input samples by a window function prior to computing the DFT. add the preprocessor command
#include "hamm128.h"
to program `tm4c123_dft128_dma.c` and alter the program statement that reads
cbuf[i].real = (float32_t)(*inBuf++);
to read
cbuf[i].real = (float32_t)(*inBuf++)*hamming[i];
File `hamm128.h` contains the declaration of array `hamming`, initialized to contain values representing a 128-point Hamming window. In order to run this program successfully, the value of the constant `BUFSIZE`, set in file `tm4c123_aic3104_init.h`, must be equal to 128. Rebuild and run the program. Figures 5.20 and 5.21 show the shape of the small pulse you can expect to see on the oscilloscope, regardless of the frequency of the sinusoidal input signal, and Figures 5.22 and 5.23 show the corresponding DFT magnitude data. The spectral leakage evident in these figures is less than that in Figures 5.17 and 5.19.
**Figure 5.20** Detail of output signal from program `tm4c123_dft128_dma.c`, modified to apply a Hamming window to blocks of input samples, for input sinusoid of frequency 1750 Hz.
**Figure 5.21** Detail of output signal from program `tm4c123_dft128_dma.c`, modified to apply a Hamming window to blocks of input samples, for input sinusoid of frequency 1781 Hz.
**Figure 5.22** Partial contents of array `outbuffer`, plotted using MATLAB function `tm4c123_plot_real()`, for input sinusoid of frequency 1750 Hz. (Hamming window applied to blocks of input samples.)
**Figure 5.23** Partial contents of array `outbuffer`, plotted using MATLAB function `tm4c123_plot_real()`, for input sinusoid of frequency 1781 Hz. (Hamming window applied to blocks of input samples.)
* * *
# Example 5.4
**FFT of a Real-Time Input Signal Using an FFT Function in C (`tm4c123_fft128_dma.c`).**
* * *
Program `tm4c123_fft128_dma.c` implements a 128-point FFT in real time using an external input signal. It calls an FFT function `fft()` written in C. That function is defined in the separate header file `fft.h` (Listing 5.10). The function was written originally for use with the Texas Instruments C31 DSK and is described in [1].
Program `tm4c123_fft128_dma.c` is similar to program `tm4c123_dft 128_dma.c` in all respects other than its use of function `fft()` in place of the less computationally efficient function `dftw()` and the slightly different computation of twiddle factors. Build and run this program. Repeat the experiments carried out in Example 5.10 and verify that the results obtained are similar.
* * *
# Example 5.5
**FFT of a Real-Time Input Signal Using CMSIS DSP function `arm_cfft_f32()` (`tm4c123_fft128_CMSIS_dma.c`).**
* * *
Program `tm4c123_fft128_CMSIS_dma.c`, shown in Listing 5.14 uses the computationally efficient CMSIS DSP library function `arm_cfft_f32()` in order to calculate the FFT of a block of samples. Other than that, it is similar to the previous two examples and should produce similar results. The twiddle factors used by function `arm_cfft_f32()` are provided by a structure defined in header file `arm_const_structs.h` and the parameter passed to the function must match the value of the constant `BUFSIZE` defined in file `tm4c123_aic3104_init.h`. For example, if the value of `BUFSIZE` is equal to 256, then the address of the structure `arm_cfft_sR_f32_len256` must be passed to function `arm_cfft_f32()`. Similarly, the header file defining the Hamming window used by the program must match the value of the constant `BUFSIZE`. For example, if the value of `BUFSIZE` is equal to 64, then the file `hamm64.h` must be included.
* * *
# Listing 5.7 Program `tm4c123_fft128_CMSIS_dma.c`
_// tm4c123_fft128_CMSIS_dma.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "arm_const_structs.h"
_// the following #include must match BUFSIZE_
_// defined in file tm4c123_aic3104_init.h_
_//#include "hamm64.h"_
**#include** "hamm128.h"
_//#include "hamm256.h"_
**extern** int16_t LpingIN[BUFSIZE], LpingOUT[BUFSIZE];
**extern** int16_t LpongIN[BUFSIZE], LpongOUT[BUFSIZE];
**extern** int16_t RpingIN[BUFSIZE], RpingOUT[BUFSIZE];
**extern** int16_t RpongIN[BUFSIZE], RpongOUT[BUFSIZE];
**extern** int16_t Lprocbuffer, Rprocbuffer;
**extern volatile** int16_t LTxcomplete, LRxcomplete;
**extern volatile** int16_t RTxcomplete, RRxcomplete;
**#define** TRIGGER 28000
**#define** MAGNITUDE_SCALING_FACTOR 32
float32_t cbuf[2*BUFSIZE];
float32_t outbuffer[BUFSIZE];
**void** Lprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
float32_t *cbufptr;
int16_t i;
**if** (Lprocbuffer PING)
{ inBuf = LpingIN; outBuf = LpingOUT; }
**if** (Lprocbuffer PONG)
{ inBuf = LpongIN; outBuf = LpongOUT; }
cbufptr = cbuf;
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*cbufptr++ = (float32_t)(*inBuf++)*hamming[i];
*cbufptr++ = 0.0f;
}
_// the following function call must match BUFSIZE_
_// defined in file tm4c123_aic3104_init.h_
_// arm_cfft_f32( &arm_cfft_sR_f32_len64, (float32_t *)(cbuf), 0, 1);_
arm_cfft_f32(&arm_cfft_sR_f32_len128, (float32_t *)(cbuf), 0, 1);
_// arm_cfft_f32( &arm_cfft_sR_f32_len256, (float32_t *)(cbuf), 0, 1);_
arm_cmplx_mag_f32((float32_t *)(cbuf),outbuffer,BUFSIZE);
**for** (i = 0; i < (BUFSIZE) ; i++)
{
**if** (i0)
*outBuf++ = TRIGGER;
**else**
*outBuf++ = (int16_t)(outbuffer[i]/MAGNITUDE_SCALING_FACTOR);
}
LTxcomplete = 0;
LRxcomplete = 0;
**return** ;
}
**void** Rprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Rprocbuffer PING)
{ inBuf = RpingIN; outBuf = RpingOUT; }
**if** (Rprocbuffer PONG)
{ inBuf = RpongIN; outBuf = RpongOUT; }
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = 0;
}
RTxcomplete = 0;
RRxcomplete = 0;
**return** ;
}
**void** SSI_interrupt_routine( **void** ){ **while** (1){}}
**int** main( **void** )
{
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_DMA,
PGA_GAIN_6_DB);
**while** (1)
{
**while** ((!LTxcomplete)|(!LRxcomplete));
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
Lprocess_buffer();
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
**while** ((!RTxcomplete)|(!RRxcomplete));
Rprocess_buffer();
}
}
* * *
* * *
# Example 5.6
**Real-Time FFT of a Sinusoidal Signal from a Lookup Table (`tm4c123_fft128_sinetable_dma.c`).**
* * *
This example program adapts program `tm4c123_fft128_dma.c` to read input from an array initialized to contain one cycle of a sinusoid. Thus, no signal source is required in order to view output signals similar to those in the previous examples. The input signal, read from array `sine_table`, is output on the right channel of the AIC3104 codec, allowing both input and output signals to be viewed together on an oscilloscope as shown in Figure 5.24. Pressing SW1 on the TM4C123 LaunchPad steps the frequency of the input signal through a range of different values.
**Figure 5.24** Output signal generated by program `tm4c123_fft128_sinetable_dma.c`, displayed using a _Rigol DS1052E_ oscilloscope.
## 5.9 Fast Convolution
Fast convolution is a technique whereby two sequences of (time-domain) samples are convolved not by direct implementation of the convolution sum but by multiplying together their frequency-domain representations. Computation of the convolution sum is computationally expensive for large , transformation between time and frequency domains may be implemented efficiently using the fast Fourier transform. An important application of fast convolution is the implementation of FIR filters in which blocks of input samples are convolved with the filter coefficients to produce blocks of filter output samples.
The steps involved in fast convolution are as follows:
1. Transform a block of input samples into the frequency domain using the FFT.
2. Multiply the frequency-domain representation of the input signal by the frequency-domain representation of the filter coefficients.
3. Transform the result back into the time domain by using the inverse FFT.
The filter coefficients need to be transformed into the frequency domain only once.
A number of considerations must be taken into account for this technique to be implemented in practice.
1. The radix-2 FFT is applicable only to blocks of samples where is an integer power of 2.
2. In order to multiply them together, the frequency-domain representations of the input signal and of the filter coefficients must be the same length.
3. The result of linearly convolving two sample sequences of lengths and is a sequence of length ( ). If an input sequence is split into blocks of samples, the result of convolving each block with a block of filter coefficients will be output samples long. In other words, the output due to one block of _N_ input samples extends beyond the corresponding block of output samples and into the next. These blocks cannot simply be concatenated in order to construct a longer output sequence but must be overlapped and added.
These considerations are addressed by the following:
1. Making an integer power of 2.
2. Processing length blocks of input samples and zero-padding both these samples and the filter coefficients used to length before using a -point FFT. This requires that the number of filter coefficients is less than or equal to .
3. Overlapping and adding the length blocks of output samples obtained using a -point inverse FFT of the result of multiplying frequency-domain representations of input samples and filter coefficients.
* * *
# Example 5.7
**Real-Time Fast Convolution (`tm4c123_fastconv_dma.c`).**
* * *
Fast convolution is implemented by program `tm4c123_fastconv_dma.c`, shown in Listing 5.16.
As described earlier, because multiplication of two signals represented in the frequency domain corresponds to circular, and not linear, convolution in the time domain, it is necessary to zero-pad both the blocks of `BUFSIZE ` input samples and the `N` FIR filter coefficients to a length greater than `(BUFSIZE + N -1)` before transforming into the frequency domain. In this program example, a `(BUFSIZE*2)`-point FFT is used and hence the maximum number of FIR filter coefficients possible is `(BUFSIZE+1)`. Inverse Fourier transformation (DFT) of the result of the multiplication of two `(BUFSIZE*2)`-point signal representations in the frequency domain yields `(BUFSIZE*2)` time-domain samples. Yet, these are the result of processing just `BUFSIZE` time-domain input samples. Blocks of `(BUFSIZE*2)` time-domain output samples are overlapped (by `BUFSIZE` samples) and added together in order to obtain the overall output of the filter in blocks of `BUFSIZE` samples.
* * *
# Listing 5.8 Program `tm4c123_fastconv_dma.c`
_// tm4c123_fastconv_dma.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "lp55.h"
**#include** "fft.h"
**extern** int16_t LpingIN[BUFSIZE], LpingOUT[BUFSIZE];
**extern** int16_t LpongIN[BUFSIZE], LpongOUT[BUFSIZE];
**extern** int16_t RpingIN[BUFSIZE], RpingOUT[BUFSIZE];
**extern** int16_t RpongIN[BUFSIZE], RpongOUT[BUFSIZE];
**extern** int16_t Lprocbuffer, Rprocbuffer;
**extern volatile** int16_t LTxcomplete, LRxcomplete;
**extern volatile** int16_t RTxcomplete, RRxcomplete;
COMPLEX procbuf[2*BUFSIZE],coeffs[2*BUFSIZE];
COMPLEX twiddle[2*BUFSIZE];
**float** overlap[BUFSIZE];
**float** a,b;
**void** Lprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Lprocbuffer PING)
{ inBuf = LpingIN; outBuf = LpingOUT; }
**if** (Lprocbuffer PONG)
{ inBuf = LpongIN; outBuf = LpongOUT; }
**for** (i = 0; i < (2*BUFSIZE) ; i++)
{
procbuf[i].real = 0.0;
procbuf[i].imag = 0.0;
}
**for** (i = 0; i < (BUFSIZE) ; i++)
{
procbuf[i].real = (float32_t)(*inBuf++);
}
fft(procbuf,2*BUFSIZE,twiddle);
**for** (i=0 ; i<(2*BUFSIZE) ; i++)
{
a = procbuf[i].real;
b = procbuf[i].imag;
procbuf[i].real = coeffs[i].real*a
- coeffs[i].imag*b;
procbuf[i].imag = -(coeffs[i].real*b
+ coeffs[i].imag*a);
}
fft(procbuf,2*BUFSIZE,twiddle);
**for** (i=0 ; i<(2*BUFSIZE) ; i++)
{
procbuf[i].real /= (2*BUFSIZE);
}
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = (int16_t)(procbuf[i].real + overlap[i]);
overlap[i] = procbuf[i+BUFSIZE].real;
}
LTxcomplete = 0;
LRxcomplete = 0;
**return** ;
}
**void** Rprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Rprocbuffer PING)
{ inBuf = RpingIN; outBuf = RpingOUT; }
**if** (Rprocbuffer PONG)
{ inBuf = RpongIN; outBuf = RpongOUT; }
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = 0x0000;
}
RTxcomplete = 0;
RRxcomplete = 0;
**return** ;
}
**void** SSI_interrupt_routine( **void** ){ **while** (1){}}
**int** main( **void** )
{
**int** i;
**for** (i=0 ; i< (2*BUFSIZE) ; i++)
{
twiddle[i].real = cos(PI*i/(2*BUFSIZE));
twiddle[i].imag = -sin(PI*i/(2*BUFSIZE));
}
**for** (i=0 ; i<((2*BUFSIZE)) ; i++)
{ coeffs[i].real = 0.0; coeffs[i].imag = 0.0;}
**for** (i=0 ; i<N ; i++) coeffs[i].real = h[i];
fft(coeffs,(2*BUFSIZE),twiddle);
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_DMA,
PGA_GAIN_6_DB);
**while** (1)
{
**while** ((!RTxcomplete)|(!RRxcomplete));
Rprocess_buffer();
**while** ((!LTxcomplete)|(!LRxcomplete));
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
Lprocess_buffer();
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
}
* * *
### 5.9.1 Running the Program
Build and run the program and verify that it implements a low-pass filter, as determined by the use of filter coefficient header file `lp55.h`. Functionally, the program is equivalent to program `tm4c123_fir_dma.c`, described in Chapter 3, and similarly introduces a delay of `BUFSIZE*2` sampling instants to an analog signal passing through the system. The program has been written so that, just as in the case of program `tm4c123_fir_dma.c`, the FIR filter coefficients are read from a separate header file specified by a preprocessor command, for example,
#include "lp55.h"
The maximum possible value of `N` (the number of filter coefficients, defined in the header file), is `(BUFSIZE+1)`.
### 5.9.2 Execution Time of Fast Convolution Method of FIR Filter Implementation
The execution time of the fast convolution algorithm implemented by program may be estimated by observing the pulse output on GPIO pin PE2 using an oscilloscope.
* * *
# Example 5.8
**Graphic Equalizer (`tm4c123_graphicEQ_dma.c`).**
* * *
Listing 5.17 is of program `tm4c123_graphicEQ_dma.c`, which implements a three-band graphic equalizer. It uses CMSIS DSP library function `arm_cfft_f32()` in order implement the complex FFT calculations.
* * *
# Listing 5.9 Program `tm4c123_graphicEQ_dma.c`)
_// tm4c123_graphicEQ_dma.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "GraphicEQcoeff.h"
**#include** "fft.h"
**extern** int16_t LpingIN[BUFSIZE], LpingOUT[BUFSIZE];
**extern** int16_t LpongIN[BUFSIZE], LpongOUT[BUFSIZE];
**extern** int16_t RpingIN[BUFSIZE], RpingOUT[BUFSIZE];
**extern** int16_t RpongIN[BUFSIZE], RpongOUT[BUFSIZE];
**extern** int16_t Lprocbuffer, Rprocbuffer;
**extern volatile** int16_t LTxcomplete, LRxcomplete;
**extern volatile** int16_t RTxcomplete, RRxcomplete;
COMPLEX xL[2*BUFSIZE],coeffs[2*BUFSIZE];
COMPLEX twiddle[2*BUFSIZE];
COMPLEX treble[2*BUFSIZE],bass[2*BUFSIZE];
COMPLEX mid[2*BUFSIZE];
**float** overlap[BUFSIZE];
**float** a,b;
float32_t bass_gain = 0.1;
float32_t mid_gain = 1.0;
float32_t treble_gain = 0.25;
int16_t NUMCOEFFS = sizeof(lpcoeff)/sizeof(float);
**void** Lprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Lprocbuffer PING)
{ inBuf = LpingIN; outBuf = LpingOUT; }
**if** (Lprocbuffer PONG)
{ inBuf = LpongIN; outBuf = LpongOUT; }
**for** (i = 0; i < (2*BUFSIZE) ; i++)
{
xL[i].real = 0.0;
xL[i].imag = 0.0;
}
**for** (i = 0; i < (BUFSIZE) ; i++)
{
xL[i].real = (float32_t)(*inBuf++);
}
fft(xL,2*BUFSIZE,twiddle);
**for** (i=0 ; i<BUFSIZE ; i++)
{
coeffs[i].real = bass[i].real*bass_gain
+ mid[i].real*mid_gain
+ treble[i].real*treble_gain;
coeffs[i].imag = bass[i].imag*bass_gain
+ mid[i].imag*mid_gain
+ treble[i].imag*treble_gain;
}
**for** (i=0 ; i<(2*BUFSIZE) ; i++)
{
a = xL[i].real;
b = xL[i].imag;
xL[i].real = coeffs[i].real*a - coeffs[i].imag*b;
xL[i].imag = -(coeffs[i].real*b + coeffs[i].imag*a);
}
fft(xL,2*BUFSIZE,twiddle);
**for** (i=0 ; i<(2*BUFSIZE) ; i++)
{
xL[i].real /= (2*BUFSIZE);
}
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = (int16_t)(xL[i].real + overlap[i]);
overlap[i] = xL[i+BUFSIZE].real;
}
LTxcomplete = 0;
LRxcomplete = 0;
**return** ;
}
**void** Rprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf;
int16_t i;
**if** (Rprocbuffer PING)
{ inBuf = RpingIN; outBuf = RpingOUT; }
**if** (Rprocbuffer PONG)
{ inBuf = RpongIN; outBuf = RpongOUT; }
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = 0x0000;
}
RTxcomplete = 0;
RRxcomplete = 0;
**return** ;
}
**void** SSI_interrupt_routine( **void** ){ **while** (1){}}
**int** main( **void** )
{
**int** i;
**for** (i=0 ; i< (2*BUFSIZE) ; i++)
{
twiddle[i].real = cos(PI*i/(2*BUFSIZE));
twiddle[i].imag = -sin(PI*i/(2*BUFSIZE));
}
**for** (i=0 ; i<(BUFSIZE*2) ; i++)
{
coeffs[i].real = 0.0;
coeffs[i].imag = 0.0;
bass[i].real = 0.0;
mid[i].real = 0.0 ;
treble[i].real = 0.0;
bass[i].imag = 0.0;
mid[i].imag = 0.0 ;
treble[i].imag = 0.0;
}
**for** (i=0 ; i<(BUFSIZE) ; i++)
{
overlap[i] = 0.0;
}
**for** (i=0 ; i<NUMCOEFFS ; i++)
{
bass[i].real = lpcoeff[i];
mid[i].real = bpcoeff[i];
treble[i].real = hpcoeff[i];
}
fft(bass,(2*BUFSIZE),twiddle);
fft(mid,(2*BUFSIZE),twiddle);
fft(treble,(2*BUFSIZE),twiddle);
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_DMA,
PGA_GAIN_6_DB);
**while** (1)
{
**while** ((!RTxcomplete)|(!RRxcomplete));
Rprocess_buffer();
**while** ((!LTxcomplete)|(!LRxcomplete));
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
Lprocess_buffer();
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
}
* * *
The coefficient header file `graphicEQcoeff.h` contains three sets of coefficients: a low-pass filter with a cutoff frequency of 1.3 kHz, a band-pass filter with cutoff frequencies at 1.3 and 2.6 kHz, and a high-pass filter with a cutoff frequency of 2.6 kHz. These filters were designed using the MATLAB function `fir1()`. The three sets of filter coefficients are transformed into the frequency domain just once, and subsequently, linear, weighted sums of their frequency domain representations are used in the fast convolution process. A similar overlap-add scheme to that used in the fast convolution example is employed. The gains in the three frequency bands are set by the program statements
float32_t bass_gain = 0.1;
float32_t mid_gain = 1.0;
float32_t treble_gain = 0.25;
As provided, the program would allow for the values of these gains to be changed while it is running. The weighted sum of the frequency-domain representations of the three filters is computed for each block of samples by the following program statements.
for (i=0 ; i<BUFSIZE ; i++)
{
coeffs[i].real = bass[i].real*bass_gain
+ mid[i].real*mid_gain
+ treble[i].real*treble_gain;
coeffs[i].imag = bass[i].imag*bass_gain
+ mid[i].imag*mid_gain
+ treble[i].imag*treble_gain;
}
However, as it stands, the program does not include a mechanism for altering the gains.
The magnitude frequency response of the graphic equalizer may be observed using the FFT function on an oscilloscope or using _Goldwave_ and either by replacing the programs statement
xL[i].real = (float32_t)(*inBuf++);
with the program statement
xL[i].real = (float32_t)(prbs(8000));
or by using a microphone as an input device and blowing gently on the microphone.
Figure 5.25 shows the frequency content of pseudorandom noise that has been filtered by the graphic equalizer with the gain settings `bass_gain = 0.1`, `mid_gain = 0.1`, and `treble_gain = 0.25`.
**Figure 5.25** Output signal from program `tm4c123_graphicEQ_CMSIS_dma.c`, displayed using _Goldwave_ , for a pseudorandom noise input signal. `bass_gain = 0.1`, `mid_gain = 0.1`, `treble_gain = 0.25`.
## Reference
1. 1. Chassaing, R., " _Digital Signal Processing Laboratory Experiments with C31_ ", John Wiley & Sons, Inc., New York, 1999.
# Chapter 6
Adaptive Filters
## 6.1 Introduction
Adaptive filters are used in situations where the characteristics or statistical properties of the signals involved are either unknown or time-varying. Typically, a nonadaptive FIR or IIR filter is designed with reference to particular signal characteristics. But if the signal characteristics encountered by such a filter are not those for which it was specifically designed, then its performance may be suboptimal. The coefficients of an adaptive filter are adjusted in such a way that its performance according to some measure improves with time and approaches optimum performance. Thus, an adaptive filter can be very useful either when there is uncertainty about the characteristics of a signal or when these characteristics are time-varying.
Adaptive systems have the potential to outperform nonadaptive systems. However, they are, by definition, nonlinear and more difficult to analyze than linear, time-invariant systems. This chapter is concerned with linear adaptive systems, that is, systems that, when adaptation is inhibited, have linear characteristics. More specifically, the filters considered here are adaptive FIR filters.
At the heart of the adaptive systems considered in this chapter is the structure shown in block diagram form in Figure 6.1.
**Figure 6.1** Basic adaptive filter structure.
Its component parts are an adjustable filter, a mechanism for performance measurement (in this case, a comparator to measure the instantaneous error between adaptive filter output and desired output) and an adaptation mechanism or algorithm. In subsequent figures, the adaptation mechanism is incorporated into the adjustable filter block as shown in Figure 6.2
**Figure 6.2** Simplified block diagram of basic adaptive filter structure.
It is conventional to refer to the coefficients of an adaptive FIR filter as weights, and the filter coefficients of the adaptive filters in several of the program examples in this chapter are stored in arrays using the identifier `w` rather than `h` as tended to be used for FIR filters in Chapter 3. The weights of the adaptive FIR filter are adjusted so as to minimize the mean squared value of the error . The mean squared error is defined as the expected value, or hypothetical mean, of the square of the error, that is,
**6.1**
This quantity may also be interpreted as representing the variance, or power, of the error signal.
## 6.2 Adaptive Filter Configurations
Four basic configurations into which the adaptive filter structure of Figure 6.2 may be incorporated are commonly used. The differences between the configurations concern the derivation of the desired output signal . Each configuration may be explained assuming that the adaptation mechanism _will_ adjust the filter weights so as to minimize the mean squared value of the error signal but without the need to understand _how_ the adaptation mechanism works.
### 6.2.1 Adaptive Prediction
In this configuration (Figure 6.3), a delayed version of the desired signal is input to the adaptive filter, which predicts the current value of the desired signal . In doing this, the filter learns something about the characteristics of the signal and/or of the process that generated it. Adaptive prediction is used widely in signal encoding and noise reduction.
**Figure 6.3** Basic adaptive filter structure configured for prediction.
### 6.2.2 System Identification or Direct Modeling
In this configuration (Figure 6.4), broadband noise is input both to the adaptive filter and to an unknown plant or system. If adaptation is successful and the mean squared error is minimized (to zero in an idealized situation), then it follows that the outputs of both systems (in response to the same input signal) are similar and that the characteristics of the systems are equivalent. The adaptive filter has identified the unknown plant by taking on its characteristics. This configuration was introduced in Chapter 2 as a means of identifying or measuring the characteristics of an audio codec and was used again in some of the examples in Chapters 3 and . A common application of this configuration is echo cancellation in communication systems.
**Figure 6.4** Basic adaptive filter structure configured for system identification.
### 6.2.3 Noise Cancellation
This configuration differs from the previous two in that while the mean squared error is minimized, it is not minimized to zero, even in the ideal case, and it is the error signal rather than the adaptive filter output that is the principal signal of interest. Consider the system illustrated in Figure 6.5. A primary sensor is positioned so as to pick up signal . However, this signal is corrupted by uncorrelated additive noise , that is, the primary sensor picks up signal . A second reference sensor is positioned so as to pick up noise from the same source as but without picking up signal . This noise signal is represented in Figure 6.5 as . Since they originate from the same source, it may be assumed that noise signals and are strongly correlated. It is assumed here also that neither noise signal is correlated with signal . In practice, the reference sensor may pick up signal to some degree, and there may be some correlation between signal and noise, leading to a reduction in the performance of the noise cancellation system.
**Figure 6.5** Basic adaptive filter structure configured for noise cancellation.
The noise cancellation system aims to subtract the additive noise from the primary sensor output . The role of the adaptive filter is therefore to estimate, or derive, from , and intuitively (since the two signals originate from the same source), this appears feasible.
An alternative representation of the situation described earlier, regarding the signals detected by the two sensors and the correlation between and , is shown in Figure 6.6. Here, it is emphasized that and have taken different paths from the same noise source to the primary and reference sensors, respectively. Note the similarity between this and the system identification configuration shown in Figure 6.4. The mean squared error may be minimized if the adaptive filter is adjusted to have similar characteristics to the block shown between signals and . In effect, the adaptive filter learns the difference in the paths between the noise source and the primary and reference sensors, represented in Figure 6.6 by the block labeled . The minimized error signal will, in this idealized situation, be equal to the signal , that is, a noise-free signal.
**Figure 6.6** Alternative representation of basic adaptive filter structure configured for noise cancellation emphasizing the difference in paths from a single noise source to primary and reference sensors.
### 6.2.4 Equalization
In this configuration (Figure 6.7), the adaptive filter is used to recover a delayed version of signal from signal (formed by passing through an unknown plant or filter). The delay is included to allow for propagation of signals through the plant and adaptive filter. After successful adaptation, the adaptive filter takes on the inverse characteristics of the unknown filter, although there are limitations on the nature of the unknown plant for this to be achievable. Commonly, the unknown plant is a communication channel and is the signal being transmitted through that channel. It is natural at this point to ask why, if a delayed but unfiltered version of signal is available for use as the desired signal at the receiver, it is necessary to attempt to derive a delayed but unfiltered version of from signal . In general, a delayed version of is not available at the receiver, but for the purposes of adaptation over short periods of time, it is effectively made available by transmitting a predetermined sequence and using a copy of this stored at the receiver as the desired signal. In most cases, a pseudorandom, broadband signal is used for this purpose.
**Figure 6.7** Basic adaptive filter structure configured for equalization.
## 6.3 Performance Function
Consider the block diagram representation of an FIR filter introduced in Chapter 3 and shown again in Figure 6.8.
**Figure 6.8** Block diagram representation of FIR filter.
In the following equations, the filter weights and the input samples stored in the FIR filter delay line at the th sampling instant are represented as vectors and , respectively, where
**6.2**
and
**6.3**
Hence, using vector notation, the filter output at the th sample instant is given by
**6.4**
Instantaneous error is given by
**6.5**
and instantaneous squared error by
**6.6**
Mean squared error (expected value of squared error) is therefore given by
**6.7**
The expected value of a sum of variables is equal to the sum of the expected values of those variables. However, the expected value of a product of variables is the product of the expected values of the variables only if those variables are statistically independent. Signals and are generally not statistically independent. If the signals and are statistically time-invariant, the expected values of the products and are constants and hence
**6.8**
where the vector of cross-correlation between input and desired output is defined as
**6.9**
and the input autocorrelation matrix is defined as
**6.10**
The performance function, or surface, is a quadratic function of and as such is referred to in the following equations as . Since it is a quadratic function of , it has one global minimum corresponding to . The optimum value of the weights, , may be found by equating the gradient of the performance surface to zero, that is,
**6.11**
and hence, in terms of the statistical quantities just described
**6.12**
and hence,
**6.13**
In a practical, real-time application, solving Equation (6.13) may not be possible either because signal statistics are unavailable or simply because of the computational effort involved in inverting the input autocorrelation matrix .
### 6.3.1 Visualizing the Performance Function
If there is just one weight in the adaptive filter, then the performance function will be a parabolic curve, as shown in Figure 6.9. If there are two weights, the performance function will be a three-dimensional surface, a paraboloid, and if there are more than two weights, then the performance function will be a hypersurface (i.e., difficult to visualize or to represent in a figure). In each case, the role of the adaptation mechanism is to adjust the filter coefficients to those values that correspond to a minimum in the performance function.
**Figure 6.9** Performance function for single weight case.
## 6.4 Searching for the Minimum
An alternative to solving Equation (6.13) by matrix inversion is to _search_ the performance function for , starting with an arbitrary set of weight values and adjusting these at each sampling instant.
One way of doing this is to use the steepest descent algorithm. At each iteration (of the algorithm) in a discrete-time implementation, the weights are adjusted in the direction of the negative gradient of the performance function and by an amount proportional to the magnitude of the gradient, that is,
**6.14**
where represents the value of the weights at the th iteration and is an arbitrary positive constant that determines the rate of adaptation. If is too large, then instability may ensue. If the statistics of the signals and are known, then it is possible to set a quantitative upper limit on the value of , but in practice, it is usual to set equal to a very low value. One iteration of the steepest descent algorithm described by Equation (6.14) is illustrated for the case of a single weight in Figure 6.10.
**Figure 6.10** Steepest descent algorithm illustrated for single weight case.
## 6.5 Least Mean Squares Algorithm
The steepest descent algorithm requires an estimate of the gradient of the performance surface at each step. But since this depends on the statistics of the signals involved, it may be computationally expensive to obtain. The least mean squares (LMS) algorithm uses instantaneous error squared as an estimate of mean squared error and yields an estimated gradient
**6.15**
or
**6.16**
Equation (6.6) gave an expression for instantaneous squared error
Differentiating this with respect to ,
**6.17**
Hence, the steepest descent algorithm, using this gradient estimate, is
**6.18**
This is the LMS algorithm. Gradient estimate is imperfect, and, therefore, the LMS adaptive process may be noisy. This is a further motivation for choosing a conservatively low value for .
The LMS algorithm is well established, computationally inexpensive, and, therefore, widely used. Other methods of adaptation include recursive least squares, which is more computationally expensive but converges faster, and normalized LMS, which takes explicit account of signal power. Given that in practice the choice of value for is somewhat arbitrary, a number of simpler fixed step size variations are practicable although, somewhat counterintuitively, these variants may be computationally more expensive to implement using a digital signal processor with single-cycle multiply capability than the straightforward LMS algorithm.
### 6.5.1 LMS Variants
For the sign-error LMS algorithm, Equation (6.18) becomes
**6.19**
where is the signum function
**6.20**
For the sign-data LMS algorithm, Equation (6.18) becomes
**6.21**
For the sign-sign LMS algorithm, Equation (6.18) becomes
**6.22**
which reduces to
**6.23**
and which involves no multiplications.
### 6.5.2 Normalized LMS Algorithm
The rate of adaptation of the standard LMS algorithm is sensitive to the magnitude of the input signal . This problem may be ameliorated by using the normalized LMS algorithm in which the adaptation rate in the LMS algorithm is replaced by
**6.24**
## 6.6 Programming Examples
The following program examples illustrate adaptive filtering using the LMS algorithm applied to an FIR filter.
* * *
# Example 6.1
**Adaptive Filter Using C Code (`stm32f4_adaptive.c`).**
* * *
This example implements the LMS algorithm as a C program. It illustrates the following steps for the adaptation process using the adaptive structure shown in Figure 6.2.
1. Obtain new samples of the desired signal and the reference input to the adaptive filter .
2. Calculate the adaptive FIR filter output , applying Equation (6.4).
3. Calculate the instantaneous error by applying Equation (6.5).
4. Update the coefficient (weight) vector by applying the LMS algorithm (6.18).
5. Shift the contents of the adaptive filter delay line, containing previous input samples, by one.
6. Repeat the adaptive process at the next sampling instant.
Program `stm32f4_adaptive.c` is shown in Listing 6.2. The desired signal is chosen to be , and the input to the adaptive filter is chosen to be . The adaptation rate , filter order , and number of samples processed in the program are equal to 0.01, 21, and 60, respectively. The overall output is the adaptive filter output , which converges to the desired cosine signal .
* * *
# Listing 6.1 Program `stm32f4_adaptive.c.`
_// stm32f4_adaptive.c_
**#include** "stm32f4_wm5102_init.h"
**#define** BETA 0.01f _// learning rate_
**#define** N 21 _// number of filter coeffs_
**#define** NUM_ITERS 60 _// number of iterations_
float32_t desired[NUM_ITERS]; _// storage for results_
float32_t y_out[NUM_ITERS];
float32_t error[NUM_ITERS];
float32_t w[N] = {0.0}; _// adaptive filter weights_
float32_t x[N] = {0.0}; _// adaptive filter delay line_
**int** i, t;
float32_t d, y, e;
**int** main()
{
**for** (t = 0; t < NUM_ITERS; t++)
{
x[0] = sin(2*PI*t/8); _// get new input sample_
d = 2*cos(2*PI*t/8); _// get new desired output_
y = 0; _// compute filter output_
**for** (i = 0; i <= N; i++)
y += (w[i]*x[i]);
e = d - y; _// compute error_
**for** (i = N; i >= 0; i--)
{
w[i] += (BETA*e*x[i]); _// update filter weights_
**if** (i != 0)
x[i] = x[i-1]; _// shift data in delay line_
}
desired[t] = d; _// store results_
y_out[t] = y;
error[t] = e;
}
**while** (1){}
}
* * *
Because the program does not use any real-time input or output, it is not necessary for it to call function `stm32f4_wm5102_init()`. Figure 6.11 shows plots of the desired output `desired`, adaptive filter output `y_out`, and error `error`, plotted using MATLAB® function `stm32f4_plot_real()` after the contents of those three arrays have been saved to files by typing
SAVE desired.dat <start address>, <start address + 0xF0>
SAVE y_out.dat <start address>, <start address + 0xF0>
SAVE error.dat <start address>, <start address + 0xF0>
in the _Command_ window in the _MDK-ARM debugger_ , where `start address` is the address of arrays `desired`, `y_out`, and `error`. Within 60 sampling instants, the filter output effectively converges to the desired cosine signal. Change the adaptation or convergence rate `BETA` to 0.02 and verify a faster rate of adaptation and convergence.
**Figure 6.11** Plots of (a) desired output, (b) adaptive filter output, and (c) error generated using program `stm32f4_adaptive.c` and displayed using MATLAB function `stm32f4_plot_real()`.
* * *
# Example 6.2
**Adaptive Filter for Noise Cancellation Using Sinusoids as Inputs (`tm4c123_adaptnoise_intr.c`).**
* * *
This example illustrates the use of the LMS algorithm to cancel an undesired sinusoidal noise signal. Listing 6.4 shows program `tm4c123_adaptnoise_intr.c`, which implements an adaptive FIR filter using the structure shown in Figure 6.5.
* * *
# Listing 6.2 Program `tm4c123_adaptnoise_intr.c.`
_// tm4c123_adaptnoise_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#define** SAMPLING_FREQ 8000
**#define** NOISE_FREQ 1200.0
**#define** SIGNAL_FREQ 2500.0
**#define** NOISE_AMPLITUDE 8000.0
**#define** SIGNAL_AMPLITUDE 8000.0
**#define** BETA 4E-12f _// adaptive learning rate_
**#define** N 10 _// number of weights_
float32_t w[N]; _// adaptive filter weights_
float32_t x[N]; _// adaptive filter delay line_
float32_t theta_increment_noise;
float32_t theta_noise = 0.0;
float32_t theta_increment_signal;
float32_t theta_signal = 0.0;
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
float32_t inputL, inputR;
int16_t i;
float32_t yn, error, signal, signoise, refnoise, dummy;
SSIDataGet(SSI0_BASE,&sample_data.bit32);
inputL = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
inputR = (float32_t)(sample_data.bit16[0]);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
theta_increment_noise = 2*PI*NOISE_FREQ/SAMPLING_FREQ;
theta_noise += theta_increment_noise;
**if** (theta_noise > 2*PI) theta_noise -= 2*PI;
theta_increment_signal = 2*PI*SIGNAL_FREQ/SAMPLING_FREQ;
theta_signal += theta_increment_signal;
**if** (theta_signal > 2*PI) theta_signal -= 2*PI;
refnoise = (NOISE_AMPLITUDE*arm_cos_f32(theta_noise));
signoise = (NOISE_AMPLITUDE*arm_sin_f32(theta_noise));
signal = (SIGNAL_AMPLITUDE*arm_sin_f32(theta_signal));
x[0] = refnoise; _// reference input to adaptive filter_
yn = 0; _// compute adaptive filter output_
**for** (i = 0; i < N; i++)
yn += (w[i] * x[i]);
error = signal + signoise - yn; _// compute error_
**for** (i = N-1; i >= 0; i--) _// update weights_
{ _// and delay line_
dummy = BETA*error;
dummy = dummy*x[i];
w[i] = w[i] + dummy;
x[i] = x[i-1];
}
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
sample_data.bit32 = ((int16_t)(error));
SSIDataPut(SSI1_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(signal + signoise));
SSIDataPut(SSI0_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main()
{
int16_t i;
**for** (i=0 ; i<N ; i++)
{
w[i] = 0.0;
x[i] = 0.0;
}
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1){}
}
* * *
A desired sinusoid `signal`, of frequency `SIGNAL_FREQ` (2500 Hz), with an added (undesired) sinusoid `signoise`, of frequency `NOISE_FREQ` (1200 Hz), forms one of two inputs to the noise cancellation structure and represents the signal plus noise from the primary sensor in Figure 6.12. A sinusoid `refnoise`, with a frequency of `NOISE_FREQ` (1200 Hz), represents the reference noise signal in Figure 6.12 and is the input to an `N`-coefficient adaptive FIR filter. The signal `refnoise` is strongly correlated with the signal `signoise` but not with the desired `signal`. At each sampling instant, the output of the adaptive FIR filter is calculated, its `N` weights are updated, and the contents of the delay line `x` are shifted. The `error` signal is the overall desired output of the adaptive structure. It comprises the desired signal and additive noise from the primary sensor (`signal + signoise`) from which the adaptive filter output `yn` has been subtracted. The input signals used in this example are generated within the program and both the input signal `signal + signoise` and the output signal `error` are output via the AIC3104 codec on right and left channels, respectively.
**Figure 6.12** Block diagram representation of program `tm4c213_adaptnoise_intr.c`.
Build and run the program and verify the following output result. The undesired 1200-Hz sinusoidal component of the output signal (error) is gradually reduced (canceled), while the desired 2500-Hz signal remains. A faster rate of adaptation can be observed by using a larger value of beta. However, if beta is too large, the adaptation process may become unstable. Program `tm4c213_adaptnoise_intr.c` demonstrates real-time adjustments to the coefficients of an FIR filter. The program makes use of CMSIS DSP library functions `arm_sin_f32()` and `arm_cos_f32()` in order to compute signal and noise signal values. Standard functions `sin()` and `cos()` would be computationally too expensive to use in real time. The adaptive FIR filter is implemented straightforwardly using program statements
yn = 0; // compute adaptive filter output
for (i = 0; i < N; i++)
yn += (w[i] * x[i]);
error = signal + signoise - yn; // compute error
for (i = N-1; i >= 0; i--) // update weights
{ // and delay line
dummy = BETA*error;
dummy = dummy*x[i];
w[i] = w[i] + dummy;
x[i] = x[i-1];
}
in which the entire contents of the filter delay line `x` are shifted at each sampling instant. Program `tm4c123_adaptnoise_CMSIS_intr.c` shown in Listing 6.5 makes use of the more computationally efficient CMSIS DSP library function `arm_lms_f32()`.
* * *
# Listing 6.3 Program `tm4c123_adaptnoise_CMSIS_intr.c).`
_// tm4c123_adaptnoise_CMSIS_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#define** SAMPLING_FREQ 8000
**#define** NOISE_FREQ 1200.0f
**#define** SIGNAL_FREQ 2500.0f
**#define** NOISE_AMPLITUDE 8000.0f
**#define** SIGNAL_AMPLITUDE 8000.0f
**#define** BETA 1E-13
**#define** NUM_TAPS 10
**#define** BLOCK_SIZE 1
float32_t theta_increment_noise;
float32_t theta_noise = 0.0;
float32_t theta_increment_signal;
float32_t theta_signal = 0.0;
float32_t firStateF32[BLOCK_SIZE + NUM_TAPS -1];
float32_t firCoeffs32[NUM_TAPS] = {0.0};
arm_lms_instance_f32 S;
**void** SSI_interrupt_routine( **void** )
}
AIC3104_data_type sample_data;
float32_t inputl, inputr;
float32_t yout, error, signal, signoise
float32_t refnoise, sigplusnoise;
SSIDataGet(SSI0_BASE,&sample_data.bit32);
inputl = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
inputr = (float32_t)(sample_data.bit16[0]);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
theta_increment_noise = 2*PI*NOISE_FREQ/SAMPLING_FREQ;
theta_noise += theta_increment_noise;
**if** (theta_noise> 2*PI) theta_noise -= 2*PI;
theta_increment_signal = 2*PI*SIGNAL_FREQ/SAMPLING_FREQ;
theta_signal += theta_increment_signal;
**if** (theta_signal> 2*PI) theta_signal -= 2*PI;
refnoise = (NOISE_AMPLITUDE*arm_cos_f32(theta_noise));
signoise = (NOISE_AMPLITUDE*arm_sin_f32(theta_noise));
signal = (SIGNAL_AMPLITUDE*arm_sin_f32(theta_signal));
sigplusnoise = signoise+signal;
arm_lms_f32(&S, &refnoise, &sigplusnoise,
&yout, &error, 1);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
sample_data.bit32 = ((int16_t)(error));
SSIDataPut(SSI0_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(sigplusnoise));
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main()
{
arm_lms_init_f32(&S, NUM_TAPS, firCoeffs32,
firStateF32, BETA, 1);
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1);
}
* * *
### 6.6.1 Using CMSIS DSP Function `arm_lms_f32()`
In order to implement an adaptive FIR filter using CMSIS DSP library function `arm_lms_f32()`, as in the previous example, the following variables must be declared.
1. A structure of type `arm_lms_instance_f32`
2. A floating-point state variable array `firStateF32`
3. A floating-point array of filter coefficients `firCoeffs32`.
The `arm_lms_instance_f32` structure comprises an integer value equal to the number of coefficients, `N` used by the filter, a floating-point value equal to the learning rate `BETA`, and pointers to the array of `N` floating-point filter coefficients and to the `N + BLOCKSIZE - 1` floating-point state variable array. The state variable array contains current and previous values of the input to the filter. Before calling function `arm_lms_f32()`, the structure is initialized using function `arm_lms_init_f32()`. This assigns values to the elements of the structure and initializes the contents of the state variable array to zero. Function `arm_lms_init_f32()` does not allocate memory for the filter coefficient or state variable arrays. They must be declared separately. Function `arm_lms_init_f32()` does not initialize or alter the contents of the filter coefficient array.
Subsequently, function `arm_lms_f32()` may be called, passing to it pointers to the `arm_lms_instance_f32` structure and to floating-point arrays of input samples, output samples, desired output samples, and error samples. Each of these arrays contains `BLOCKSIZE` samples. Each call to function `arm_lms_f32()` processes `BLOCKSIZE` samples, and although it is possible to set `BLOCKSIZE` to one, the function is optimized according to the architecture of the ARM Cortex-M4 to operate on at least four samples per call. More details of function `arm_lms_f32()` can be found in the CMSIS documentation [1].
* * *
# Example 6.3
**Adaptive FIR Filter for Noise Cancellation Using External Inputs (`stm32f4_noise_cancellation_CMSIS_dma.c`).**
* * *
This example extends the previous one to cancel an undesired noise signal using external inputs. Program `stm32f4_noise_cancellation_CMSIS_dma.c`, shown in Listing 6.7, requires two external inputs, a desired signal, and a reference noise signal to be input to left and right channels of LINE IN, respectively. A stereo 3.5-mm jack plug to dual RCA jack plug cable is useful for implementing this example using two different signal sources. Alternatively, a test input signal is provided in file `speechnoise.wav`. This may be played through a PC sound card and input to the audio card via a stereo 3.5 mm jack plug to 3.5 mm jack plug cable. `speechnoise.wav` comprises pseudorandom noise on the left channel and speech on the right channel.
* * *
# Listing 6.4 Program `stm32f4_noise_cancellation_CMSIS_dma.c`
_// stm32f4_noise_cancellation_CMSIS_dma.c_
**#include** "stm32f4_wm5102_init.h"
**#include** "bilinear.h"
**extern** uint16_t pingIN[BUFSIZE], pingOUT[BUFSIZE]
**extern** uint16_t pongIN[BUFSIZE], pongOUT[BUFSIZE];
**int** rx_proc_buffer, tx_proc_buffer;
**volatile int** RX_buffer_full = 0;
**volatile int** TX_buffer_empty = 0;
**#define** BLOCK_SIZE 1
**#define** NUM_TAPS 32
float32_t beta = 1e-11;
float32_t firStateF32[BLOCK_SIZE + NUM_TAPS -1];
float32_t firCoeffs32[NUM_TAPS] = {0.0};
arm_lms_instance_f32 S;
float32_t input, signoise, wn, yn, yout, error;
**float** w[NUM_SECTIONS][2] = {0.0f, 0.0f}; _// IIR coeffs_
**void** DMA1_Stream3_IRQHandler()
{
**if** (DMA_GetITStatus(DMA1_Stream3,DMA_IT_TCIF3))
{
DMA_ClearITPendingBit(DMA1_Stream3,DMA_IT_TCIF3);
**if** (DMA_GetCurrentMemoryTarget(DMA1_Stream3))
rx_proc_buffer = PING;
**else**
rx_proc_buffer = PONG;
RX_buffer_full = 1;
}
}
**void** DMA1_Stream4_IRQHandler()
{
**if** (DMA_GetITStatus(DMA1_Stream4,DMA_IT_TCIF4))
{
DMA_ClearITPendingBit(DMA1_Stream4,DMA_IT_TCIF4);
**if** (DMA_GetCurrentMemoryTarget(DMA1_Stream4))
tx_proc_buffer = PING;
**else**
tx_proc_buffer = PONG;
TX_buffer_empty = 1;
}
}
**void** process_buffer()
{
**int** i;
uint16_t *rxbuf, *txbuf;
float32_t refnoise, signal;
int16_t left_in_sample, right_in_sample;
**int** section;
_// determine which buffers to use_
**if** (rx_proc_buffer PING) rxbuf = pingIN;
**else** rxbuf = pongIN;
**if** (tx_proc_buffer PING) txbuf = pingOUT;
**else** txbuf = pongOUT;
**for** (i=0 ; i<(BUFSIZE/2) ; i++)
{
right_in_sample = *rxbuf++;
left_in_sample = *rxbuf++;
refnoise = (float32_t)(right_in_sample);
signal = (float32_t)(left_in_sample);
input = refnoise;
**for** (section=0 ; section<NUM_SECTIONS ; section++)
{
wn = input - a[section][1]*w[section][0]
- a[section][2]*w[section][1];
yn = b[section][0]*wn + b[section][1]*w[section][0]
+ b[section][2]*w[section][1];
w[section][1] = w[section][0];
w[section][0] = wn;
input = yn;
}
signoise = yn + signal;
arm_lms_f32(&S, &refnoise, &signoise,
&yout, &error, 1);
*txbuf++ = (int16_t)(signoise);
*txbuf++ = (int16_t)(error);
}
TX_buffer_empty = 0;
RX_buffer_full = 0;
}
**int** main()
{
arm_lms_init_f32(&S, NUM_TAPS, firCoeffs32,
firStateF32, beta, 1);
stm32_wm5102_init(FS_8000_HZ,
WM5102_LINE_IN,
IO_METHOD_DMA);
**while** (1)
{
**while** (!(RX_buffer_full && TX_buffer_empty)){}
GPIO_SetBits(GPIOD, GPIO_Pin_15);
process_buffer();
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
}
}
* * *
Figure 6.13 shows the program in block diagram. Within the program, a primary noise signal, correlated to the reference noise signal input on the left channel, is formed by passing the reference noise through an IIR filter. The primary noise signal is added to the desired signal (speech) input on the right channel.
**Figure 6.13** Block diagram representation of program `tm4c123_noise_cancellation_intr.c`.
Build and run the program and test it using file `speechnoise.wav`. As adaptation takes place, the output on the left channel of LINE OUT should gradually change from speech plus noise to speech only. You may need to adjust the volume at which you play the file `speechnoise.wav`. If the input signals are too quiet, then adaptation may be very slow. This is an example of the disadvantage of the LMS algorithm versus the NLMS algorithm. After adaptation has taken place, the 32 coefficients of the adaptive FIR filter, `firCoeffs32`, may be saved to a data file by typing
SAVE <filename> <start address>, <end address>
in the _Command_ window of the _MDK-ARM debugger_ , where `start address` is the address of array `firCoeffs32` and `end address` is equal to `start address + 0x80`, and plotted using MATLAB function `stm32f4_logfft()`. This should reveal the time- and frequency-domain characteristics of the IIR filter implemented by the program, as identified by the adaptive filter and as shown in Figure 6.14.
**Figure 6.14** Impulse response and magnitude frequency response of IIR filter identified by the adaptive filter in program `tm4c123_noise_cancellation_intr.c` and plotted using MATLAB function `tm4c123_logfft()`.
* * *
# Example 6.4
**Adaptive FIR Filter for System Identification of a Fixed FIR Filter as the Unknown System`tm4c123_adaptIDFIR_CMSIS_intr.c`).**
* * *
Listing 6.9 shows program `tm4c123_adaptIDFIR_CMSIS_intr.c`, which uses an adaptive FIR filter to identify an unknown system. A block diagram of the system implemented in this example is shown in Figure 6.15. The unknown system to be identified is a 55-coefficient FIR band-pass filter centered at 2000 Hz. The coefficients of this fixed FIR filter are read from header file `bp55.h`, previously used in Example 3.23. A 60-coefficient adaptive FIR filter is used to identify the fixed (unknown) FIR band-pass filter.
**Figure 6.15** Block diagram representation of program `tm4c123_adaptIDFIR_CMSIS_intr.c`.
A pseudorandom binary noise sequence, generated within the program, is input to both the fixed (unknown) and the adaptive FIR filters and an error signal formed from their outputs. The adaptation process seeks to minimize the variance of that error signal. It is important to use wideband noise as an input signal in order to identify the characteristics of the unknown system over the entire frequency range from zero to half the sampling frequency.
* * *
# Listing 6.5 Program `tm4c123_adaptIDFIR_CMSIS_intr.c.`
_// tm4c123_adaptIDFIR_CMSIS_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "bp55.h"
**#define** BETA 5E-13 _// adaptive learning rate_
**#define** NUM_COEFFS 60
**#define** BLOCK_SIZE 1
float32_t firStateF32[BLOCK_SIZE + NUM_COEFFS -1];
float32_t firCoeffs32[NUM_COEFFS] = {0.0};
arm_lms_instance_f32 S_lms;
float32_t state[N];
arm_fir_instance_f32 S_fir;
**volatile** int16_t out_flag = 0; _// determines output_
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
float32_t x_fir, y_fir;
float32_t inputl, inputr;
float32_t x_lms, y_lms, error;
SSIDataGet(SSI0_BASE,&sample_data.bit32); _// input RIGHT_
inputl = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI1_BASE,&sample_data.bit32); _// input LEFT_
inputr = (float32_t)(sample_data.bit16[0]);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4); _// PE2 high_
x_fir = (float32_t)(prbs(8000));
x_lms = x_fir;
arm_fir_f32(&S_fir, &x_fir, &y_fir, 1);
arm_lms_f32(&S_lms, &x_lms, &y_fir, &y_lms, &error, 1);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0); _// PE2 low_
**if** (out_flag 0)
sample_data.bit32 = ((int16_t)(y_lms));
**else**
sample_data.bit32 = ((int16_t)(y_fir));
SSIDataPut(SSI0_BASE,sample_data.bit32); _// output RIGHT_
sample_data.bit32 = ((int16_t)(error));
SSIDataPut(SSI1_BASE,sample_data.bit32); _// output LEFT_
SSIIntClear(SSI0_BASE,SSI_RXFF); _// clear interrupt flag_
}
**int** main()
{
arm_fir_init_f32(&S_fir, N, h, state, 1);
arm_lms_init_f32(&S_lms, NUM_COEFFS, firCoeffs32, firStateF32,
BETA, 1);
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1)
{
ROM_SysCtlDelay(10000);
_// test SWI1 closed/pressed_
**if** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4))
{
ROM_SysCtlDelay(10000);
out_flag = (out_flag+1)%2; _// toggle out_flag_
_// wait until SWI not closed/pressed_
**while** (!GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4)){}
}
}
}
* * *
Build, load, and run the program. The blue user pushbutton on the Discovery may be used to toggle the output between `y_fir` (the output from the fixed (unknown) FIR filter) and `y_lms` (the output from the adaptive FIR filter) as the signal written to the right channel of LINE OUT on the audio card. `error` (the error signal) is always written to the left channel of LINE OUT. Verify that the output of the adaptive FIR filter (`y_lms`) converges to bandlimited noise similar in frequency content to the output of the fixed FIR filter (`y_fir`) and that the variance of the error signal (`error`) gradually diminishes as adaptation takes place.
Edit the program to include the coefficient file `bs55.h` (in place of `bp55.h`), which implements a 55-coefficient FIR band-stop filter centered at 2 kHz. Rebuild and run the program and verify that, after adaptation has taken place, the output of the adaptive FIR filter is almost identical to that of the FIR band-stop filter. Figure 6.16 shows the output of the program while adaptation is taking place. The upper time-domain trace shows the output of the adaptive FIR filter, the lower time-domain trace shows the error signal, and the magnitude of the FFT of the output of the adaptive FIR filter is shown below them. Increase (or decrease) the value of `beta` by a factor of 10 to observe a faster (or slower) rate of convergence. Change the number of weights (coefficients) from 60 to 40 and verify a slight degradation in the identification process. You can examine the adaptive filter coefficients stored in array `firCoeffs32` in this example by saving them to data file and using the MATLAB function `stm32f4_logfft()` to plot them in the time and frequency domains.
**Figure 6.16** Output from program `stm32f4_adaptIDFIR_CMSIS_intr.c` using coefficient header file `bs55.h` viewed using _Rigol DS1052E_ oscilloscope.
* * *
# Example 6.5
**Adaptive FIR Filter for System ID of a Fixed FIR as an Unknown System with Adaptive Filter Initialized as a Band-Pass Filter (`stm32f4_adaptIDFIR_CMSIS_init_intr.c`).**
* * *
In this example, program `stm32f4_adaptIDFIR_CMSIS_intr.c` has been modified slightly in order to create program `stm32f4_adaptIDFIR_init_intr.c`. This program initializes the weights, `firCoeffs32`, of the adaptive FIR filter using the coefficients of an FIR band-pass filter centered at 3 kHz, rather than initializing the weights to zero. Both sets of filter coefficients (adaptive and fixed) are read from file `adaptIDFIR_CMSIS_init_coeffs.h`. Build, load, and run the program. Initially, the frequency content of the output of the adaptive FIR filter is centered at 3 kHz. Then, gradually, as the adaptive filter identifies the fixed (unknown) FIR band-pass filter, its output changes to bandlimited noise centered on frequency 2 kHz. The adaptation process is illustrated in Figure 6.17, which shows the frequency content of the output of the adaptive filter at different stages in the adaptation process.
**Figure 6.17** Output from adaptive filter in program `tm4c123_adaptIDFIR_CMSIS_init_intr.c`.
As in most of the example programs in this chapter, the rate of adaptation has been set very low.
* * *
# Example 6.6
**Adaptive FIR for System ID of Fixed IIR as an Unknown System (`tm4c123_iirsosadapt_CMSIS_intr.c`).**
* * *
An adaptive FIR filter can be used to identify the characteristics not only of other FIR filters but also of IIR filters (provided that the substantial part of the IIR filter impulse response is shorter than that possible using the adaptive FIR filter). Program `tm4c123_iirsosadapt_CMSIS_intr.c`, shown in Listing 6.12 combines programs `tm4c123_iirsos_intr.c` (Example 4.2) and `tm4c123_adaptIDFIR_CMSIS_intr.c` in order to illustrate this (Figure 6.18). The IIR filter coefficients used are those of a fourth-order low-pass elliptic filter (see Example 4.9) and are read from file `elliptic.h`. Build and run the program and verify that the adaptive filter converges to a state in which the frequency content of its output matches that of the (unknown) IIR filter. Listening to the decaying error signal output on the left channel of LINE OUT on the audio booster pack gives an indication of the progress of the adaptation process. Figures 6.19 and 6.20 show the output of the adaptive filter (displayed using the FFT function of a _Rigol DS1052E_ oscilloscope) and the magnitude FFT of the coefficients (weights) of the adaptive FIR filter saved to a data file and displayed using MATLAB function `tm4c123_logfft()`. The result of the adaptive system identification procedure is similar in form to that obtained by recording the impulse response of an elliptic low-pass filter using program `tm4c123_iirsosdelta_intr.c` in Example 4.10.
**Figure 6.18** Block diagram representation of program `tm4c123_iirsosadapt_CMSIS_intr.c`.
**Figure 6.19** Output from adaptive filter in program `tm4c123_iirsosadapt_CMSIS_intr.c` viewed using a _Rigol DS1052E_ oscilloscope.
**Figure 6.20** Adaptive filter coefficients from program `tm4c123_iirsosadapt_CMSIS_intr.c` plotted using MATLAB function `tm4c123_logfft()`.
* * *
# Listing 6.6 Program `tm4c123_iirsosadapt_CMSIS_intr.c.`
_// tm4c123_iirsosadapt_CMSIS_intr.c_
**#include** "tm4c123_aic3104_init.h"
**#include** "elliptic.h"
**#define** BETA 1E-12
**#define** NUM_TAPS 128
**#define** BLOCK_SIZE 1
float32_t firStateF32[BLOCK_SIZE + NUM_TAPS -1];
float32_t firCoeffs32[NUM_TAPS] = {0.0};
arm_lms_instance_f32 S;
float32_t w[NUM_SECTIONS][2] = {0.0f, 0.0f};
**void** SSI_interrupt_routine( **void** )
{
AIC3104_data_type sample_data;
float32_t adapt_in, adapt_out, error;
float32_t iir_in, wn, iir_out, input;
int16_t section;
SSIDataGet(SSI0_BASE,&sample_data.bit32);
input = (float32_t)(sample_data.bit16[0]);
SSIDataGet(SSI1_BASE,&sample_data.bit32);
input = (float32_t)(sample_data.bit16[0]);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
iir_in = (float32_t)(prbs(8000));
adapt_in = iir_in;
**for** (section=0 ; section<NUM_SECTIONS ; section++)
{
wn = iir_in - a[section][1]*w[section][0]
- a[section][2]*w[section][1];
iir_out = b[section][0]*wn
+ b[section][1]*w[section][0]
+ b[section][2]*w[section][1];
w[section][1] = w[section][0];
w[section][0] = wn;
iir_in = iir_out;
}
arm_lms_f32(&S, &adapt_in, &iir_out, &adapt_out,
&error, 1);
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
sample_data.bit32 = ((int16_t)(adapt_out));
SSIDataPut(SSI0_BASE,sample_data.bit32);
sample_data.bit32 = ((int16_t)(error));
SSIDataPut(SSI1_BASE,sample_data.bit32);
SSIIntClear(SSI0_BASE,SSI_RXFF);
}
**int** main()
{
arm_lms_init_f32(&S, NUM_TAPS, firCoeffs32,
firStateF32, BETA, 1);
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_INTR,
PGA_GAIN_6_DB);
**while** (1);
}
* * *
* * *
# Example 6.7
**Adaptive FIR Filter for System Identification of an External System (`tm4c123_sysid_CMSIS_intr.c`).**
* * *
Program `tm4c123_sysid_CMSIS_intr.c`, introduced in Chapter 2, extends the previous examples to allow the identification of an external system, connected between the LINE OUT and LINE IN sockets of the audio booster pack. In Example 3.17, program `tm4c123_sysid_CMSIS_intr.c` was used to identify the characteristics of a moving average filter implemented using a second TM4C123 LaunchPad and audio booster pack. Alternatively, a purely analog system or a filter implemented using different DSP hardware can be connected between LINE OUT and LINE IN and its characteristics identified. Connect two systems as shown in Figure 6.21. Load and run `tm4c123_iirsos_intr.c`, including coefficient header file `elliptic.h` on the first. Run program `tm4c123_sysid_CMSIS_intr.c` on the second. Halt program `tm4c123_sysid_CMSIS_intr.c` after a few seconds and save the 256 adaptive filter coefficients `firCoeffs32` to a data file. You can plot the saved coefficients using MATLAB function `tm4c123_logfft()`. Figure 6.22 shows typical results.
**Figure 6.21** Connection diagram for program `tm4c123_sysid_CMSIS_intr.c` in Example 6.14.
**Figure 6.22** Adaptive filter coefficients from program `tm4c123_sysid_CMSIS_intr.c` plotted using MATLAB function `tm4c123_logfft()`
A number of features of the plots shown in Figure 6.22 are worthy of comment. Compare the magnitude frequency response in Figure 6.22(b) with that in Figure 6.20(b). The characteristics of the codec reconstruction and antialiasing filters and of the ac coupling between codecs and jack sockets on both boards are included in the signal path identified by program `tm4c123_sysid_CMSIS_intr.c` in this example and are apparent in the roll-off of the magnitude frequency response at frequencies above 3800 Hz and below 100 Hz. There is no roll-off in Figure 6.20(b). Compare the impulse response in Figure 6.22(b) with that in Figure 6.20(b). Apart from its slightly different form, corresponding to the roll-off in its magnitude frequency response, there is an additional delay of approximately 12 ms.
* * *
# Example 6.8
**Adaptive FIR Filter for System Identification of an External System Using DMA-Based I/O (`tm4c123_sysid_CMSIS_dma.c`).**
* * *
Functionally, program `tm4c123_sysid_CMSIS_dma.c` (Listing 6.15) is similar to program `tm4c123_sysid_CMSIS_intr.c`. Both programs use an adaptive FIR filter, implemented using CMSIS DSP library function `arm_lms_f32()`, to identify the impulse response of a system connected between LINE OUT and LINE IN connections to the audio booster pack. However, program `tm4c123_sysid_CMSIS_dma.c` is more computationally efficient and can run at higher sampling rates. Because function `arm_lms_f32()` is optimized to process blocks of input data rather than just one sample at a time, it is appropriate to use DMA-based rather than interrupt-based i/o in this example. However, DMA-based i/o introduces an extra delay into the signal path identified, and this is evident in the examples of successfully adapted weights shown in Figure 6.23. In each case, the adaptive filter used 256 weights. The program has been run successfully using up to 512 weights at a sampling rate of 8 kHz on the TM4C123 LaunchPad with a processor clock rate of 84 MHz.
**Figure 6.23** Adaptive filter coefficients from program `tm4c123_sysid_CMSIS_dma.c` plotted using MATLAB function `tm4c123_logfft()`. (a) `BUFSIZE` = 32 (b) `BUFSIZE` = 64.
* * *
# Listing 6.7 Program `tm4c123_sysid_CMSIS_dma.c.`
_// tm4c123_sysid_CMSIS_dma.c_
**#include** "tm4c123_aic3104_init.h"
**extern** int16_t LpingIN[BUFSIZE], LpingOUT[BUFSIZE];
**extern** int16_t LpongIN[BUFSIZE], LpongOUT[BUFSIZE];
**extern** int16_t RpingIN[BUFSIZE], RpingOUT[BUFSIZE];
**extern** int16_t RpongIN[BUFSIZE], RpongOUT[BUFSIZE];
**extern** int16_t Lprocbuffer, Rprocbuffer;
**extern volatile** int16_t Lbuffer_full, Rbuffer_full;
**extern volatile** int16_t LTxcomplete, LRxcomplete,
**extern volatile** int16_t RTxcomplete, RRxcomplete;
**#define** BETA 1E-12 _// adaptive learning rate_
**#define** NUM_TAPS 256
float32_t firStateF32[BUFSIZE + NUM_TAPS -1];
float32_t firCoeffs32[NUM_TAPS] = {0.0};
arm_lms_instance_f32 S;
**void** Lprocess_buffer( **void** )
{
float32_t adapt_in[BUFSIZE], adapt_out[BUFSIZE]
float32_t desired[BUFSIZE], error[BUFSIZE];
int16_t *inBuf, *outBuf; _// temp buffer pointers_
**int** i;
**if** (Lprocbuffer PING) _// use ping or pong buffers_
{ inBuf = LpingIN; outBuf = LpingOUT; }
**if** (Lprocbuffer PONG)
{ inBuf = LpongIN; outBuf = LpongOUT;}
**for** (i = 0; i < (BUFSIZE) ; i++)
{
adapt_in[i] = (float32_t)(prbs(8000));
desired[i] = (float32_t)(*inBuf++);
}
arm_lms_f32(&S, adapt_in, desired,
adapt_out, error, BUFSIZE);
**for** (i = 0; i < (BUFSIZE) ; i++)
{
*outBuf++ = (int16_t)(adapt_in[i]);
}
LTxcomplete = 0;
LRxcomplete = 0;
**return** ;
}
**void** Rprocess_buffer( **void** )
{
int16_t *inBuf, *outBuf; _// temp buffer pointers_
**int** i;
**if** (Rprocbuffer PING) _// use ping or pong buffers_
{ inBuf = RpingIN; outBuf = RpingOUT; }
**if** (Rprocbuffer PONG)
{ inBuf = RpongIN; outBuf = RpongOUT;}
**for** (i = 0; i < (BUFSIZE) ; i++) *outBuf++ = (int16_t)(0);
RTxcomplete = 0;
RRxcomplete = 0;
**return** ;
}
**void** SSI_interrupt_routine( **void** ){ **while** (1){}}
**int** main( **void** )
{
arm_lms_init_f32(&S, NUM_TAPS, firCoeffs32, firStateF32,
BETA, BUFSIZE);
tm4c123_aic3104_init(FS_8000_HZ,
AIC3104_LINE_IN,
IO_METHOD_DMA,
PGA_GAIN_6_DB);
**while** (1)
{
**while** ((!RTxcomplete)|(!RRxcomplete));
Rprocess_buffer();
while((!LTxcomplete)|(!LRxcomplete));
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 4);
Lprocess_buffer();
GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_2, 0);
}
}
* * *
# Index
1. Adaptive filters
1. for channel equalization
2. for noise cancellation
3. for prediction
4. for sinusoidal noise cancellation
5. for system ID of FIR filter
6. for system ID of IIR filter
7. for system ID of moving average filter
2. AIC3104 codec
1. ADC gain
2. de-emphasis
3. identification of bandwidth of
4. impulse response of
5. programmable digital effects filter
6. sampling frequency
3. Aliasing
1. in impulse invariance method
4. Amplitude modulation (AM)
5. Analog-to-digital converter (ADC)
6. Antialiasing filter
7. `arm_biquad_cascade_df1_f32()`
8. `arm_cfft_f32()`
9. `arm_fir_f32()`
10. `arm_lms_f32()`
11. Bilinear transformation (BLT)
1. design procedure using
2. frequency warping in
12. Bit reversed addressing
13. Blackman window function
14. Breakpoints
15. Butterfly structure
16. Cascade IIR filter structure
17. CMSIS DSP library
1. `arm_biquad_cascade_df1_f32()`
2. `arm_cfft_f32()`
3. `arm_fir_f32()`
4. `arm_lms_f32()`
18. Convolution
19. Decimation-in-frequency (DIF) algorithm
20. Decimation-in-time (DIT) algorithm
21. Difference equations
1. DTMF tone generation using
2. sine generation using
3. swept sinusoid generation using
22. Digital-to-analog converter (DAC)
1. 12-bit
23. Direct form I IIR filter structure
24. Direct form II IIR filter structure
25. Direct form II transpose IIR filter structure
26. Direct memory access (DMA)
1. delay introduced by
2. in STM32F407
3. in TM4C123
27. Discrete Fourier transform (DFT)
1. of complex-number sequence
2. of real-time signal
28. Discrete-time Fourier Transform (DTFT)
29. DTMF generation
1. using difference equations
2. using lookup tables
30. Fast convolution
31. Fast Fourier transform (FFT)
1. bit reversed addressing
2. butterfly structure
3. decimation-in-frequency algorithm for
4. decimation-in-time algorithm for
5. radix-2
6. radix-4
7. of real-time input
8. of a real-time input signal
9. of a sinusoidal signal
32. `fdatool` filter design and analysis tool
33. Finite impulse response (FIR) filters
1. window design method
34. Fourier series (FS)
35. Fourier transform (FT)
36. Frame-based processing
37. Frequency inversion, scrambling by
38. Frequency warping
39. _Goldwave_
40. Graphic equalizer
41. Hamming window function
42. Hanning window function
43. Impulse invariance method
44. Impulse response
1. of AIC3104 codec
2. of WM5102 codec
45. Infinite impulse response (IIR) filters
1. cascade IIR filter structure
2. direct form I IIR filter structure
3. direct form II IIR filter structure
4. direct form II transpose IIR filter structure
5. parallel IIR filter structure
6. second order sections
46. I/O
1. DMA-based
2. interrupt-based
3. polling-based
47. Inverse fast Fourier transform (IFFT)
48. Kaiser window function
49. Least mean squares (LMS) algorithm
1. sign-data algorithm
2. sign-error algorithm
3. sign-sign algorithm
50. Lookup table
1. DTMF generation with
2. impulse generation with
3. sine wave generation with
4. square-wave generation with
5. swept sine wave generation with
51. _MDK-ARM_
52. Memory data, viewing and saving
53. Moving average filter
54. Noise cancellation
55. Notch filters
1. FIR
2. IIR
56. Overlap-add
57. Parallel form IIR filter structure
58. Parks-Miller algorithm
59. Performance function
60. Ping-pong buffers
61. PRBS
62. Prediction
63. Pseudorandom noise
1. as input to FIR filter
2. as input to IIR filter
3. as input to moving average filter
64. Radix-2 decimation-in-frequency FFT algorithm
65. Radix-2 decimation-in-time FFT algorithm
66. Radix-4 decimation-in-frequency FFT algorithm
67. Reconstruction filter
68. Rectangular window function
69. Sine wave generation
1. using difference equation
2. using lookup table
3. using `sinf()` function call
70. Sinusoidal noise cancellation, adaptive filter for
71. Spectral leakage
72. Square wave generation
73. `SSI0IntHandler()`
74. Steepest descent algorithm
75. `stm32f4_adaptIDFIR_CMSIS_ init_intr.c`
76. `stm32f4_adaptive.c`
77. `stm32f4_average_intr.c`
78. `stm32f4_average_prbs_intr.c`
79. `stm32f4_dft.c`
80. `stm32f4_dftw.c`
81. `stm32f4_dimpulse_DAC12_intr.c`
82. `stm32f4_dimpulse_intr.c`
83. `stm32f4_fft.c`
84. `stm32f4_fft_CMSIS.c`
85. `stm32f4_fft128_dma.c`
86. `stm32f4_fir_coeffs.m`
87. `stm32f4_fir_dma.c`
88. `stm32f4_fir_intr.c`
89. `stm32f4_fir_prbs_buf_intr.c`
90. `stm32f4_fir_prbs_CMSIS_dma.c`
91. `stm32f4_iirsos_intr.c`
92. `stm32f4_iirsostr_intr.c`
93. `stm32f4_logfft.m`
94. `stm32f4_loop_buf_intr.c`
95. `stm32f4_loop_dma.c`
96. `stm32f4_loop_intr.c`
97. `stm32f4_loop_poll.c`
98. `stm32f4_noise_cancellation_ CMSIS_dma.c`
99. `stm32f4_plot_complex.m`
100. `stm32f4_plot_real.m`
101. `stm32f4_prbs_DAC12_intr.c`
102. `stm32f4_sine_intr.c`
103. `stm32f4_sine48_intr.c`
104. `stm32f4_sine8_intr.c`
105. `stm32f4_sine8_DAC12_intr.c`
106. `stm32f4_sinegenDE_intr.c`
107. `stm32f4_sinegenDTMF_intr.c`
108. `stm32f4_square_DAC12_intr.c`
109. `stm32f4_square_intr.c`
110. `stm32f4_sweep_intr.c`
111. `stm32f4_sweepDE_intr.c`
112. System identification
1. of codec antialiasing and reconstruction filters
2. of FIR filter
3. of IIR filter
4. of moving average filter
113. `tm4c123_adaptIDFIR_CMSIS_intr.c`
114. `tm4c123_adaptnoise_CMSIS_intr.c`
115. `tm4c123_adaptnoise_intr.c`
116. `tm4c123_aic3104_biquad.m`
117. `tm4c123_aliasing_intr.c`
118. `tm4c123_AM_poll.c,`
119. `tm4c123_delay_intr.c`
120. `tm4c123_dft128_dma.c`
121. `tm4c123_dimpulse_intr.c`
122. `tm4c123_echo_intr.c`
123. `tm4c123_fastconv_dma.c`
124. `tm4c123_fft128_CMSIS_dma.c`
125. `tm4c123_fft128_sinetable_dma.c`
126. `tm4c123_fir_dma.c`
127. `tm4c123_fir_intr.c`
128. `tm4c123_fir_prbs_CMSIS_dma.c`
129. `tm4c123_fir_prbs_intr.c`
130. `tm4c123_fir3lp_intr.c`
131. `tm4c123_fir3ways_intr.c`
132. `tm4c123_fir4types_intr.c`
133. `tm4c123_fir_coeffs.m`
134. `tm4c123_flanger_dimpulse_intr.c`
135. `tm4c123_flanger_intr.c`
136. `tm4c123_graphicEQ_dma.c`
137. `tm4c123_iirsos_CMSIS_intr.c`
138. `tm4c123_iirsos_coeffs.m`
139. `tm4c123_iirsos_delta_intr.c`
140. `tm4c123_iirsos_intr.c`
141. `tm4c123_iirsos_prbs_intr.c`
142. `tm4c123_iirsosadapt_CMSIS_intr.c`
143. `tm4c123_logfft.m`
144. `tm4c123_loop_buf_intr.c`
145. `tm4c123_loop_dma.c`
146. `tm4c123_loop_intr.c`
147. `tm4c123_loop_poll.c`
148. `tm4c123_notch2_intr.c`
149. `tm4c123_prandom_intr.c`
150. `tm4c123_prbs_biquad_intr.c`
151. `tm4c123_prbs_deemph_intr.c`
152. `tm4c123_prbs_prbs_intr.c`
153. `tm4c123_prbs_intr.c`
154. `tm4c123_ramp_intr.c`
155. `tm4c123_scrambler_intr.c`
156. `tm4c123_sine48_intr.c`
157. `tm4c123_sine48_loop_intr.c`
158. `tm4c123_sineDTMF_intr.c`
159. `tm4c123_square_1kHz_intr.c`
160. `tm4c123_square_intr.c`
161. `tm4c123_sysid_average_CMSIS_ intr.c`
162. `tm4c123_sysid_biquad_intr.c`
163. `tm4c123_sysid_CMSIS_dma.c`
164. `tm4c123_sysid_CMSIS_intr.c`
165. `tm4c123_sysid_deemph_CMSIS_intr.c`
166. `tm4c123_sysid_flange_intr.c`
167. Twiddle factors
168. Voice scrambling, using filtering and modulation
169. Window functions
1. Blackman
2. Hamming
3. Hanning
4. Kaiser
5. rectangular
170. WM5102 codec
1. impulse response of
171. Z-transform (ZT)
172. Zero padding
# WILEY END USER LICENSE AGREEMENT
Go to www.wiley.com/go/eula to access Wiley's ebook EULA.
|
/**
* EmailTemplate is an email template, though it could actually be used for anything,
* identified by a unique key and set to be locale specific if desired
*/
@Root
@Entity
@Table(name = "EMAIL_TEMPLATE_ITEM",
uniqueConstraints = {@UniqueConstraint(columnNames = {"TEMPLATE_KEY", "TEMPLATE_LOCALE"})},
indexes = {@Index(name = "email_templ_owner", columnList = "OWNER"),
@Index(name = "email_templ_key", columnList= "TEMPLATE_KEY")}
)
@Getter @Setter
public class EmailTemplate implements java.io.Serializable, PersistableEntity<Long> {
public static final String DEFAULT_LOCALE = "default";
private static final long serialVersionUID = -8697605573015358433L;
@Id
@GeneratedValue
@Column(name = "ID")
private Long id;
@Column(name = "LAST_MODIFIED", nullable = false)
private Date lastModified;
@Element
@Column(name = "TEMPLATE_KEY", nullable = false, length = 255)
private String key;
@Element(required = false)
@Column(name = "TEMPLATE_LOCALE", length = 255)
private String locale;
@Element
@Column(name = "OWNER", nullable = false, length = 255)
private String owner;
@Element
@Lob
@Column(name = "SUBJECT", nullable = false, length = 100000000)
private String subject;
@Element
@Lob
@Column(name = "MESSAGE", nullable = false, length = 100000000)
private String message;
@Element(required = false)
@Lob
@Column(name = "HTMLMESSAGE", length = 100000000)
private String htmlMessage;
@Element
@Column(name = "VERSION")
private Integer version;
@Column(name = "emailfrom", length = 255)
private String from;
@Column(length = 255, unique = false)
private String defaultType;
/** default constructor */
public EmailTemplate() {
}
public EmailTemplate(String key, String owner, String message) {
if (this.lastModified == null) {
this.lastModified = new Date();
}
this.owner = owner;
this.message = message;
}
/** full constructor */
public EmailTemplate(String key, String owner, String message, String defaultType, String locale) {
if (this.lastModified == null) {
this.lastModified = new Date();
}
this.key = key;
this.locale = locale;
this.owner = owner;
this.message = message;
this.defaultType = defaultType;
}
} |
/// Executes the `create2` operation for a given contract with the given value
/// and salt.
pub fn create2(
contract: &Contract,
value: yul::Expression,
salt: yul::Expression,
) -> yul::Expression {
let name = literal_expression! { (format!("\"{}\"", contract.name)) };
expression! {
contract_create2(
(dataoffset([name.clone()])),
(datasize([name])),
[value],
[salt]
)
}
} |
// After taking a lock on the table for the given bucket, this function will
// check the hashpower to make sure it is the same as what it was before the
// lock was taken. If it isn't unlock the bucket and throw a
// hashpower_changed exception.
inline void check_hashpower(const size_t hp, const size_t lock) const {
if (get_hashpower() != hp) {
locks_[lock].unlock();
LIBCUCKOO_DBG("%s", "hashpower changed\n");
throw hashpower_changed();
}
} |
import { Me } from '@codement/ui/lib/containers/Me.container';
import { Loader } from '@codement/ui';
import React from 'react';
import { useHistory } from 'react-router';
import styles from './Dashboard.module.css';
import { ModuleTree } from '../../components/ModuleTree/ModuleTree';
import { LeaderboardWidget } from '../../components/LeaderBoardWidget/LeaderBoardWidget';
import { Page } from '../../components/Page/Page';
import { ProgressWidget } from '../../components/ProgressWidget/ProgressWidget';
import { routes } from '../../router/routes';
import { Path } from '../../containers/Path.container';
export const DashboardPage = () => {
const history = useHistory();
const { me } = Me.useContainer();
const { loading } = Path.useContainer();
if (!me?.userPreferences) history.push(routes.onboardingWorkflow());
if (loading) return <Loader />;
return <Page title="Dashboard" type="dashboard" className="bg-white">
<div className={styles.dashboard}>
<ModuleTree />
<ProgressWidget className="w-64 my-6 bg-white" />
<LeaderboardWidget className="w-64" />
</div>
</Page>;
};
|
// GetDataChannelStats is a helper method to return the associated stats for a given DataChannel
func (r StatsReport) GetSCTPTransportStats(st *SCTPTransport) (SCTPTransportStats, bool) {
stats, ok := r["sctpTransport"]
if !ok {
return SCTPTransportStats{}, false
}
stStats, ok := stats.(SCTPTransportStats)
if !ok {
return SCTPTransportStats{}, false
}
return stStats, true
} |
Kentucky’s chapter of College Republicans have dug up one of the weakest “gotcha” moments in recent political memory.
The group posted cell phone video of Democratic Senate candidate Alison Lundergan Grimes being picked up by her husband at what appears to be Lexington’s Blue Grass Airport.
The video shows Grimes, who’s serving her first term as Kentucky’s secretary of state, climb into the back seat of the couple’s black Chevy Suburban while her husband wheels around her suitcase and places it into the cargo area.
Grimes then immediately pulls out her phone as her husband drives away, with no other passengers in the SUV.
“We think you’ll agree – this. is. weird,” the College Republicans said in a press release.
While it’s possible that a state official who’s running for national elected office might have some business to catch up on after a flight, the College Republicans think it reveals something more essential about Grimes’ character.
“(Grimes) thinks she’s so important that she needs to ride around town in the back seat of a black suburban … driven by personal chauffeur, her husband,” the group said.
The College Republicans said “popular belief” held that Hollywood had left the state when actress Ashley Judd declined to run against Republican Sen. Mitch McConnell, who’s also being challenged in a primary by Louisville businessman Matt Bevin.
“Perhaps after rubbing elbows with Harry Reid and Hollywood liberals Alison Lundergan Grimes has returned to KY thinking she’s the new star in town,” the group said.
Watch the cell phone video posted Wednesday:
[Image via YouTube] |
/**
* Provided schedule is started.
*
* @param schedule
* the schedule to start
* @return returns true if schedule was started
*/
public boolean start(Schedule schedule) {
boolean ret = false;
if (schedule != null) {
if (!isScheduleActive(schedule.getName())) {
if (schedule instanceof MaintenanceSchedule) {
resetMaintenanceStatus((MaintenanceSchedule) schedule);
}
ret = addTimer(schedule.getTimerSchedule(), schedule.getName());
if (ret) {
log.debug("Started schedule :: " + schedule.getName());
} else {
log.error("Failed to start schedule :: " + schedule.getName());
}
}
}
return ret;
} |
<reponame>mahdiyarsoft/TIc-Tac-Toe
(() => {
const pos: NodeListOf<Element> = document.querySelectorAll('.row');
let option: string = "O";
pos.forEach(pos => pos.addEventListener("click", () => {
CHECKoption();
if (pos.innerHTML == "") {
const x = document.createElement("h1");
pos.appendChild(x); x.classList.add(`${option}-item`); x.innerHTML = option;
};
function CHECKoption() {
if (option == "X") {
option = "O";
} else {
option = "X";
};
};
CHECKwin();
}));
function CHECKwin() {
if (pos[0].innerHTML == pos[1].innerHTML && pos[2].innerHTML == pos[1].innerHTML && pos[0].innerHTML !== "" && pos[1].innerHTML !== "" && pos[2].innerHTML !== "") {
win(0, 1, 2);
}
if (pos[3].innerHTML == pos[4].innerHTML && pos[5].innerHTML == pos[4].innerHTML && pos[3].innerHTML !== "" && pos[4].innerHTML !== "" && pos[5].innerHTML !== "") {
win(3, 4, 5);
}
if (pos[6].innerHTML == pos[7].innerHTML && pos[8].innerHTML == pos[7].innerHTML && pos[6].innerHTML !== "" && pos[7].innerHTML !== "" && pos[8].innerHTML !== "") {
win(6, 7, 8)
}
if (pos[0].innerHTML == pos[3].innerHTML && pos[6].innerHTML == pos[3].innerHTML && pos[0].innerHTML !== "" && pos[3].innerHTML !== "" && pos[6].innerHTML !== "") {
win(0, 3, 6)
}
// ////
if (pos[1].innerHTML == pos[4].innerHTML && pos[7].innerHTML == pos[4].innerHTML && pos[1].innerHTML !== "" && pos[4].innerHTML !== "" && pos[7].innerHTML !== "") {
win(1, 4, 7)
}
if (pos[2].innerHTML == pos[5].innerHTML && pos[8].innerHTML == pos[5].innerHTML && pos[2].innerHTML !== "" && pos[5].innerHTML !== "" && pos[8].innerHTML !== "") {
win(2, 5, 8)
}
if (pos[0].innerHTML == pos[4].innerHTML && pos[8].innerHTML == pos[4].innerHTML && pos[0].innerHTML !== "" && pos[4].innerHTML !== "" && pos[8].innerHTML !== "") {
win(0, 4, 8)
}
if (pos[2].innerHTML == pos[4].innerHTML && pos[6].innerHTML == pos[4].innerHTML && pos[2].innerHTML !== "" && pos[4].innerHTML !== "" && pos[6].innerHTML !== "") {
win(2, 4, 6)
}
if (pos[0].innerHTML!==""&&pos[1].innerHTML!==""&&pos[2].innerHTML!==""&&pos[3].innerHTML!==""&&pos[4].innerHTML!==""&&pos[5].innerHTML!==""&&pos[6].innerHTML!==""&&pos[7].innerHTML!==""&&pos[8].innerHTML!=="") {
alert("The end")
}
}
function win(x1: number, x2: number, x3: number) {
pos[x1].classList.add("win");
pos[x2].classList.add("win");
pos[x3].classList.add("win");
var winnerOption = pos[x3].childNodes[0].innerHTML;
console.log(winnerOption);
let x = document.createElement("div");
let y = document.createElement("h1");
let t = document.createElement("button");
document.body.appendChild(x);
x.classList.add("end");
function whoWin(winnerOption: any) {
y.innerHTML = `${winnerOption} Win :)`;
}
whoWin(winnerOption);
t.addEventListener("click", reset);
const end = <HTMLDivElement>document.querySelector('.end');
end.appendChild(y);
end.appendChild(t);
function reset() {
window.location.reload();
}
}
})(); |
Down syndrome and breastfeeding: A systematic review
Several conditions related to serious difficulty in initiating and maintaining breastfeeding in neonates with Down syndrome are described in the literature. This study aimed to investigate the frequency of breastfeeding in neonates with Down syndrome, as well as the reasons for not breastfeeding, through a systematic literature review by searching MEDLINE via PubMed, Cochrane Library, Scopus, Embase via Elsevier, and Cumulative Index to Nursing and Allied Health Literature (CINAHL) databases. Sixteen studies were included with a total sample size of 2022 children with Down syndrome. The frequency of exclusive breastfeeding was 31.6–55.4%, with five studies reporting breastfeeding for longer than 6 months. Breastfeeding from birth was present for 48–92.5% of the children with Down syndrome in six studies. Two studies reported that around 50% and 23.3% of the children with Down syndrome were never breastfed, and rates of breastfeeding in infants with Down syndrome were lower than those in controls in three studies. The reasons for not breastfeeding or cessation of breastfeeding were associated with Down syndrome-specific challenges, maternal reasons, and healthcare aspects. |
/**
* A generic RecyclerView adapter that uses Data Binding
* @author lipeiyong
*/
public abstract class BaseDataBoundAdapter<DataType, V extends ViewDataBinding> extends RecyclerView.Adapter<DataBoundViewHolder<V>> implements DataBoundAble<DataType> {
public BaseDataBoundAdapter() {
}
public BaseDataBoundAdapter(List<DataType> items) {
this.items = items;
}
public List<DataType> items;
@Override
public final DataBoundViewHolder<V> onCreateViewHolder(ViewGroup parent, int viewType) {
return new DataBoundViewHolder<>(createBinding(parent, viewType));
}
@Override
public final void onBindViewHolder(@NonNull DataBoundViewHolder<V> holder, int position) {
bind(holder.binding, position);
holder.binding.executePendingBindings();
}
@Override
public int getItemCount() {
return items == null ? 0 : items.size();
}
@Override
public void submitList(List<DataType> update) {
items = update;
notifyDataSetChanged();
}
/**
* 创建一个 V
*
* @param parent The ViewGroup into which the new View will be added after it is bound to an adapter position.
* @param viewType The view type of the new View.
* @return A new DataBoundViewHolder<> that holds a View of the given view type.
*/
protected abstract V createBinding(ViewGroup parent, int viewType);
/**
* 数据绑定
*
* @param binding 视图
* @param position 数据下标
*/
protected abstract void bind(V binding, int position);
} |
<reponame>AriaMinaei/leva
import { useRef } from 'react'
import create from 'zustand'
import shallow from 'zustand/shallow'
import { normalizeInput, pick, getKeyPath, join } from './utils'
import { warn, LevaErrors } from './utils/log'
import { Data, FolderSettings, Folders, SpecialInputTypes } from './types'
type State = { data: Data }
// zustand store
const _store = create<State>(() => ({ data: {} }))
// possibly make this reactive
const FOLDERS: Folders = {}
const PATHS = new Set<string>()
const useStore = _store
// shorthand to get zustand store data
const getData = () => _store.getState().data
function setPaths(newPaths: string[]) {
newPaths.forEach(p => PATHS.add(p))
}
/**
* Merges the data passed as an argument with the store data.
* If an input path from the data already exists in the store,
* the function doesn't update the data but increments count
* to keep track of how many components use that input key.
* @param newData the data to update
*/
function setData(newData: Data) {
_store.setState(s => {
const data = s.data
Object.entries(newData).forEach(([path, value]) => {
const input = data[path]
// if an input already exists at the path, increment
// the reference count.
if (!!input) input.count++
// if not, create a path for the input.
else data[path] = { ...value, count: 1 }
})
// TODO not sure about direct mutation but since this
// returns a new object that should work and trigger
// a re-render.
return { data }
})
}
/**
* Shorthand function to set the value of an input at a given path.
* @param path path of the input
* @param value new value of the input
*/
function setValueAtPath(path: string, value: any) {
_store.setState(s => {
const data = s.data
//@ts-expect-error (we always update inputs with a value)
data[path].value = value
return { data }
})
}
/**
* For a given data structure, gets all paths for which inputs have
* a reference count superior to zero. This function is used by the
* root pane to only display the inputs that are consumed by mounted
* components.
* @param data
*/
function getVisiblePaths(data: Data) {
const visiblePaths: string[] = []
PATHS.forEach(path => {
if (data[path]?.count > 0) visiblePaths.push(path)
})
return visiblePaths
}
/**
* Hook used by the root component to get all visible inputs.
*/
export const useVisiblePaths = () => useStore(s => getVisiblePaths(s.data), shallow)
function getValuesForPaths(data: Data, paths: string[], shouldWarn: boolean) {
return Object.entries(pick(data, paths) as Data).reduce(
// Typescript complaints that SpecialInput type doesn't have a value key.
// But getValuesForPath is only called from paths that are inputs,
// so they always have a value key.
// @ts-expect-error
(acc, [path, { value }]) => {
const [key] = getKeyPath(path)
// if a key already exists in the accumulator, prompt an error.
if (acc[key] !== undefined) {
if (shouldWarn) warn(LevaErrors.DUPLICATE_KEYS, key, path)
return acc
}
return { ...acc, [key]: value }
},
{} as { [path: string]: any }
)
}
/**
* Hook that returns the values from the zustand store for the given paths.
* @param paths paths for which to return values
* @param initialData
*/
export function useValuesForPath(paths: string[], initialData: Data) {
// init is used to know when to prompt duplicate key errors to the user.
// We don't want to show the errors on every render, only when the hook
// is first used!
const init = useRef(true)
const valuesForPath = useStore(s => {
const data = init.current ? initialData : s.data
return getValuesForPaths(data, paths, init.current)
}, shallow)
init.current = false
return valuesForPath
}
/**
* Return all input (value and settings) properties at a given path.
* @param path
*/
export function useInput(path: string) {
return useStore(s => {
const { count, ...input } = s.data[path]
return input
}, shallow)
}
export const getFolderSettings = (path: string) => FOLDERS[path]
/**
* Extract the data from the schema and sets folder initial preferences.
* @param schema
*/
export function getDataFromSchema(schema: any, rootPath = '') {
const data: any = {}
const paths: string[] = []
Object.entries(schema).forEach(([path, value]: [string, any]) => {
const newPath = join(rootPath, path)
if (value.type === SpecialInputTypes.FOLDER) {
Object.assign(data, getDataFromSchema(value.schema, newPath))
FOLDERS[newPath] = value.settings as FolderSettings
} else {
const input = normalizeInput(value, newPath)
if (input) {
data[newPath] = input
paths.push(newPath)
}
}
})
return data as Data
}
export function getPaths(initialData: Data) {
const paths = Object.keys(initialData)
setPaths(paths)
return paths
}
function disposePaths(paths: string[]) {
_store.setState(s => {
const data = s.data
paths.forEach(path => data[path].count--)
return { data }
})
}
export const store = {
getData,
setData,
setValueAtPath,
disposePaths,
}
if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
// TODO remove store from window
// @ts-expect-error
window.__LEVA__STORE = _store
}
|
// formatSetValuesAsArgs formats the given values as command line args for helm using the given flag (e.g flags of
// the format "--set"/"--set-string" resulting in args like --set/set-string key=value...)
func formatSetValuesAsArgs(setValues map[string]string, flag string) []string {
args := []string{}
keys := collections.Keys(setValues)
for _, key := range keys {
value := setValues[key]
argValue := fmt.Sprintf("%s=%s", key, value)
args = append(args, flag, argValue)
}
return args
} |
/**
* Implementation of the PageMessage Interface.
*
* @version JSR281-PUBLIC-REVIEW (subject to change).
*
* @author Cheambe Alice <[email protected]>
* @author Andreas Bachmann <[email protected]>
*
*/
public class PageMessageImpl extends ServiceMethodImpl implements PageMessage
{
private static Logger LOGGER = LoggerFactory.getLogger(PageMessageImpl.class);
private PageMessageListener listener;
private byte[] content;
private String contentType;
private int state;
private MessageImpl responseMessage;
public PageMessageImpl(CoreServiceImpl coreService, PageMessageContainer container, String remoteUri, String localUri) throws ImsException
{
super(coreService, container, remoteUri, localUri);
listener = null;
state = PageMessage.STATE_UNSENT;
setNextRequest(new MessageImpl(Message.PAGEMESSAGE_SEND, "MESSAGE"));
container.put(this);
}
public PageMessageImpl(CoreServiceImpl coreService, PageMessageContainer container, Request request, String localUri) throws ImsException
{
super(coreService, container, request, localUri);
state = PageMessage.STATE_RECEIVED;
listener = null;
ContentTypeHeader cType = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME);
if (cType != null)
contentType = cType.getContentType() + "/" + cType.getContentSubType();
content = request.getRawContent();
}
public byte[] getContent()
{
return content;
}
public String getContentType()
{
return contentType;
}
public int getState()
{
return state;
}
public MessageImpl getResponseMessage() {
return responseMessage;
}
public void send(byte[] content, String contentType) throws ServiceClosedException, IllegalStateException, IllegalArgumentException
{
if (state != PageMessage.STATE_UNSENT)
throw new IllegalStateException("Method send() cannot be called. Current state (" + state + ") is not UNSENT!");
if (content != null)
this.content = content;
if (contentType != null)
this.contentType = contentType;
Message message = getNextRequest();
try
{
MessageBodyPart part = message.createBodyPart();
part.setHeader("Content-Type", contentType);
part.openContentOutputStream().write(content);
} catch (Exception e)
{
LOGGER.error(e.getMessage());
return;
}
if (sendNextRequest())
{
state = PageMessage.STATE_SENT;
getContainer().put(this);
}
}
public void setListener(PageMessageListener pagemessagelistener)
{
if (pagemessagelistener == null)
this.listener = null;
else
this.listener = pagemessagelistener;
}
protected MessageImpl createRequestMessage(Request request)
{
return new MessageImpl(Message.PAGEMESSAGE_SEND, request);
}
protected MessageImpl createResponseMessage(Response response)
{
return new MessageImpl(Message.PAGEMESSAGE_SEND, response);
}
// ------ Helper Methods ------ //
public void methodDelivered(MessageImpl responseMessage)
{
LOGGER.info("PageMessageImpl: method delivered with {"+new Integer(responseMessage.getStatusCode())+"} {"+responseMessage.getMethod()+"}");
this.responseMessage = responseMessage;
// inform a waiting reference about responses
try
{
referenceNotify(ReferenceInformationListener.STATE_REFERENCE_TERMINATED, 0, responseMessage.getStatusCode() + " "
+ responseMessage.getReasonPhrase());
} catch (Exception e)
{
LOGGER.error(e.getMessage(), e);
}
if (listener != null)
listener.pageMessageDelivered(this);
}
public void methodDeliveryFailed(MessageImpl responseMessage)
{
LOGGER.error("PageMessageImpl: method failed " + responseMessage.getMethod() + " - statuscode " + responseMessage.getStatusCode());
// inform a waiting reference about responses
try
{
referenceNotify(ReferenceInformationListener.STATE_REFERENCE_TERMINATED, 0, responseMessage.getStatusCode() + " "
+ responseMessage.getReasonPhrase());
} catch (Exception e)
{
LOGGER.error(e.getMessage(), e);
}
if (listener != null)
listener.pageMessageDeliveredFailed(this);
}
} |
Between Isolation and Integration: Religion, Politics, and the Catholic Irish in Preston, C.1829-1868
ABSTRACT Since the 1970s, case-studies have highlighted specific local contexts which informed variegated Irish migrant experience across nineteenth-century Britain. This article scrutinises how the Catholic Irish in Preston navigated their host society. Especially in public and organisational expressions of religion and politics, the Preston Irish were unusually closely connected to their host community. Preston’s unusual confessional demographics and multifaceted political contestation offered the Catholic Irish opportunities for meaningful interventions in local society. Situating this case-study comparatively, this article posits four key interlinking factors shaping migrants’ experiences of a nineteenth-century town: its size, broader immigration patterns, confessional composition, and labour politics. |
DRD Tactical’s new Paratus is a semi-automatic take-down .308 Win. rifle designed to meet the military’s Clandestine Break-Down Semi-Automatic Rifle (CSR) proposal specifications. When broken down it fits inside an attaché case and can be assembled and ready to fire in under 60 seconds as demonstrated in the video below.
DRD Tactical Paratus-SBR-12 (12″ short barrled model)
The rifle appears to be based on the AR-10 design with a return spring integrated into the upper receiver and a charging handle on the left side. Other than the charging handle, the controls are the same as an AR-10/AR-15.
With a price starting at $5615, this rifle is not designed for the casual shooters.
Specifications Caliber .308 Win / 7.62x51mm NATO Capacity 20 Rounds Finish Nickel Boron Grip Magpul Barrel Lothar-Walther 16” with 1 in 10 twist Stock Magpul Folding Trigger Geissele 2-Stage Weight 9.2 lbs Sights Magpul MBUS Availability Now
The price for the Paratus-16 (16″ model) is $5,615 and Paratus-SBR-12 (12″ model with AAC muzzle brake) is $5,999. The company plans to offer additional calibers in the future. |
/**
* Contains information about a datapoint on an ROC curve
*/
public static class DataPoint
extends AbstractCloneableSerializable
{
/**
* Binary classifier used to create the corresponding ConfusionMatrix,
* which is really a wrapper for the threshold
*/
private ScalarThresholdBinaryCategorizer classifier;
/**
* Corresponding ConfusionMatrix with this datapoint
*/
private DefaultBinaryConfusionMatrix confusionMatrix;
/**
* Creates a new instance of DataPoint
*
* @param classifier
* Binary classifier used to create the corresponding ConfusionMatrix,
* which is really a wrapper for the threshold
* @param confusionMatrix
* Corresponding ConfusionMatrix with this datapoint
*/
public DataPoint(
ScalarThresholdBinaryCategorizer classifier,
DefaultBinaryConfusionMatrix confusionMatrix )
{
this.setClassifier( classifier );
this.setConfusionMatrix( confusionMatrix );
}
/**
* Getter for classifier
* @return
* Binary classifier used to create the corresponding ConfusionMatrix,
* which is really a wrapper for the threshold
*/
public ScalarThresholdBinaryCategorizer getClassifier()
{
return this.classifier;
}
/**
* Setter for classifier
* @param classifier
* Binary classifier used to create the corresponding ConfusionMatrix,
* which is really a wrapper for the threshold
*/
public void setClassifier(
ScalarThresholdBinaryCategorizer classifier)
{
this.classifier = classifier;
}
/**
* Getter for confusionMatrix
* @return
* Corresponding ConfusionMatrix with this datapoint
*/
public DefaultBinaryConfusionMatrix getConfusionMatrix()
{
return this.confusionMatrix;
}
/**
* Setter for confusionMatrix
* @param confusionMatrix
* Corresponding ConfusionMatrix with this datapoint
*/
protected void setConfusionMatrix(
DefaultBinaryConfusionMatrix confusionMatrix)
{
this.confusionMatrix = confusionMatrix;
}
/**
* Gets the falsePositiveRate associated with this datapoint
* @return
* falsePositiveRate associated with this datapoint
*/
public double getFalsePositiveRate()
{
return this.getConfusionMatrix().getFalsePositivesRate();
}
/**
* Gets the truePositiveRate associated with this datapoint
* @return
* truePositiveRate associated with this datapoint
*/
public double getTruePositiveRate()
{
return this.getConfusionMatrix().getTruePositivesRate();
}
/**
* Sorts DataPoints in ascending order according to their
* falsePositiveRate (x-axis)
*/
public static class Sorter
extends AbstractCloneableSerializable
implements Comparator<DataPoint>
{
/**
* Sorts ROCDataPoints in ascending order according to their
* falsePositiveRate (x-axis), used in Arrays.sort() method
*
* @param o1 First datapoint
* @param o2 Second datapoint
* @return
* -1 if o1<o2, +1 if o1>o2, 0 if o1=o2
*/
@Override
public int compare(
ReceiverOperatingCharacteristic.DataPoint o1,
ReceiverOperatingCharacteristic.DataPoint o2)
{
double x1 = o1.getFalsePositiveRate();
double x2 = o2.getFalsePositiveRate();
if( x1 < x2 )
{
return -1;
}
else if( x1 > x2 )
{
return +1;
}
else
{
double y1 = o1.getTruePositiveRate();
double y2 = o2.getTruePositiveRate();
if( y1 < y2 )
{
return -1;
}
else if( y1 > y2 )
{
return +1;
}
else
{
return 0;
}
}
}
}
} |
/**
* Test of getTargetNamespace method, of class XMLUtil.
*/
@Test
public void testGetTargetNamespace() throws Exception {
System.out.println("getTargetNamespace");
File xsdFile = new File("src/test/resources/xsd/mets.xsd");
Document document = JaxenUtil.getDocument(xsdFile);
String expResult = "http://www.loc.gov/METS/";
String result = XmlUtil.getTargetNamespace(document);
assertEquals(expResult, result);
} |
#include "pigeon.h"
#include "utils.h"
#include "client.h"
int NewSocket() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, NULL, sizeof(int));
if (sockfd <= 0) {
err_quit("NewSocket failed!");
}
return sockfd;
}
struct sockaddr_in *NewServerAddr(int sockfd, const char *ip) {
struct sockaddr_in *servaddr = NULL;
servaddr = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in));
if (servaddr == NULL) {
err_quit("%s: new server addr failed", __FUNCTION__);
}
memset(servaddr, 0, sizeof(struct sockaddr_in));
servaddr->sin_family = AF_INET;
servaddr->sin_port = htons(SERV_PORT);
inet_pton(AF_INET, ip, &servaddr->sin_addr);
return servaddr;
}
int BuildConnection(const char *ip, int *fdArray, int len) {
for (int i = 0; i < len; ++i) {
int sockfd = NewSocket();
struct sockaddr_in *servaddr = NewServerAddr(sockfd, ip);
if (connect(sockfd, (struct sockaddr *)servaddr,
sizeof(*servaddr)) != 0) {
err_quit("connect failed");
}
fdArray[i] = sockfd;
}
return 0;
}
int FdsetInit(fdset_t *fdSet) {
if (fdSet == NULL) {
return -1;
}
for (int i = 0; i < THREADNUM; ++i) {
sem_init(&fdSet->isFree[i], 0, 1);
}
return 0;
}
int FdsetDestroy(fdset_t *fdSet) {
if (fdSet == NULL) {
return -1;
}
for (int i = 0; i < THREADNUM; ++i) {
close(fdSet->sockfdArray[i]);
close(fdSet->filefdArray[i]);
sem_destroy(&fdSet->isFree[i]);
}
return 0;
} |
<filename>src/app/utilities/mockdata.ts
import { Participants } from '../interfaces/participants';
import { Tournament } from '../interfaces/tournament';
export class MockData {
public static getTournaments(): Tournament[] {
return [
{
id: '378426939508809728',
discipline: 'my_discipline',
name: 'My Weekly Tournament',
full_name: 'My Weekly Tournament - Long title',
status: 'running',
scheduled_date_start: '2015-09-06',
scheduled_date_end: '2015-09-07',
timezone: 'America/Sao_Paulo',
public: true,
size: 16,
online: true,
location: 'London',
country: 'GB',
platforms: ['pc', 'playstation4'],
logo: {
logo_small: 'https://www.toornament.com/media/file/123456/logo_small',
logo_medium:
'https://www.toornament.com/media/file/123456/logo_medium',
logo_large: 'https://www.toornament.com/media/file/123456/logo_large',
original: 'https://www.toornament.com/media/file/123456/original',
},
registration_enabled: true,
registration_opening_datetime: '1999-01-01T00:00:00+00:00',
registration_closing_datetime: '1999-01-01T00:00:00+00:00',
},
{
id: '378426939508809728',
discipline: 'my_discipline',
name: 'Kanaliiga V2 Tournament',
full_name: 'My Weekly Tournament - Long title',
status: 'running',
scheduled_date_start: '2015-09-06',
scheduled_date_end: '2015-09-07',
timezone: 'America/Sao_Paulo',
public: true,
size: 16,
online: true,
location: 'London',
country: 'GB',
platforms: ['pc', 'playstation4'],
logo: {
logo_small: 'https://www.toornament.com/media/file/123456/logo_small',
logo_medium:
'https://www.toornament.com/media/file/123456/logo_medium',
logo_large: 'https://www.toornament.com/media/file/123456/logo_large',
original: 'https://www.toornament.com/media/file/123456/original',
},
registration_enabled: true,
registration_opening_datetime: '1999-01-01T00:00:00+00:00',
registration_closing_datetime: '1999-01-01T00:00:00+00:00',
},
{
id: '378426939508809728',
discipline: 'my_discipline',
name: 'My Weekly Tournament',
full_name: 'My Weekly Tournament - Long title',
status: 'running',
scheduled_date_start: '2015-09-06',
scheduled_date_end: '2015-09-07',
timezone: 'America/Sao_Paulo',
public: true,
size: 16,
online: true,
location: 'London',
country: 'GB',
platforms: ['pc', 'playstation4'],
logo: {
logo_small: 'https://www.toornament.com/media/file/123456/logo_small',
logo_medium:
'https://www.toornament.com/media/file/123456/logo_medium',
logo_large: 'https://www.toornament.com/media/file/123456/logo_large',
original: 'https://www.toornament.com/media/file/123456/original',
},
registration_enabled: true,
registration_opening_datetime: '1999-01-01T00:00:00+00:00',
registration_closing_datetime: '1999-01-01T00:00:00+00:00',
},
{
id: '378426939508809728',
discipline: 'my_discipline',
name: 'Kanaliiga V2 Tournament',
full_name: 'My Weekly Tournament - Long title',
status: 'running',
scheduled_date_start: '2015-09-06',
scheduled_date_end: '2015-09-07',
timezone: 'America/Sao_Paulo',
public: true,
size: 16,
online: true,
location: 'London',
country: 'GB',
platforms: ['pc', 'playstation4'],
logo: {
logo_small: 'https://www.toornament.com/media/file/123456/logo_small',
logo_medium:
'https://www.toornament.com/media/file/123456/logo_medium',
logo_large: 'https://www.toornament.com/media/file/123456/logo_large',
original: 'https://www.toornament.com/media/file/123456/original',
},
registration_enabled: true,
registration_opening_datetime: '1999-01-01T00:00:00+00:00',
registration_closing_datetime: '1999-01-01T00:00:00+00:00',
},
];
}
public static getMatchData(): any {
return [
{
id: '618954615761465416',
number: 1,
type: 'duel',
status: 'pending',
scheduled_datetime: '2015-12-31T00:00:00+00:00',
played_at: '2015-12-31T00:00:00+00:00',
opponents: [
{
name: 'Valtori',
result: 'lose',
forfeit: false,
score: 4,
scoreOpponent: '',
participants: [
{
id: '375143143408309123',
name: 'Tupravaara',
},
{
id: '3715252525435436666',
name: 'Rento',
},
{
name: '<NAME>',
},
],
},
{
name: '<NAME>',
number: 1,
position: 1,
result: 'win',
forfeit: false,
score: 15,
scoreOpponent: '',
participants: [
{
id: '375143143408309123',
name: 'TECHNODICTATOR',
},
{
id: '3715252525435436666',
name: 'Wacky',
},
{
name: 'deepfake22',
},
],
},
],
},
{
id: '618954615761465416',
number: 2,
type: 'duel',
status: 'pending',
scheduled_datetime: '2015-12-31T00:00:00+00:00',
played_at: '2015-12-31T00:00:00+00:00',
opponents: [
{
name: 'Valtori',
result: 'lose',
forfeit: false,
score: 4,
scoreOpponent: '',
participants: [
{
id: '375143143408309123',
name: '<NAME>',
},
{
id: '3715252525435436666',
name: '<NAME>',
},
{
name: '<NAME>',
},
],
},
{
name: '<NAME>',
number: 1,
position: 1,
result: 'win',
forfeit: false,
score: 15,
scoreOpponent: '',
participants: [
{
id: '375143143408309123',
name: 'TECHNODICTATOR',
},
{
id: '3715252525435436666',
name: 'Wacky',
},
{
name: 'deepfake22',
},
],
},
],
},
];
}
public static getParticipants(): any[] {
return [
{
id: '375143143408309123',
name: 'Highlanders',
lineUp: [
{ name: 'Rentovaara' },
{ name: 'Tupra' },
{ name: 'Kalukassi' },
],
},
{
id: '5353535211214389',
name: '<NAME>',
lineUp: [
{ name: 'TECHNODICTATOR' },
{ name: 'Wacky' },
{ name: 'deepfake22' },
],
},
];
}
}
|
<gh_stars>1-10
package org.mark.mobile.ctrl;
/**
* Created by mark on 2019/8/5
*/
public class KeyIndex {
public static final String SPEED = "config_speed";
}
|
/**
* @param item desired element for searching.
* @return reference of node of item if item is present in the tree.
*/
public Node<E> postOrderSearch(E item,int option) {
if(root == null) return null;
Stack<Node<E>> tree = new Stack<>();
Node<E> temp = root;
while(!tree.empty() || temp!=null){
if(temp!=null)
{
tree.push(temp);
temp=temp.left;
}
else
{
Node<E> node = tree.pop();
if (option == 1) System.out.printf(" %s ",node.toString());
if (node.data.equals(item)) return node;
temp = node.right;
}
}
if (option == 1)System.out.println();
return null;
} |
Blue noise digital color halftoning with multiscale error diffusion
Abstract. A recent trend in color halftoning is to explicitly control color overlapping, dot positioning, and dot coloring in different stages of the halftoning process. As feature-preserving multiscale error diffusion (FMED) shows its capability and flexibility in dot positioning in both binary and multilevel halftoning applications, it naturally becomes a potential candidate in the development of new color halftoning algorithms. This paper presents an FMED-based color halftoning algorithm developed based on the aforementioned strategy. In contrast to the algorithms that adopt the same strategy, the proposed algorithm has no bias for specific Neugebauer primaries in dot coloring and has no fixed scanning path to place dots in dot positioning. These features allow the algorithm to place dots of the correct colors on the right positions with less constraint. Hence, the algorithm is better able to preserve image features. |
<reponame>parduino/MDOF<filename>Model.cpp
#include "Model.h"
#include <QDebug>
Model::Model(QObject *parent) :
QObject(parent)
{
}
void
Model::setNumFloors(int num){
numFloors = num;
if (mass != 0 || numFloors != num) {
delete [] mass;
}
mass = new double[num];
qDebug() << numFloors;
}
void Model::setMasses(double *newMasses, int floor)
{
if (floor != 0)
mass[floor-1] = newMasses[0];
else {
for (int i=0; i<numFloors; i++)
mass[i]=newMasses[i];
}
}
|
/// Some cycleways intersect footways with detailed curb mapping. The current rules for figuring
/// out which walking paths also allow bikes are imperfect, so we wind up with short dead-end
/// "stubs." Trim those.
///
/// Also do the same thing for extremely short dead-end service roads.
pub fn trim_deadends(raw: &mut RawMap) {
let mut remove_roads = BTreeSet::new();
let mut remove_intersections = BTreeSet::new();
for (id, i) in &raw.intersections {
let roads = raw.roads_per_intersection(*id);
if roads.len() != 1 || i.intersection_type == IntersectionType::Border {
continue;
}
let road = &raw.roads[&roads[0]];
if road.length() < SHORT_THRESHOLD
&& (is_cycleway(&get_lane_specs_ltr(&road.osm_tags, &raw.config))
|| road.osm_tags.is(osm::HIGHWAY, "service"))
{
remove_roads.insert(roads[0]);
remove_intersections.insert(*id);
}
}
for r in remove_roads {
raw.roads.remove(&r).unwrap();
}
for i in remove_intersections {
raw.delete_intersection(i);
}
// It's possible we need to do this in a fixed-point until there are no changes, but meh.
// Results look good so far.
} |
/**
* A simple application that uses MongoDB to store and manage User details.
*
* @author gazbert
*/
@SpringBootApplication
public class Application implements CommandLineRunner {
private UserService userService;
private RegistrationService registrationService;
@Autowired
public Application(UserService userService, RegistrationService registrationService) {
this.userService = userService;
this.registrationService = registrationService;
}
/**
* Starts the app.
*
* @param args no args required.
*/
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
/**
* Runs the sample app.
*
* @param args no args passed.
*/
@Override
public void run(String... args) {
userService.createUsers();
userService.fetchSomeUsers();
userService.updateUser();
userService.removeUser();
registrationService.createRegistrations();
registrationService.fetchSomeRegistrations();
registrationService.updateRegistration();
registrationService.removeRegistration();
}
} |
k,n = [int(kn) for kn in raw_input().split(" ")]
t = [int(ti) for ti in raw_input().split(" ")]
ans = 0
for b in range(n):
m = 0
o = 0
# if b > 0:
# print
# print b
for i in range(k):
if ((i-b)%n) == 0:
pass
# print '..',
else:
if t[i] == -1:
m += 1
elif t[i] == 1:
o += 1
# print '%2s'%str(t[i]),
# print abs(m-o)
ans = max(ans,abs(m-o))
print ans |
/*
* Create the final wieghted (Gmm) combined curve. The Gmm curves were
* scaled by their weights while building (above).
*/
private void computeFinal() {
double sourceSetWeight = sourceSet.weight();
for (Entry<Imt, Map<Gmm, ArrayXY_Sequence>> entry : curveMap.entrySet()) {
Imt imt = entry.getKey();
ArrayXY_Sequence totalCurve = copyOf(modelCurves.get(imt)).clear();
for (ArrayXY_Sequence curve : entry.getValue().values()) {
totalCurve.add(curve);
}
totalCurve.multiply(sourceSetWeight);
totalCurves.put(imt, totalCurve);
}
} |
def format_for_post(self):
records = []
now = datetime.datetime.now()
for app, sessions in self._apps.iteritems():
for session in sessions:
start = session[0]
end = session[1] or now
records.append(self.DATA_SEPARATOR.join((app, start.isoformat(), end.isoformat())))
return self.RECORD_SEPARATOR.join(records) |
// This file has been automatically generated by writeMessageClasses.js
import { UUID } from '../UUID';
import { Vector3 } from '../Vector3';
import { MessageFlags } from '../../enums/MessageFlags';
import { MessageBase } from '../MessageBase';
import { Message } from '../../enums/Message';
export class UserReportMessage implements MessageBase
{
name = 'UserReport';
messageFlags = MessageFlags.Zerocoded | MessageFlags.FrequencyLow;
id = Message.UserReport;
AgentData: {
AgentID: UUID;
SessionID: UUID;
};
ReportData: {
ReportType: number;
Category: number;
Position: Vector3;
CheckFlags: number;
ScreenshotID: UUID;
ObjectID: UUID;
AbuserID: UUID;
AbuseRegionName: Buffer;
AbuseRegionID: UUID;
Summary: Buffer;
Details: Buffer;
VersionString: Buffer;
};
getSize(): number
{
return (this.ReportData['AbuseRegionName'].length + 1 + this.ReportData['Summary'].length + 1 + this.ReportData['Details'].length + 2 + this.ReportData['VersionString'].length + 1) + 111;
}
// @ts-ignore
writeToBuffer(buf: Buffer, pos: number): number
{
const startPos = pos;
this.AgentData['AgentID'].writeToBuffer(buf, pos);
pos += 16;
this.AgentData['SessionID'].writeToBuffer(buf, pos);
pos += 16;
buf.writeUInt8(this.ReportData['ReportType'], pos++);
buf.writeUInt8(this.ReportData['Category'], pos++);
this.ReportData['Position'].writeToBuffer(buf, pos, false);
pos += 12;
buf.writeUInt8(this.ReportData['CheckFlags'], pos++);
this.ReportData['ScreenshotID'].writeToBuffer(buf, pos);
pos += 16;
this.ReportData['ObjectID'].writeToBuffer(buf, pos);
pos += 16;
this.ReportData['AbuserID'].writeToBuffer(buf, pos);
pos += 16;
buf.writeUInt8(this.ReportData['AbuseRegionName'].length, pos++);
this.ReportData['AbuseRegionName'].copy(buf, pos);
pos += this.ReportData['AbuseRegionName'].length;
this.ReportData['AbuseRegionID'].writeToBuffer(buf, pos);
pos += 16;
buf.writeUInt8(this.ReportData['Summary'].length, pos++);
this.ReportData['Summary'].copy(buf, pos);
pos += this.ReportData['Summary'].length;
buf.writeUInt16LE(this.ReportData['Details'].length, pos);
pos += 2;
this.ReportData['Details'].copy(buf, pos);
pos += this.ReportData['Details'].length;
buf.writeUInt8(this.ReportData['VersionString'].length, pos++);
this.ReportData['VersionString'].copy(buf, pos);
pos += this.ReportData['VersionString'].length;
return pos - startPos;
}
// @ts-ignore
readFromBuffer(buf: Buffer, pos: number): number
{
const startPos = pos;
let varLength = 0;
const newObjAgentData: {
AgentID: UUID,
SessionID: UUID
} = {
AgentID: UUID.zero(),
SessionID: UUID.zero()
};
newObjAgentData['AgentID'] = new UUID(buf, pos);
pos += 16;
newObjAgentData['SessionID'] = new UUID(buf, pos);
pos += 16;
this.AgentData = newObjAgentData;
const newObjReportData: {
ReportType: number,
Category: number,
Position: Vector3,
CheckFlags: number,
ScreenshotID: UUID,
ObjectID: UUID,
AbuserID: UUID,
AbuseRegionName: Buffer,
AbuseRegionID: UUID,
Summary: Buffer,
Details: Buffer,
VersionString: Buffer
} = {
ReportType: 0,
Category: 0,
Position: Vector3.getZero(),
CheckFlags: 0,
ScreenshotID: UUID.zero(),
ObjectID: UUID.zero(),
AbuserID: UUID.zero(),
AbuseRegionName: Buffer.allocUnsafe(0),
AbuseRegionID: UUID.zero(),
Summary: Buffer.allocUnsafe(0),
Details: Buffer.allocUnsafe(0),
VersionString: Buffer.allocUnsafe(0)
};
newObjReportData['ReportType'] = buf.readUInt8(pos++);
newObjReportData['Category'] = buf.readUInt8(pos++);
newObjReportData['Position'] = new Vector3(buf, pos, false);
pos += 12;
newObjReportData['CheckFlags'] = buf.readUInt8(pos++);
newObjReportData['ScreenshotID'] = new UUID(buf, pos);
pos += 16;
newObjReportData['ObjectID'] = new UUID(buf, pos);
pos += 16;
newObjReportData['AbuserID'] = new UUID(buf, pos);
pos += 16;
varLength = buf.readUInt8(pos++);
newObjReportData['AbuseRegionName'] = buf.slice(pos, pos + varLength);
pos += varLength;
newObjReportData['AbuseRegionID'] = new UUID(buf, pos);
pos += 16;
varLength = buf.readUInt8(pos++);
newObjReportData['Summary'] = buf.slice(pos, pos + varLength);
pos += varLength;
varLength = buf.readUInt16LE(pos);
pos += 2;
newObjReportData['Details'] = buf.slice(pos, pos + varLength);
pos += varLength;
varLength = buf.readUInt8(pos++);
newObjReportData['VersionString'] = buf.slice(pos, pos + varLength);
pos += varLength;
this.ReportData = newObjReportData;
return pos - startPos;
}
}
|
<filename>bath_fitting/SDR_fitting.py
import cvxpy as cp
import numpy as np
import mosek
def delta_eval(poles, z, X):
# compute \sum \frac{X_j}{z_i - \lambda_j }
# output =
K = poles.shape[0]
L = X[0].shape[0]
assert X[0].shape[1] == L
diff = 1/(np.reshape(z, (-1, 1, 1, 1)) - np.reshape(poles, (1, K, 1, 1)))
X_array = np.array(X).reshape((1,K,L,L))
return np.sum(diff*X_array, axis = 1)
class SDRFit:
def __init__(self, z, Delta, L, K, solver="SCS"):
self.K = K
self.nz = z.shape[0]
self.L = L
self.Delta = Delta
self.z = z
self.solver = solver
# creating the parameters for the poles
self.poles = [ cp.Parameter() for _ in range(self.K)]
# definin the SDP variables
self.X = []
for ii in range(K):
self.X.append(cp.Variable((L,L), PSD=True))
# convenient stored matrix for SDP
self.diff_param_real = [ cp.Parameter((self.nz)) for _ in range(K)]
self.diff_param_imag = [ cp.Parameter((self.nz)) for _ in range(K)]
# compute \sum \frac{X_j}{z_i - \lambda_j }
sum_poles = []
for j in range(self.nz):
partial_sum = self.X[0]*( self.diff_param_real[0][j]\
+ 1j*self.diff_param_imag[0][j])
for i in range(1, self.K):
partial_sum += self.X[i]*( self.diff_param_real[i][j] \
+ 1j*self.diff_param_imag[i][j])
sum_poles.append(partial_sum)
# compute sum_u [ \sum \frac{X_j}{z_i - \lambda_j } - Delta(z_i) ]^2
self.loss = 0
for j in range(self.nz):
self.loss += cp.sum_squares( sum_poles[j] - Delta[j,:,:])
# self.loss += cp.norm(sum_poles[j] - Delta[j,:,:], p = 'fro')
# setting up the problem
self.prob = cp.Problem(cp.Minimize(self.loss))
def __call__(self, poles, flag = "value", verbose = False):
assert poles.shape[0] == self.K
# creating the diff array
diff_array = [1/(np.reshape(self.z, (-1,)) - pole) for pole in poles]
for diff, val in zip(self.diff_param_real, diff_array):
diff.value = val.real
for diff, val in zip(self.diff_param_imag, diff_array):
diff.value = val.imag
# This is a fairly non-optimal choice of parameters for MOSEK
if self.solver == "MOSEK":
mosek_params_dict = {"MSK_DPAR_INTPNT_CO_TOL_PFEAS": 1.e-10,\
"MSK_DPAR_INTPNT_CO_TOL_DFEAS": 1.e-10,
"MSK_DPAR_INTPNT_CO_TOL_REL_GAP": 1.e-10,
"MSK_DPAR_INTPNT_CO_TOL_NEAR_REL": 1000}
self.prob.solve(solver = "MOSEK", verbose=verbose,\
mosek_params = mosek_params_dict)
else :
self.prob.solve(solver = self.solver,
verbose = verbose,
eps = 1.e-11)
if flag == 'value':
# flag (by default) to return the value of the optimization
return self.prob.value
if flag == 'bath':
# flag to return the bath matrices
return [ self.X[ii].value for ii in range(self.K)]
if flag == 'grad':
# flag to compute the derivative of the function
# we extract the values of X
X_list = [ self.X[ii].value for ii in range(self.K)]
# We compute the approximation
Delta_approx = delta_eval(poles, self.z, X_list)
error_fit = self.Delta - Delta_approx
X_numpy = np.array(X_list).reshape(1, self.K, self.L, self.L)
mat = np.square(diff_array).T.reshape(self.nz, self.K, 1, 1)
C = np.conj(X_numpy*mat)
error_fit = error_fit.reshape(self.nz, 1, self.L, self.L )
grad = -2*np.sum(np.real(C*error_fit), axis = (0,2,3))
# we return the value of the function together with the derivative
return self.prob.value, grad
|
#pragma GCC optimize("O3")
#include<bits/stdc++.h>
#define rc(x) return cout<<x<<endl,0
#define pb push_back
#define in insert
#define er erase
#define fr first
#define sc second
const int inf=INT_MAX;
const int nmax=1e5+5;
const int mod=1e9+7;
typedef long long ll;
using namespace std;
int n,k,i,a[123],j;
string s;
int main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cerr.tie(0);cout.tie(0);
//freopen("sol.in","r",stdin);
cin>>n>>k>>s;
for(i=0;i<s.size();i++)a[s[i]]++;
for(j=1;j<=k;j++)for(i='a';i<='z';i++)if(a[i])a[i]--;
for(i='a';i<='z';i++)if(a[i])rc("NO");
rc("YES");
//return 0;
}
|
def predict(self, num_points=50):
if self.modeltype == 'Numpy':
pred_r = prediction.rec_forecast_np(y=self.df,
model=self.model,
window_length=self.window_length,
feature_names=self.best_features,
rolling_window=self.rolling_window,
n_steps=num_points,
freq=self.freq)
else:
pred_r = prediction.rec_forecast(y=self.df,
model=self.model,
window_length=self.window_length,
feature_names=self.best_features,
rolling_window=self.rolling_window,
n_steps=num_points,
freq=self.freq)
self.pred_r = pred_r
return pred_r |
<filename>src/app/modules/shared/root-components/components/responsive-sidenav/responsive-sidenav.component.ts
import {
Component,
Input,
ViewChild,
OnInit,
OnDestroy,
ChangeDetectionStrategy,
ChangeDetectorRef,
} from '@angular/core';
import { MatSidenav } from '@angular/material/sidenav';
import { Router, NavigationStart, Event } from '@angular/router';
import { WindowService } from '@core/services';
import { SubSink } from 'subsink';
/** Component which abstracts away the logic of showing and hiding an
* Angular Material sidenav in a responsive manner based on a specified
* screen size cutoff.
*/
@Component({
selector: 'blr-responsive-sidenav-container',
templateUrl: './responsive-sidenav.component.html',
styleUrls: ['./responsive-sidenav.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ResponsiveSidenavComponent implements OnInit, OnDestroy {
/** The minimum screen width that we consider to be a large screen.
* For example, if you set screenSizeCutoff to 800, then the sidenav
* will be in smallScreen mode while the screen is 799 pixels wide
* and smaller.
*/
@Input() screenSizeCutoff = 800;
/** Internal ViewChild hook for interacting with the MatSideNav component. */
@ViewChild('sideNav', { static: true }) sideNav: MatSidenav;
private subs = new SubSink();
constructor(
private router: Router,
private changeDetectorRef: ChangeDetectorRef,
private windowService: WindowService
) {}
ngOnInit() {
// Perform CD on window resize so that we can show / hide the sidenav as necessary
this.subs.sink = this.windowService.resize.subscribe(() =>
this.changeDetectorRef.detectChanges()
);
this.subs.sink = this.router.events.subscribe(event =>
this.onRouterEvent(event)
);
}
ngOnDestroy() {
this.subs.unsubscribe();
}
private onRouterEvent(routerEvent: Event) {
/* Hide the sidenav on NavigationStart on small screens because
it's expected that the user clicked one of the nav links in the
expanded sidebar menu. */
if (routerEvent instanceof NavigationStart && this.smallScreen) {
this.sideNav.close();
this.changeDetectorRef.detectChanges();
}
}
/** We're in smallScreen mode if the current window width is less than
* the specified screenSizeCutoff.
*/
public get smallScreen(): boolean {
return this.windowService.innerWidth < this.screenSizeCutoff;
}
/** Toggle the Angular Material Sidenav */
public toggle(): void {
this.sideNav.toggle();
this.changeDetectorRef.detectChanges();
}
}
|
<reponame>zyx-team/zyx-news-service
package com.zyx.grace.result;
/**
* 响应结果枚举,用于提供给GraceJSONResult返回给前端的
* 本枚举类中包含了很多的不同的状态码供使用,可以自定义
* 便于更优雅的对状态码进行管理,一目了然
*/
public enum ResponseStatusEnum {
SUCCESS(200, true, "操作成功!"),
FAILED(500, false, "操作失败!"),
// 50x
UN_LOGIN(501,false,"请登录后再继续操作!"),
TICKET_INVALID(502,false,"会话失效,请重新登录!"),
NO_AUTH(503,false,"您的权限不足,无法继续操作!"),
MOBILE_ERROR(504,false,"短信发送失败,请稍后重试!"),
SMS_NEED_WAIT_ERROR(505,false,"短信发送太快啦~请稍后再试!"),
SMS_CODE_ERROR(506,false,"验证码过期或不匹配,请稍后再试!"),
USER_FROZEN(507,false,"用户已被冻结,请联系管理员!"),
USER_UPDATE_ERROR(508,false,"用户信息更新失败,请联系管理员!"),
USER_INACTIVE_ERROR(509,false,"请前往[账号设置]修改信息激活后再进行后续操作!"),
FILE_UPLOAD_NULL_ERROR(510,false,"文件不能为空,请选择一个文件再上传!"),
FILE_UPLOAD_FAILD(511,false,"文件上传失败!"),
FILE_FORMATTER_FAILD(512,false,"文件图片格式不支持!"),
FILE_MAX_SIZE_ERROR(513,false,"仅支持500kb大小以下的图片上传!"),
FILE_NOT_EXIST_ERROR(514,false,"你所查看的文件不存在!"),
USER_STATUS_ERROR(515,false,"用户状态参数出错!"),
USER_NOT_EXIST_ERROR(516,false,"用户不存在!"),
// 自定义系统级别异常 54x
SYSTEM_INDEX_OUT_OF_BOUNDS(541, false, "系统错误,数组越界!"),
SYSTEM_ARITHMETIC_BY_ZERO(542, false, "系统错误,无法除零!"),
SYSTEM_NULL_POINTER(543, false, "系统错误,空指针!"),
SYSTEM_NUMBER_FORMAT(544, false, "系统错误,数字转换异常!"),
SYSTEM_PARSE(545, false, "系统错误,解析异常!"),
SYSTEM_IO(546, false, "系统错误,IO输入输出异常!"),
SYSTEM_FILE_NOT_FOUND(547, false, "系统错误,文件未找到!"),
SYSTEM_CLASS_CAST(548, false, "系统错误,类型强制转换错误!"),
SYSTEM_PARSER_ERROR(549, false, "系统错误,解析出错!"),
SYSTEM_DATE_PARSER_ERROR(550, false, "系统错误,日期解析出错!"),
// admin 管理系统 56x
ADMIN_USERNAME_NULL_ERROR(561, false, "管理员登录名不能为空!"),
ADMIN_USERNAME_EXIST_ERROR(562, false, "管理员登录名已存在!"),
ADMIN_NAME_NULL_ERROR(563, false, "管理员负责人不能为空!"),
ADMIN_PASSWORD_ERROR(564, false, "密码不能为空后者两次输入不一致!"),
ADMIN_CREATE_ERROR(565, false, "添加管理员失败!"),
ADMIN_PASSWORD_NULL_ERROR(566, false, "密码不能为空!"),
ADMIN_NOT_EXIT_ERROR(567, false, "管理员不存在或密码错误!"),
ADMIN_FACE_NULL_ERROR(568, false, "人脸信息不能为空!"),
ADMIN_FACE_LOGIN_ERROR(569, false, "人脸识别失败,请重试!"),
CATEGORY_EXIST_ERROR(570, false, "文章分类已存在,请换一个分类名!"),
// 媒体中心 相关错误 58x
ARTICLE_COVER_NOT_EXIST_ERROR(580, false, "文章封面不存在,请选择一个!"),
ARTICLE_CATEGORY_NOT_EXIST_ERROR(581, false, "请选择正确的文章领域!"),
ARTICLE_CREATE_ERROR(582, false, "创建文章失败,请重试或联系管理员!"),
ARTICLE_QUERY_PARAMS_ERROR(583, false, "文章列表查询参数错误!"),
ARTICLE_DELETE_ERROR(584, false, "文章删除失败!"),
ARTICLE_WITHDRAW_ERROR(585, false, "文章撤回失败!"),
ARTICLE_REVIEW_ERROR(585, false, "文章审核出错!"),
ARTICLE_ALREADY_READ_ERROR(586, false, "文章重复阅读!"),
// 人脸识别错误代码
FACE_VERIFY_TYPE_ERROR(600, false, "人脸比对验证类型不正确!"),
FACE_VERIFY_LOGIN_ERROR(601, false, "人脸登录失败!"),
// 系统错误,未预期的错误 555
SYSTEM_ERROR(555, false, "系统繁忙,请稍后再试!"),
SYSTEM_OPERATION_ERROR(556, false, "操作失败,请重试或联系管理员"),
SYSTEM_RESPONSE_NO_INFO(557, false, ""),
SYSTEM_ERROR_GLOBAL(558, false, "全局降级:系统繁忙,请稍后再试!"),
SYSTEM_ERROR_FEIGN(559, false, "客户端Feign降级:系统繁忙,请稍后再试!"),
SYSTEM_ERROR_ZUUL(560, false, "请求系统过于繁忙,请稍后再试!");
// 响应业务状态
private Integer status;
// 调用是否成功
private Boolean success;
// 响应消息,可以为成功或者失败的消息
private String msg;
ResponseStatusEnum(Integer status, Boolean success, String msg) {
this.status = status;
this.success = success;
this.msg = msg;
}
public Integer status() {
return status;
}
public Boolean success() {
return success;
}
public String msg() {
return msg;
}
}
|
/**
* Creates the Shape_c subtype if it doesn't exist
* already, this method also fixes it's own inconsistency
* by removing the additional subtype (the method originally
* created a new subtype even if a ContainingShape_c subtype
* already existed)
*/
public void createShapeSubtypes(Ooaofgraphics root) {
Shape_c[] shapes = Shape_c.ShapeInstances(root, null, false);
for(int i = 0; i < shapes.length; i++) {
NoncontainingShape_c ncs = NoncontainingShape_c.getOneGD_NCSOnR28(shapes[i]);
ContainingShape_c cs = ContainingShape_c.getOneGD_CTROnR28(shapes[i]);
if(ncs == null && cs == null) {
ncs = new NoncontainingShape_c(root);
ncs.relateAcrossR28To(shapes[i]);
}
if(ncs != null && cs != null) {
shapes[i].unrelateAcrossR28From(ncs);
ncs.delete();
}
}
} |
In the previous part of VivaGlobetrotting you will have found out that Alejandro Hurtado has left Chicago Fire in the MLS to join an unnamed Spanish La Liga team.
As it is 2031, it seems an appropriate point to take a look back at some of Hurtado’s past clubs to see how they are getting on now.
It also serves the purpose of a reminder of our journey so far since we began this save back in November 2016.
So, let’s begin with Alejandro Hurtado’s first job in management: Deportes Puerto Montt.
Deportes Puerto Montt
Under Hurtado
2016-2017 (221 days in charge)
Matches: 17
Wins: 1
8th January 2017: Sacked after six months in charge.
Since Hurtado
Deportes Puerto Montt came so close to winning promotion to the Primera Division in 2023, finishing 2nd in the league behind Deportes Melipilla.
They’ve remained a Primera B side but will certainly look at the career of their sacked manager Hurtado and wonder what could have been.
Union San Felipe
Under Hurtado
2017-2023 (2433 days in charge)
1 Primera title
2 Primera B titles
Alejandro Hurtado took Union San Felipe from the depths of the second tier of Chile to the very top, beating the likes of Colo Colo and Universidad de Chile to win the Primera in 2022.
Matches: 253
Wins: 134
Since Hurtado
Union San Felipe have dropped off from their title winning highs.
Since coming 3rd in Hurtado’s final season, USF have become a mid-table Primera side and have not been able to replicate the successes from earlier in the decade.
Alejandro Hurtado vs Pablo Guede. A clear winner emerges.
Deportes Tolima
Under Hurtado
2023-2026 (897 days in charge)
The 2025 seasons under Hurtado’s leadership remain the most infamous year in Tolima’s history.
3 penalty shootout losses in 3 finals (Apertura, Finalizacion and Colombian Cup) put the wheels in motion for Hurtado’s departure the following summer.
Matches: 140
Wins: 68
Since Hurtado
Like Union San Felipe, Deportes Tolima have been unable to build on the progress made by Hurtado throughout his time in Colombia. In two full seasons, Hurtado built Tolima into a top five club.
But Tolima have now dropped off, and in their most recent season finished 10th and 14th. An identical finish to that of Hurtado’s first season in charge of the Colombian side.
Club Atletico River Plate
Under Hurtado
2026-2028 (776 days in charge)
Matches: 111
Wins: 65
River Plate won the Argentine Primera two years in a row prior to Hurtado’s arrival at the club. This showed that he had a good squad capable of winning the league again and perhaps pushing for Copa Libertadores success.
But in two full seasons at the club, Hurtado failed to live up to the high expectations, finishing 3rd in both seasons. He did, however, win one Argentinian Cup to lift his spirits slightly.
Since Hurtado
River Plate have improved to become the top side in Argentina once more. In three seasons without the Chilean, their league finishes have been 2nd, 1st and 1st.
The latest season won’t show on the graph, but two league wins since Hurtado’s departure proves that River Plate will be seen as a failure on Hurtado’s CV.
Chicago Fire
Under Hurtado
2028-2031 (962 days in charge)
Matches: 76
Wins: 21
Hurtado took charge of Chicago Fire in 2028 when they had just eight playable players. The rest of the squad were made up of greyed out players.
Over three years at the club, Hurtado built a side that were competitive and difficult to beat but left before any successes could be had with the team. He led Chicago to a 14th place finish in his final full season in the MLS.
Since Hurtado
Despite having only just left Chicago Fire, we have actually completed one full season at our new club. Let’s take a peek at how Chicago Fire performed in the 2031 season!
An incredible season saw Chicago Fire come second in the MLS Supporters Shield, winning their Eastern Conference in the process.
Would Chicago have performed this well with Hurtado in charge? Perhaps. But it must be said that the squad that Hurtado built, from just eight playable players in 2028, is a truly brilliant achievement.
Chicago owe a lot to the Chilean manager.
Colombia
In 2025 Alejandro Hurtado took up the role of Colombian national manager. He oversaw the team progress through to the 2026 World Cup where he led them to a Quarter Final.
To see more about our World Cup campaign follow this link.
Hurtado resigned as manager of Colombia after the 2026 World Cup to focus on his club career.
15 Years as a Manager
Matches: 608
Wins: 296
Draws: 136
Losses: 176
Top Honours
2x Chilean Primera B
1x Chilean Primera
1x Copa Argentina
Alejandro Hurtado’s next move
So where has our manager ended up. In the last part of VivaGlobetrotting we said that he had been offered a role at a well established club in the Spanish La Liga.
And it can be confirmed that Celta Vigo have signed Alejandro Hurtado on a two year deal!
Take a look at our Social Networks | Follow our Twitter or Like our Facebook Page
Thanks for reading this 15 year review of our VivaGlobetrotting adventure.
It has certainly been one of my favourite ever FM saves and I hope it can continue until a satisfying end with Alejandro Hurtado winning the Champions League with Sevilla.
Let’s hope we can make it there!
VivaLaVidaFM |
<reponame>cedrictrovati-bib/sp-dev-fx-controls-react
export * from './FolderTile';
export * from './IFolderTileProps';
|
// Get returns the value stored at the given key. If an object was previously
// stored at the key, it serialized bytes will be returned.
func (t *Tx) Get(ctx context.Context, key string) (string, error) {
okey, err := internal.NewObjectKey(key)
if err != nil {
return "", err
}
s, err := t.tx.Get(ctx, okey.String())
if err != nil {
return "", err
}
v, err := internal.ParseValue(s)
if err != nil {
return "", err
}
return v.Data, nil
} |
/**
* Find string "findStr" in another string "str"
* Returns true if found, false elsewhere
*/
int16_t SIM808Driver::strIndex(const char *str, const char *findStr, uint16_t startIdx)
{
int16_t firstIndex = -1;
int16_t sizeMatch = 0;
for (int16_t i = startIdx; i < strlen(str); i++)
{
if (sizeMatch >= strlen(findStr))
{
break;
}
if (str[i] == findStr[sizeMatch])
{
if (firstIndex < 0)
{
firstIndex = i;
}
sizeMatch++;
}
else
{
firstIndex = -1;
sizeMatch = 0;
}
}
if (sizeMatch >= strlen(findStr))
{
return firstIndex;
}
else
{
return -1;
}
} |
<reponame>admiraltyio/multicluster-controller
/*
Copyright 2018 The Multicluster-Controller Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package deploymentcopy // import "admiralty.io/multicluster-controller/examples/deploymentcopy/pkg/controller/deploymentcopy"
import (
"context"
"fmt"
"reflect"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"admiralty.io/multicluster-controller/pkg/cluster"
"admiralty.io/multicluster-controller/pkg/controller"
"admiralty.io/multicluster-controller/pkg/reconcile"
"admiralty.io/multicluster-controller/pkg/reference"
)
func NewController(ctx context.Context, src *cluster.Cluster, dst *cluster.Cluster) (*controller.Controller, error) {
srcClient, err := src.GetDelegatingClient()
if err != nil {
return nil, fmt.Errorf("getting delegating client for source cluster: %v", err)
}
dstClient, err := dst.GetDelegatingClient()
if err != nil {
return nil, fmt.Errorf("getting delegating client for destination cluster: %v", err)
}
co := controller.New(&reconciler{source: srcClient, destination: dstClient}, controller.Options{})
if err := co.WatchResourceReconcileObject(ctx, src, &appsv1.Deployment{}, controller.WatchOptions{}); err != nil {
return nil, fmt.Errorf("setting up Deployment watch in source cluster: %v", err)
}
if err := co.WatchResourceReconcileController(ctx, dst, &appsv1.Deployment{}, controller.WatchOptions{}); err != nil {
return nil, fmt.Errorf("setting up Deployment watch in destination cluster: %v", err)
}
return co, nil
}
type reconciler struct {
source client.Client
destination client.Client
}
func (r *reconciler) Reconcile(req reconcile.Request) (reconcile.Result, error) {
p := &appsv1.Deployment{}
if err := r.source.Get(context.TODO(), req.NamespacedName, p); err != nil {
if errors.IsNotFound(err) {
// ...TODO: multicluster garbage collector
// Until then...
err := r.deleteCopy(req.NamespacedName)
return reconcile.Result{}, err
}
return reconcile.Result{}, err
}
dc := makeCopy(p)
reference.SetMulticlusterControllerReference(dc, reference.NewMulticlusterOwnerReference(p, p.GroupVersionKind(), req.Context))
oc := &appsv1.Deployment{}
if err := r.destination.Get(context.TODO(), req.NamespacedName, oc); err != nil {
if errors.IsNotFound(err) {
err := r.destination.Create(context.TODO(), dc)
return reconcile.Result{}, err
}
return reconcile.Result{}, err
}
if reflect.DeepEqual(dc.Spec, oc.Spec) {
return reconcile.Result{}, nil
}
oc.Spec = dc.Spec
err := r.destination.Update(context.TODO(), oc)
return reconcile.Result{}, err
}
func (r *reconciler) deleteCopy(nsn types.NamespacedName) error {
g := &appsv1.Deployment{}
if err := r.destination.Get(context.TODO(), nsn, g); err != nil {
if errors.IsNotFound(err) {
// all good
return nil
}
return err
}
if err := r.destination.Delete(context.TODO(), g); err != nil {
return err
}
return nil
}
func makeCopy(d *appsv1.Deployment) *appsv1.Deployment {
spec := d.Spec.DeepCopy()
return &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Namespace: d.Namespace,
Name: d.Name,
},
Spec: *spec,
}
}
|
Beyond Learner-Centered Practice: Adult Education, Power, and Society.
At the heart of practice in most conceptions of adult education is the adult
learner whose needs for learning, once uncovered, can be met through the
effective design of educational programs. There has been increasing
dissatisfaction with this view of practice, however, as adult education has
moved to a central position in the constitution of social, cultural, and
economic life. Learner-centeredness is a naive position that does not come
close to approximating the political and ethical dilemmas nor the
contradictions and the possibilities for action in this new situation for adult
education. In place of learner-centeredness we suggest that adult
education in the next millennium must be seen as a struggle for the
distribution of knowledge and power in society. At the heart of practice,
then, should be a vision linking adult education, power, and society.
Resume La plupart des conceptions andragogiques placent l'apprenant au centre
de leur preoccupation pratique. Elles considerent que les besoins
d'apprentissage de celui-ci, une fois identifies, peuvent etre rencontres
grace au design de programmes educatifs. Or, cette conception s'est butee
a une insatisfaction croissante alors que la pratique andragogique
s'etablissait au cœur la vie sociale, culturelle et economique. La notion
d'intervention centree sur l'apprenant est naive et ne rend pas compte des
dilemmes politiques et ethiques, ni des contradictions et des possibilites
d'action dans le nouveau contexte. A l'aube du nouveau millenaire, nous
suggerons plutot une representation de l'andragogie qui etaye la lutte
pour une distribution equitable du savoir et dupouvoir dans la societe. La
pratique devient alors tributaire d'une vision liant andragogie, pouvoir et
societe. |
/**
* Group regular expression settings by xml
* group-regular.xml
* @author zonglu
*/
public class GroupRegularExpression
{
@Test(groups="group1.one")
public void group1One()
{
System.out.println("group1 one");
}
@Test(groups="group1.two")
public void group1Two()
{
System.out.println("group1 two");
}
@Test(groups="group2.one")
public void group2One()
{
System.out.println("group2 one");
}
@Test(groups="group2.two")
public void group2Two()
{
System.out.println("group2 two");
}
} |
Southern Fluffy Gluten Free Biscuit Recipe
Friends, I am excited. Finally, a Southern, fluffy, gluten free biscuit I am proud of.
I worked for six months experimenting on a gluten free biscuit. The feedback has been heart warming, and gratifying as it quickly rose to my number one food post out of 1,000 recipes.
This is my rice flour based gluten free biscuit. The next biscuit that is wildly popular is my almond flour based low-carb, grain free biscuit. Both are very worthy, so it will be up to you.
You see, I never set out to make a good Southern fluffy biscuit here at Spinach Tiger, but I did and the comments and emails I still receive years later on this recipe have proved how good my biscuit recipe and technique is.
However, I know many of you are gluten free, as am I, because of a health issue, and you deserve to have the best biscuit possible.
I have Hashimoto’s and wrote about my personal story with this immune disorder that affects the thyroid, and while gluten doesn’t seem to make me sick, it’s very discouraged. This is why you are seeing an increasing amount of gluten-free baked goods and grain free baked goods.
I am one of more blessed people with this disease, because I haven’t had any serious symptoms, as it was discovered early and medication has balanced my thyroid numbers. I want to keep it that way and eat as healthy as possible. That means no gluten. (It pays to get a wellness blood test every year that checks your thyroid).
About Gluten Free Biscuit Recipes and My Trial and Error
This is not going to be the exact duplicate of my original Southern biscuit. However, I’ve gotten as close as I think I can get.
I experimented with flours. I experimented with eggs, no eggs, buttermilk, fake buttermilk and cream, corn starch, no corn starch.
I made several batches, sometimes one after another. Then yesterday morning, the second batch of the day got the result I was looking for.
The problem with gluten free biscuit baking is that too many of the biscuits were grainy, tasted funky, and didn’t rise. Sometimes they were too gummy and sometimes they didn’t brown. The most noticeable issue was that, if left on the counter all day, they turned to rocks.
One unusual counter intuitive attribute about gluten free biscuits is that you can’t eat them right out of the oven. The texture will be a bit gummy; let them cool about five or 10 minutes.
My Criteria for a Gluten Free Biscuit
Realizing gluten free biscuits cannot be exactly the same as gluten-floured biscuits, I still had a criteria.
Texture could not be grainy, but must be crispy outside, fluffy inside. Flavor. No after taste, just buttery. Rise. Biscuits would have to rise or they are not biscuits. Southern Approved. Mr. Spinach Tiger, who has a perfect palate, gives the thumbs up. He tasted every batch, and actually guided me to the right balance of ingredients and texture.
My Secret for a Gluten Free Biscuit
This might seem odd, but I tried adding in ricotta cheese and this gave me the texture and flavor I was looking for. If you don’t want to use ricotta cheese, they will still be good, especially since I have added in golden flax meal.
Gluten Free Flour. I did not mix my own gluten free flour for this biscuit. I know you’re not going to do that and truthfully, that is just too tenuous and inconsistent. I chose a flour readily available in the grocery store. If you want to make your own flour, I do have a recipe for you here.
Bob’s Red Mill 1-1 Baking is the flour of my choice and you can order it here. If that changes, I’ll let you know. If you think you have something better, let me know. They have a biscuit recipe on the back and I did not use that. Mine is better.
Stay away from gluten free flours that have beans because the flavor will not be satisfactory. Stay away from gluten free flours where the first ingredient is corn starch.
No to Corn Starch. I’ve seen some recipes out there that add a half cup of corn starch. I tried that recipe that claimed greatness and it was the worst of ten batches. The biscuit was grainy, flat, and tasted terrible.
Eggs. Many recipes call for 1 egg per cup of flour. I found that 1 egg per two cups of flour reduced that odd gummy texture I didn’t like.
Butter. Real unsalted butter is the only way I make biscuits, again for flavor and texture.
You can make really small ones too out of the same batch.
Salt and sugar add flavor and the sugar helps the biscuits brown.
Golden Flax Meal adds something to the texture and flavor, but it’s an option. My original recipe didn’t include this. I discovered it when I made these biscuits for this chicken pot pie.
Liquid: I like Real Buttermilk. It’s not just for texture; it’s for flavor. See notes below for substitutes. However, you can also use whole milk with a teaspoon of added white vinegar. Some have had great success with almond milk!
I paid attention to the tips I’ve outlined in my original Southern Fluffy recipe. I decided that the gluten free biscuit should not touch (we call this kissing) as I recommend in regular biscuits so that the edges brown, but I still maintain a hot oven of 450°F.
Size of Biscuit – This recipe only makes eight biscuits. The round is about 7 inches in diameter, no more, as that will result in a flat dry biscuit. It’s very important that you do not roll this out any larger or flatter or you will be disappointed.
You Need Sticky Dough to Make a Good Gluten Free Biscuit
You need sticky dough. If you feel the dough is too sticky to work with, you can make these drop biscuits, but just spooning the dough onto the cookie sheet. You may want to watch the video to see how I deal with the sticky dough. I highly recommend you watch the video.
You Can Make a Gluten Free Biscuit Dairy Free by Doing This
If you have to eat dairy free, substitute the buttermilk with almond milk, water or coconut milk along with a teaspoon of white vinegar. Vinegar will add tenderness to the biscuit dough. Mix the egg right into the liquid.
Substitute the butter with this shortening by Nutiva. Using a fork, add in shortening in small pieces. You may need to use your hands. Freeze this for twenty minutes, and refrigerate the liquid. Once you add the liquid into this flour mixture, then mix according to the directions. Remember sticky dough!
Chicken Pot Pie with Gluten Free Biscuits, a Comfort Food Dinner
You may also like to make a dinner with these biscuits, making a gluten free Chicken Pot Pie with Biscuits.
Gluten Free Strawberry Biscuits with video – Similar to this recipe, but sweeter and with strawberries. Instead of ricotta cheese, I use yogurt to get the right texture.
Gluten Free Pizza Crust – The one thing I missed the most was pizza. Friends, this gluten-free pizza crust is just simply amazing. It’s chewy and crispy and there’s a video.
My Absolute Favorite Gluten Free Baking Recipe is this Bread and It’s Easy
This recipe for Gluten French Bread is another one I did ten times to make it perfect. It’s so easy, made in 60 minutes start to finish, and you can freeze it.
Gluten Free Focaccia
You may also want to try these gluten free sweet potato biscuits.
You may also like my latest GRAIN FREE BISCUIT which is also keto, low-carb, low calorie and diabetic friendly.
My Newest Recipe is the Grain Free Stuffing Made with Sausage
I get a lot of emails about this biscuit. Feel free to write me at anytime at [email protected]
Let me know what gluten free baking you would like me to do! What are you missing the most? |
Novel investigational drugs for basal cell carcinoma
Importance of the field: In the United States, the annual incidence of basal cell carcinoma (BCC) is close to 1 million. Ultraviolet radiation exposure is the main risk factor; however, the availability of ever more potent sunscreens and education have not prevented the rise in BCC incidence. Therefore, concerted effects to identify novel preventive and therapeutic strategies are necessary. Areas covered in this review: This article summarizes our current understanding of the etiology and molecular mechanisms of BCC tumorigenesis and discusses the preclinical and clinical studies to identify agents with anti-BCC efficacy. What the reader will gain: The discovery that hyperactive Hh pathway signaling causes several cancers, including BCC, has spawned the development of many pharmacologic inhibitors of Hh signaling. Early clinical testing of the most advanced, GDC-0449, demonstrated impressive efficacy in patients with advanced BCC. Other promising anti-BCC chemopreventive strategies include drugs that are already FDA-approved for treating other diseases. Take home message: Preclinical and clinical trials with pre-existing FDA-approved drugs suggest novel uses for BCC chemoprevention and treatment. Also, new chemical entities that inhibit the Hh pathway show promise, and in combination with other drugs may provide a nonsurgical cure for this most common cancer. |
// Copyright 2004-9 Trustees of Indiana University
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// read_graphviz_new.hpp -
// Initialize a model of the BGL's MutableGraph concept and an associated
// collection of property maps using a graph expressed in the GraphViz
// DOT Language.
//
// Based on the grammar found at:
// http://www.graphviz.org/cvs/doc/info/lang.html
//
// Jeremiah rewrite used grammar found at:
// http://www.graphviz.org/doc/info/lang.html
// and page 34 or http://www.graphviz.org/pdf/dotguide.pdf
//
// See documentation for this code at:
// http://www.boost.org/libs/graph/doc/read_graphviz.html
//
// Author: Jeremiah Willcock
// Ronald Garcia
//
#ifndef BOOST_READ_GRAPHVIZ_NEW_HPP
#define BOOST_READ_GRAPHVIZ_NEW_HPP
#include <boost/ref.hpp>
#include <boost/property_map/dynamic_property_map.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/detail/workaround.hpp>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <utility>
#include <map>
#include <iostream>
#include <cstdlib>
namespace boost {
namespace read_graphviz_detail {
typedef std::string node_name;
typedef std::string subgraph_name;
typedef std::map<std::string, std::string> properties;
struct node_and_port {
node_name name;
std::string angle; // Or empty if no angle
std::vector<std::string> location; // Up to two identifiers
friend inline bool operator==(const node_and_port& a, const node_and_port& b) {
return a.name == b.name &&
a.angle == b.angle &&
a.location == b.location;
}
friend inline bool operator<(const node_and_port& a, const node_and_port& b) {
if (a.name != b.name) return a.name < b.name;
if (a.angle != b.angle) return a.angle < b.angle;
return a.location < b.location;
}
};
struct edge_info {
node_and_port source;
node_and_port target;
properties props;
};
struct parser_result {
bool graph_is_directed;
bool graph_is_strict;
std::map<node_name, properties> nodes; // Global set
std::vector<edge_info> edges;
std::map<subgraph_name, properties> graph_props; // Root and subgraphs
};
// The actual parser, from libs/graph/src/read_graphviz_new.cpp
void parse_graphviz_from_string(const std::string& str, parser_result& result, bool want_directed);
// Translate from those results to a graph
void translate_results_to_graph(const parser_result& r, ::boost::detail::graph::mutate_graph* mg);
} // namespace read_graphviz_detail
namespace detail {
namespace graph {
BOOST_GRAPH_DECL bool read_graphviz_new(const std::string& str, boost::detail::graph::mutate_graph* mg);
} // end namespace graph
} // end namespace detail
template <typename MutableGraph>
bool read_graphviz_new(const std::string& str,
MutableGraph& graph, boost::dynamic_properties& dp,
std::string const& node_id = "node_id") {
boost::detail::graph::mutate_graph_impl<MutableGraph> mg(graph, dp, node_id);
return detail::graph::read_graphviz_new(str, &mg);
}
} // namespace boost
#endif // BOOST_READ_GRAPHVIZ_NEW_HPP
|
import os
import re
import toml
import subprocess
from typing import Dict, Optional, List
import logging
logger = logging.Logger(__name__)
def no_exist_msg(s: str) -> str:
"""return no exist s in config"""
return f"{s} do not exist in qsubpy_config.toml"
class Resource:
def __init__(self, config: Dict) -> None:
self.resource_params: str = config["resource"]["header"].rstrip("\n")
self.default_mem: str = config["resource"]["default_mem"]
self.default_slot: str = config["resource"]["default_slot"]
def _resource(self, mem: str = None, slot: str = None) -> str:
if mem is None:
mem = self.default_mem
if slot is None:
slot = self.default_slot
return self.resource_params.replace("{mem}", str(mem)).replace(
"{slot}", str(slot)
)
class SingularityConfig:
def __init__(self, config: Dict) -> None:
singularity = config.get("singularity")
if singularity is None:
logger.warn(no_exist_msg("singularity"))
self.singularity_image_root = None
self.singularity_default_ext = None
else:
self.singularity_image_root = singularity.get("image_root")
self.singularity_default_ext = singularity.get("default_ext")
def singularity_image(self, image: str, root: Optional[str]) -> str:
if self.singularity_default_ext is None:
logger.warn(f"singularity default ext is not set in config.toml, so use image name: {image} directly!")
else:
if not image.endswith(self.singularity_default_ext):
image += f".{self.singularity_default_ext}"
# image is abspath
if image.startswith(os.path.sep) or image.startswith("~"):
return image
# overwrite root information
if root is not None:
return os.path.join(root, image)
# use default root information
if self.singularity_image_root is not None:
return os.path.join(self.singularity_image_root, image)
# return image only
return image
#!TODO: add log path
#!TODO: add singularity
class Config:
def __init__(self, config: dict):
self.header: str = config["scripts"]["header"].rstrip("\n")
self.body: str = config["scripts"]["body"].rstrip("\n")
# Reource
self.resources = Resource(config)
# array job
self.array_job_id: Optional[str] = None
if config["arrayjob"]["id"].startswith("$"):
self.array_job_id = config["arrayjob"]["id"]
else:
self.array_job_id = "$" + config["arrayjob"]["id"]
self.array_params: str = config["arrayjob"]["header"].rstrip("\n")
# qsub option
options = config.get("options")
if options is None:
logger.warn(no_exist_msg("Options"))
self.sync_options = None
self.ord_options = None
else:
self.sync_options: Optional[List[str]] = options.get("sync")
self.ord_options: Optional[List[str]] = options.get("order")
# jid re
jid = config.get("jid")
if jid is None:
logger.warn(no_exist_msg("jid"))
self.jid_re = None
else:
self.jid_re: Optional[re.Pattern] = re.compile(config["jid"].get("re"))
# common variables
common_variables = config.get("common_variables")
if common_variables is None:
self.common_variables = {}
else:
self.common_variables = common_variables
# singularity
self.singularity_config = SingularityConfig(config)
def resource(self, mem: Optional[str] = None, slot: Optional[str] = None) -> str:
return self.resources._resource(mem=mem, slot=slot)
def array_header_with_cmd(self, command: str) -> tuple:
length = self.bash_array_len(command)
array_header = (
self.array_params.replace("{start}", "1")
.replace("{end}", str(length))
.replace("{step}", "1")
)
array = f"array=($({command}))"
# like following
# elem=${array[$(($SGE_TASK_ID-1))]}
elem = "elem=${array[$((" + self.array_job_id + "-1))]}"
return array_header, "\n".join([array, elem])
def sync_qsub_command(self) -> list:
return ["qsub"] + self.sync_options
def ord_qsub_command(self, jid: str) -> list:
cmd = ["qsub"]
for s in self.ord_options:
if "{JID}" in s:
cmd.append(s.replace("{JID}", jid))
else:
cmd.append(s)
return cmd
def make_common_variables_list(self):
if self.common_variables == {}:
return []
ret = []
for k, v in self.common_variables.items():
ret.append(k + "=" + "\"" + str(v) + "\"")
return ret
def common_variables_1linear(self) -> str:
l = self.make_common_variables_list()
if len(l) == 0:
return ""
ret_command = ""
ret_command = " && ".join(l)
ret_command += " && "
return ret_command
def make_common_variables_params(self):
return "\n".join(self.make_common_variables_list())
def bash_array_len(self, command: str) -> int:
"""array length of bash
Args:
command (str): command
Returns:
int: length of array in bash
>>> bash_array_len("echo 'a b'")
2
"""
len_command = self.common_variables_1linear()
len_command += " ".join([f"t=($({command}))", "&&", "echo ${#t[@]}"])
logger.debug(f"len_command: {len_command}")
proc = subprocess.run(
len_command, shell=True, capture_output=True, executable="/bin/bash"
)
try:
ret = int(proc.stdout)
except:
logger.error(f"{len_command} results cannot to convert integer")
raise ValueError(
"Invalid literal for int(). Please check your array command!"
)
return ret
def __str__(self):
ret = ["-" * 20]
ret.append("config_path: " + get_default_config_path())
def get_default_config_path() -> str:
path = os.environ.get("QSUBPY_CONFIG")
if path is None:
home = os.environ["HOME"]
path = os.path.join(home, ".config", "qsubpy_config.toml")
return path
def read_config(path: str = None) -> Config:
path = get_default_config_path()
config_dict = toml.load(open(path))
return Config(config_dict)
SHIROKANE_CONFIG = '''
[scripts]
header = """
#!/bin/bash
#$ -S /bin/bash
#$ -cwd
"""
body = """
source ~/.bashrc
source ~/.bash_profile
set -eu
"""
[resource]
default_mem = "4G"
default_slot = "1"
header = """
#$ -l s_vmem={mem} -l mem_req={mem}
#$ -pe def_slot {slot}
"""
[arrayjob]
id = "SGE_TASK_ID"
header = "#$ -t {start}-{end}:{step}"
[options]
sync = ["-sync", "y"]
order = ["-hold_jid", "{JID}"]
[jid]
"Your (job|job-array) (?P<jid>\\d{8})"
[singularity]
image_root = "~/singularity_img"
default_ext = "sif"
'''
def generate_default_config():
path = get_default_config_path()
if os.path.exists(path):
return
with open(path, "w") as f:
f.write(SHIROKANE_CONFIG)
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static class Node {
int p = -1, l, r;
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
Node[] nodes = new Node[n];
for (int i = 0; i < n; i++) nodes[i] = new Node();
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(reader.readLine());
int id = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
nodes[id].l = l;
nodes[id].r = r;
if (l != -1) nodes[l].p = id;
if (r != -1) nodes[r].p = id;
}
reader.close();
int rootId = -1;
for (int i = 0; i < n; i++) {
if (nodes[i].p == -1) {
rootId = i;
break;
}
}
System.out.println("Preorder");
preOrder(nodes, rootId);
System.out.println();
System.out.println("Inorder");
inOrder(nodes, rootId);
System.out.println();
System.out.println("Postorder");
postOrder(nodes, rootId);
System.out.println();
}
private static void preOrder(Node[] nodes, int u) {
if (u == -1) return;
System.out.print(" " + u);
preOrder(nodes, nodes[u].l);
preOrder(nodes, nodes[u].r);
}
private static void inOrder(Node[] nodes, int u) {
if (u == -1) return;
inOrder(nodes, nodes[u].l);
System.out.print(" " + u);
inOrder(nodes, nodes[u].r);
}
private static void postOrder(Node[] nodes, int u) {
if (u == -1) return;
postOrder(nodes, nodes[u].l);
postOrder(nodes, nodes[u].r);
System.out.print(" " + u);
}
}
|
package com.boot.payment.init;
import com.boot.payment.properties.WxProperties;
import lombok.Data;
import java.security.PrivateKey;
/**
* 微信支付元数据
*
* @author lizhifu
* @date 2021/1/12
*/
@Data
public class WxMetaData {
/**
* privateKey
*/
private PrivateKey privateKey;
/**
* 配置文件信息
*/
private WxProperties.Detail detail;
}
|
// Note sets the value of the 'note' attribute to the given value.
//
//
func (b *EventBuilder) Note(value string) *EventBuilder {
b.note = value
b.bitmap_ |= 8192
return b
} |
def create_mask(image):
selem = skimage.morphology.disk(2)
im = equalize_adaptive_clahe(image)
im = threshold_otsu(im)
im = erosion_binary(im, selem)
mask = np.ones(im.shape, dtype=bool)
segmentation = connected_components(im, background=0)
for i in segmentation.identifiers:
region = segmentation.region_by_identifier(i)
if region.area > 5000:
mask[np.where(region.convex_hull)] = False
return Image.from_array(mask) |
<gh_stars>1-10
import base64
import tempfile
import nibabel
import numpy as np
import os
from nilearn._utils import check_niimg
def _get_64(niimg):
f = check_niimg(niimg)
data = f.get_data().astype(float)
data = data + data.min()
data = data / data.max() * 254.
data = data.astype(np.uint8)
f = nibabel.Nifti1Image(data, f.get_affine())
_, filename = tempfile.mkstemp(suffix='.nii.gz')
f.to_filename(filename)
with open(filename, 'rb') as f:
b64 = base64.b64encode(f.read())
os.unlink(filename)
return b64.decode('utf-8')
def papaya_viewer(maps_niimg, output_file=None):
# The template is tempita compliant but I don't include it just for a
# simple replace. If it becomes a dependency, use it here.
# import tempita
open_in_browser = (output_file is None)
if open_in_browser:
_, output_file = tempfile.mkstemp(suffix='.html')
body = ""
package_directory = os.path.dirname(os.path.abspath(__file__))
data = os.path.join(package_directory, "data", "papaya")
with open(os.path.join(data, 'template.html'), 'rb') as f:
template = f.read().decode('utf-8')
javascript = u''
javascript += 'var maps = "'
javascript += _get_64(maps_niimg)
javascript += '";\n'
javascript += 'var template = "'
javascript += _get_64(os.path.join(data, 'template.nii.gz'))
javascript += '";\n'
with open(os.path.join(data, 'papaya.js'), 'rb') as f:
javascript += f.read().decode('utf-8')
with open(os.path.join(data, 'papaya.css'), 'rb') as f:
css = f.read().decode('utf-8')
text = template.replace('{{css}}', css)
text = text.replace('{{javascript}}', javascript)
text = text.replace('{{body}}', body)
with open(output_file, 'wb') as m:
m.write(text.encode('utf-8'))
if open_in_browser:
from nilearn._utils.compat import _urllib
import webbrowser
webbrowser.open(_urllib.request.pathname2url(output_file))
|
/**
* Implementation of heap restore operation.
*
* @param <K> The data type that the serializer serializes.
*/
public class HeapRestoreOperation<K> implements RestoreOperation<Void> {
private final Collection<KeyedStateHandle> restoreStateHandles;
private final StateSerializerProvider<K> keySerializerProvider;
private final ClassLoader userCodeClassLoader;
private final Map<String, StateTable<K, ?, ?>> registeredKVStates;
private final Map<String, HeapPriorityQueueSnapshotRestoreWrapper> registeredPQStates;
private final CloseableRegistry cancelStreamRegistry;
private final HeapPriorityQueueSetFactory priorityQueueSetFactory;
@Nonnull
private final KeyGroupRange keyGroupRange;
@Nonnegative
private final int numberOfKeyGroups;
private final HeapSnapshotStrategy<K> snapshotStrategy;
private final InternalKeyContext<K> keyContext;
HeapRestoreOperation(
@Nonnull Collection<KeyedStateHandle> restoreStateHandles,
StateSerializerProvider<K> keySerializerProvider,
ClassLoader userCodeClassLoader,
Map<String, StateTable<K, ?, ?>> registeredKVStates,
Map<String, HeapPriorityQueueSnapshotRestoreWrapper> registeredPQStates,
CloseableRegistry cancelStreamRegistry,
HeapPriorityQueueSetFactory priorityQueueSetFactory,
@Nonnull KeyGroupRange keyGroupRange,
int numberOfKeyGroups,
HeapSnapshotStrategy<K> snapshotStrategy,
InternalKeyContext<K> keyContext) {
this.restoreStateHandles = restoreStateHandles;
this.keySerializerProvider = keySerializerProvider;
this.userCodeClassLoader = userCodeClassLoader;
this.registeredKVStates = registeredKVStates;
this.registeredPQStates = registeredPQStates;
this.cancelStreamRegistry = cancelStreamRegistry;
this.priorityQueueSetFactory = priorityQueueSetFactory;
this.keyGroupRange = keyGroupRange;
this.numberOfKeyGroups = numberOfKeyGroups;
this.snapshotStrategy = snapshotStrategy;
this.keyContext = keyContext;
}
@Override
public Void restore() throws Exception {
registeredKVStates.clear();
registeredPQStates.clear();
return null;
}
} |
#![feature(globs, if_let)]
extern crate gopher;
use gopher::DirEntity;
use gopher::client::Gopher;
use std::io::IoResult;
fn pretty_print(item: &DirEntity) {
use gopher::EntityKind::{Known, Unknown};
use gopher::KnownEntityKind::*;
let kind = match item.kind {
Known(File) => "file",
Known(Dir) => "dir",
Known(CsoQuery) => "cso",
Known(Error) => "err",
Known(MacBinHex) => "binhex",
Known(DosBin) => "dosbin",
Known(Uuenc) => "uuenc",
Known(SearchQuery) => "search",
Known(Telnet) => "tel",
Known(Binary) => "bin",
Known(RedundantServer) => "server",
Known(Tn3270) => "tn3270",
Known(Gif) => "gif",
Known(Html) => "html",
Known(Info) => "info",
Known(Image) => "img",
Unknown(_) => "?"
};
println!("[{:>6}] {}", kind, item.display);
}
fn stuff() -> IoResult<()> {
let gopher = Gopher::new("freeshell.org", 70);
let menu = try!(gopher.root());
if let Some(dir) = menu.iter().find(|&x| x.is_dir()) {
println!("found dir, path = {}", String::from_utf8_lossy(&*dir.selector));
for x in try!(gopher.fetch_dir(&*dir.selector)).iter() {
pretty_print(x);
}
}
Ok(())
}
fn main() {
match stuff() {
Err(e) => {
let mut err = std::io::stdio::stderr();
let _ = writeln!(&mut err, "error: {}", e);
std::os::set_exit_status(1);
}
_ => {}
}
}
|
/**
* @author alexander karmanov on 2016-10-14.
*/
public class CommonBase extends RecyclerView.ViewHolder {
protected HostFragmentInterface hostFragment;
protected final ImageView imageView;
protected AsyncTask<FilepickerFile, Integer, Bitmap> imageLoadTask;
protected boolean loadingImage = false;
public CommonBase(View itemView) {
super(itemView);
this.imageView = (ImageView) itemView.findViewById(R.id.li_image);
}
public void setHostFragment(HostFragmentInterface hostFragment) {
this.hostFragment = hostFragment;
}
public void setUpView(FilepickerFile item) {}
public String getAdjustedTitle(String title) {
int len = title.length();
if (len > 17) {
String newTitle = title.substring(0, 10);
return newTitle.concat("...").concat(title.substring(len-5, len));
}
return title;
}
protected void loadImage(FilepickerFile item) {
imageView.setVisibility(View.INVISIBLE);
Bitmap map = hostFragment.getFilepicker().getFilepickerContext()
.getBitmapCache()
.getBitmapFromCache(item.getPath());
if (map != null) {
imageView.setImageBitmap(map);
imageView.setVisibility(View.VISIBLE);
}
else {
if (loadingImage) {
imageLoadTask.cancel(true);
}
imageLoadTask = new LoadImageTask().execute(item);
loadingImage = true;
}
}
protected boolean isImage(FilepickerFile item) {
String type = item.getType();
return FilepickerConfig.JPG.equals(type) || FilepickerConfig.PNG.equals(type);
}
private class LoadImageTask extends AsyncTask<FilepickerFile, Integer, Bitmap> {
@Override
protected Bitmap doInBackground(FilepickerFile... filepickerFiles) {
String path = filepickerFiles[0].getPath();
Bitmap bm = BitmapFactory.decodeFile(path);
Bitmap mutableBitmap = getResizedBitmap(
bm,
hostFragment.getFilepicker().getFilepickerContext().getConfig().getMaxImageSize()
);
ByteArrayOutputStream out = new ByteArrayOutputStream();
mutableBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap map = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
hostFragment.getFilepicker().getFilepickerContext().getBitmapCache().addBitmapToCache(path, map);
return map;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
loadingImage = false;
imageView.setVisibility(View.VISIBLE);
}
private Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
}
} |
import discord
from discord.ext import commands
import os
import asyncio
import SimpleJSON
Path = f"/DaeGal/Data"
class Docs(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(name="help", aliases=["도움말", "Help", "도움"])
async def help(self, ctx:commands.Context, category:str=None, command:str=None):
if category is not None: category = category.lower()
if command is not None: command = command.lower()
Docs = SimpleJSON.Read(Path=f"{Path}/Help/Help/Help.json")
if category is None:
Embed = discord.Embed(
title="카테고리 목록",
color=0xFFCC00
)
for Cat in Docs.keys():
if not bool(Docs[Cat]["info"]["commandList"]):
Embed.add_field(
name=f"`{Cat}`",
value="`비어있음`",
inline=True
)
else:
Embed.add_field(
name=f"`{Cat}`",
value=", ".join(Docs[Cat]["info"]["commandList"]),
inline=True
)
await ctx.send(embed=Embed)
elif command is None:
try:
Embed = discord.Embed(
title=f"명령어 목록: `{category}`",
color=0xFFCC00
)
for Com in Docs[category].keys():
Embed.add_field(
name=f"`{Com}`",
value=f"{Docs[category][Com]['description'].strip('ㅤ')}",
inline=False
)
await ctx.send(embed=Embed)
except KeyError:
Embed = discord.Embed(
title="오류",
description=f"`{category}` 카테고리를 찾지 못했습니다",
color=0xFF0000
)
await ctx.send(embed=Embed)
else:
command = command.strip("`")
try:
Help = Docs[category][command]
Embed = discord.Embed(
title=f"명령어: `{category}/{command}`",
description=Help["description"],
color=0xFFCC00
)
if Help["type"] == "info":
Embed.add_field(name="명령어 목록", value=", ".join(Help["commandList"]), inline=False)
if Help["type"] == "command":
if bool(Help["arguments"]):
Embed.add_field(name="인수 목록", value="\n".join(Help["arguments"]), inline=False)
else:
Embed.add_field(name="인수 목록", value="**없음**", inline=False)
Embed.add_field(name="사용", value=Help["use"], inline=False)
if bool(Help["aliases"]):
Embed.add_field(name="별칭", value=", ".join(Help["aliases"]), inline=True)
else:
Embed.add_field(name="별칭", value="**없음**", inline=True)
if Help["isDeprecated"]:
Embed.add_field(name="삭제/대체 예정?", value="예")
else:
Embed.add_field(name="삭제/대체 예정?", value="아니오")
Embed.add_field(name="도움말 보는 법", value="[대갈 위키](https://github.com/chae03yb/DaeGal/wiki/Help:-view)", inline=False)
await ctx.send(embed=Embed)
except KeyError:
Embed = discord.Embed(
title="오류",
description=f"`{command}` 명령어를 찾지 못했습니다",
color=0xFF0000
)
await ctx.send(embed=Embed)
@commands.command(name="memo", aliases=["메모"])
async def memo(self, ctx: commands.Context, TargetMemo=None):
if TargetMemo is None:
return await ctx.send("메모의 제목도 함께 써주십시오")
if "/" in TargetMemo or "." in TargetMemo:
return await ctx.send("허용되지 않은 문자가 있습니다")
SavePath = None
try:
SavePath = f"{Path}/Guild/{ctx.guild.id}/Memo"
except AttributeError:
SavePath = f"{Path}/User/{ctx.author.id}/Memo"
ErrorEmbed = discord.Embed(
title="오류",
description="시간 초과.",
color=0xFF0303
)
Embed = discord.Embed(
title="메모",
description="📝: 메모 쓰기\n" \
"🔍: 메모 보기\n" \
"🗑: 메모 삭제\n" \
"📁: 메모 검색"
)
msg = await ctx.send(embed=Embed)
for emoji in ["📝", "🔍", "🗑", "📁"]:
await msg.add_reaction(emoji)
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji)
try:
reaction, user = await self.client.wait_for("reaction_add", timeout=120, check=check)
except asyncio.TimeoutError:
await ctx.send(embed=ErrorEmbed)
await msg.delete(delay=3)
else:
reaction = str(reaction.emoji)
await msg.delete()
if reaction == "📝":
Memo = None
def MemoContent(message: discord.Message):
return message.author == ctx.message.author and message.content
try:
await ctx.send("메모의 내용을 입력해주십시오")
Memo = await self.client.wait_for("message", timeout=120, check=MemoContent)
except asyncio.TimeoutError:
await ctx.send(embed=ErrorEmbed)
await msg.delete(delay=3)
else:
try:
open(f"{SavePath}/{TargetMemo}", "w").close()
except FileNotFoundError:
try:
os.mkdir(SavePath)
except AttributeError:
os.mkdir(SavePath)
finally:
with open(f"{SavePath}/{TargetMemo}", "w") as File:
File.write(Memo.content)
await ctx.send("완료.")
elif reaction == "🔍":
try:
with open(f"{SavePath}/{TargetMemo}") as Memo:
Embed = discord.Embed(
title=f"메모: {TargetMemo}",
description=Memo.read()
)
await ctx.send(embed=Embed)
except FileNotFoundError:
await ctx.send("메모가 없습니다.")
elif reaction == "🗑":
try:
def deleteCheck(answer):
return answer.author == ctx.message.author and answer.content == "Y"
await ctx.send("메모 삭제를 원하신다면 Y를 입력해주십시오")
await self.client.wait_for("message", timeout=600, check=deleteCheck)
except asyncio.TimeoutError:
await ctx.send(embed=ErrorEmbed)
# return "시간 초과"
else:
try:
os.remove(f"{SavePath}/{TargetMemo}")
await ctx.send("삭제 완료")
except FileNotFoundError:
await ctx.send("메모가 없습니다.")
elif reaction == "📁":
searchResult = []
for result in os.listdir(SavePath):
if TargetMemo in result:
searchResult.append(f"`{result}`")
Embed = None
if not searchResult:
Embed = discord.Embed(
title=f"검색: {TargetMemo}",
description="검색 결과가 없습니다."
)
else:
Embed = discord.Embed(title=f"검색 결과: {TargetMemo}")
Embed.add_field(name="결과", value=f", ".join(searchResult))
await ctx.send(embed=Embed)
def setup(client):
client.add_cog(Docs(client)) |
<commit_msg>Add guard for multiple calls of Stop-method.
<commit_before>//Copyright 2016 lyobzik
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
package utils
import (
"sync"
)
type Stopper struct {
waitDone sync.WaitGroup
Stopping chan struct{}
}
func NewStopper() *Stopper {
return &Stopper{
waitDone: sync.WaitGroup{},
Stopping: make(chan struct{}, 1),
}
}
func (s *Stopper) Stop() {
close(s.Stopping)
}
func (s *Stopper) WaitDone() {
s.waitDone.Wait()
}
func (s *Stopper) Add() {
s.waitDone.Add(1)
}
func (s *Stopper) Done() {
s.waitDone.Done()
}
func (s *Stopper) Join() {
s.Stop()
s.WaitDone()
}
<commit_after>//Copyright 2016 lyobzik
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
package utils
import (
"sync"
"sync/atomic"
)
type Stopper struct {
closed int32
waitDone sync.WaitGroup
Stopping chan struct{}
}
func NewStopper() *Stopper {
return &Stopper{
closed: 0,
waitDone: sync.WaitGroup{},
Stopping: make(chan struct{}, 1),
}
}
func (s *Stopper) Stop() {
if atomic.CompareAndSwapInt32(&s.closed, 0, 1) {
close(s.Stopping)
}
}
func (s *Stopper) WaitDone() {
s.waitDone.Wait()
}
func (s *Stopper) Add() {
s.waitDone.Add(1)
}
func (s *Stopper) Done() {
s.waitDone.Done()
}
func (s *Stopper) Join() {
s.Stop()
s.WaitDone()
}
|
The Impact of Distressed Sales on Repeat-Transactions; House Price Indexes
The paper discusses the impact of distressed sales on recent estimates of house price changes in California. Using information from Notice of Default (NOD) filings in that state, the paper compares the usual FHFA HPI against an index computed after removing sales occurring after NOD filings. The paper also shows the effect that such sales are having on an index constructed using county recorder data (as opposed to the Fannie Mae/Freddie Mac-financed mortgages). Distressed sales are shown to have had small but significant impacts on both metrics, although the impact on the FHFA HPI is shown to be larger. Measured since-peak price declines for California become about 5 percentage points smaller if one removes distresed sales (i.e., post-NOD sales) from the FHFA HPI. Alternatively, measured since-peak declines are about 2 percentage points less severe when one removes distressed sales from a recorder-based index. |
/**
* @author Dave Syer
* @author Mahmoud Ben Hassine
*
*/
@Configuration
@PropertySource("classpath:/batch-hsql.properties")
public class DataSourceConfiguration {
@Autowired
private Environment environment;
@Autowired
private ResourceLoader resourceLoader;
@PostConstruct
protected void initialize() {
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScript(resourceLoader.getResource(environment.getProperty("batch.schema.script")));
populator.setContinueOnError(true);
DatabasePopulatorUtils.execute(populator, dataSource());
}
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(environment.getProperty("batch.jdbc.driver"));
dataSource.setUrl(environment.getProperty("batch.jdbc.url"));
dataSource.setUsername(environment.getProperty("batch.jdbc.user"));
dataSource.setPassword(environment.getProperty("batch.jdbc.password"));
return dataSource;
}
} |
Cardio-oncology: A Subspecialty in its Infancy
S everal years ago, after spending my professional life in cardiology, I was happy to join a private practice where I could focus my energies on managing patients with heart failure (HF). It was through this experience that I noticed a growing population of women previously treated for breast cancer who were now being seen for HF management. So began a journey to explore the relationship between cancer and cardiovascular disease. Since that time, I have spent many hours reading, writing, speaking with colleagues (a few of whom are contributors in this issue), and caring for oncology patients in the throes of or at risk for cardiotoxicity. Currently, from anthracyclines to checkpoint inhibitors, there is a cancer treatment rush filled with cardiotoxic possibilities, the likes of which we have not seen in many years.
S everal years ago, after spending my professional life in cardiology, I was happy to join a private practice where I could focus my energies on managing patients with heart failure (HF). It was through this experience that I noticed a growing population of women previously treated for breast cancer who were now being seen for HF management. So began a journey to explore the relationship between cancer and cardiovascular disease.
Since that time, I have spent many hours reading, writing, speaking with colleagues (a few of whom are contributors in this issue), and caring for oncology patients in the throes of or at risk for cardiotoxicity. Currently, from anthracyclines to checkpoint inhibitors, there is a cancer treatment rush filled with cardiotoxic possibilities, the likes of which we have not seen in many years.
WHAT'S IN A NAME?
So, what is cardio-oncology? Or is it onco-cardiology?
Shakespeare refers to a rose by any other name still smelling as sweet. Early on, what we called ourselves became an issue as cardiooncology programs became integrated into standard care.
Typically, the second part of the term indicates the person's position. So, if you are an oncologist who has an interest in cardiology, we would call you a cardio-oncologist. The same is true if you are a cardiologist. You would then be referred to as an onco-cardiologist. After much debate, the term "cardiooncology" has become widely accepted despite all the discussion on Latin origins. But, no matter which side of the fence, the terms describe the integration of cardiology and oncology.
Cardio-oncology is a subspecialty of cardiology. It was developed because of the oncology data indicating that newly developed drugs for cancer treatment were having unanticipated cardiac side effects. Cardio-oncology designs surveillance strategies and interventions to reduce cardiovascular (CV) risk and prevent cardiotoxicities.
GOAL
The goal of cardio-oncology is to provide CV safety as patients experience their cancer treatment. The history begins by assessing CV risk factors that may make the heart more sensitive to certain kinds of chemotherapy and/or radiation. Increased CV risk may be due to preexisting disease in combination with potentially cardiotoxic cancer treatment.
Dr. Coviello is associate professor at the Yale University School of Nursing and an adult nurse practitioner in cardio-oncology at the Smilow Cancer Hospital in New Haven, Connecticut.
The burden of CV risk increases in the context of chemotherapy due to weight gain, an increase in central obesity, high cholesterol, blood sugar, or blood pressure, but few studies have looked at pretreatment risk. Patients previously treated with chemotherapy and radiation therapy are at increased CV risk, with this risk higher than the actual risk of tumor recurrence (Albini et al., 2010;Tromp, Steggink, Van Veldhuisen, Gietema, & van der Meer, 2017). In long-term cancer survivors, a higher incidence of hypertension, dyslipidemia, acute coronary syndromes or myocardial infarction, and stroke have been reported.
EVIDENCE-BASED GUIDELINES
There are currently no evidence-based guidelines for the monitoring of cardiotoxicity during and after cancer therapies in adults. Several recommendations are available; however, there is variation on how often, by what means, or how long cardiac function should be monitored. The 2016 European Society for Medical Oncology Clinical Practice Guidelines (Zamorano et al., 2016) are available, but are mostly based on consensus and not randomized controlled trials (RCTs). They do provide a specific management guide. There are also pharmaceutical-based treatment "recipes," an example of which can be found on the website for trastuzumab (Genentech USA, Inc, 2018). Pharmaceutical-based surveillance and management recommendations are based on the RCT for the drug.
The 2013 American College of Cardiology Foundation (ACCF)/American Heart Association (AHA) Guidelines for HF are the only guidelines based on RCTs that address the cancer population (Yancy et al., 2013). According to the guidelines, the patients we currently see are Stage A and B patients. Stage A patients are those patients who will receive cancer treatment. They are the pretreatment group. In assessing for CV risks, the cancer and cancer treatment represent the very first risk factor before we even assess for the others. We consider cancer treatment to be in the same category as hypertension in patients in whom there is no structural heart disease. The 2013 ACCF/AHA Guidelines clearly recognize cancer patients as a specific risk group. Goals for therapy are aimed at preventing structural change as well as reducing risk.
FUTURE DIRECTIONS
Cardio-oncology is a relatively new field in this country. There are gaps in awareness, referral, and in RCTs to inform a standard of care. Since the competing cause of death in the growing number of cancer survivors is cardiovascular disease, cure is not enough. There needs to be more evidence to inform providers which predisposing CV risk factors warrant intervention and which cardio-diagnostic tests provide for the earliest recognition of myocyte dysfunction or death. Still to be answered is what the best treatment surveillance strategies and interventions to produce the greatest outcomes are.
It is rare to find a field so unexplored. That is what makes it both exciting and challenging. In this issue of JADPRO, we begin with a review of the current state of the science regarding the assessment and management of cardiotoxicities. The original research article addresses the symptom management gap in patients with cancer and HF. In a practice matters article, we describe the creation of a cardio-oncology clinic in a community hospital. Finally, a case study is presented with an opportunity for readers to infer the diagnosis. l
Disclosure
The author has no conflicts of interest to disclose. |
/* VC-2 11.1 - parse_parameters()
* The level dictates what the decoder should expect in terms of resolution
* and allows it to quickly reject whatever it can't support. Remember,
* this codec kinda targets cheapo FPGAs without much memory. Unfortunately
* it also limits us greatly in our choice of formats, hence the flag to disable
* strict_compliance */
static void encode_parse_params(VC2EncContext *s)
{
put_vc2_ue_uint(&s->pb, s->ver.major);
put_vc2_ue_uint(&s->pb, s->ver.minor);
put_vc2_ue_uint(&s->pb, s->profile);
put_vc2_ue_uint(&s->pb, s->level);
} |
<gh_stars>1-10
use parser::{DatalogParser, Rule};
#[test]
fn idents() {
parses_to! {
parser: DatalogParser,
input: "parent",
rule: Rule::ident,
tokens: [
ident(0, 6),
]
}
parses_to! {
parser: DatalogParser,
input: "1234",
rule: Rule::ident,
tokens: [
ident(0, 4),
]
}
}
#[test]
fn vars() {
parses_to! {
parser: DatalogParser,
input: "Foo",
rule: Rule::variable,
tokens: [
variable(0, 3),
]
}
}
#[test]
fn strings() {
parses_to! {
parser: DatalogParser,
input: r#""""#,
rule: Rule::string,
tokens: [
string(0, 2),
]
}
parses_to! {
parser: DatalogParser,
input: r#""-:-""#,
rule: Rule::string,
tokens: [
string(0, 5, [
raw_ch(1, 2),
raw_ch(2, 3),
raw_ch(3, 4),
]),
]
}
parses_to! {
parser: DatalogParser,
input: r#""first\nsecond""#,
rule: Rule::string,
tokens: [
string(0, 15, [
raw_ch(1, 2),
raw_ch(2, 3),
raw_ch(3, 4),
raw_ch(4, 5),
raw_ch(5, 6),
esc_ch(6, 8, [
predef_esc(7, 8)
]),
raw_ch(8, 9),
raw_ch(9, 10),
raw_ch(10, 11),
raw_ch(11, 12),
raw_ch(12, 13),
raw_ch(13, 14),
]),
]
}
}
#[test]
fn literals() {
parses_to! {
parser: DatalogParser,
input: "zero-arity-literal",
rule: Rule::literal,
tokens: [
literal(0, 18, [
name(0, 18, [
ident(0, 18),
]),
]),
]
}
parses_to! {
parser: DatalogParser,
input: "also-zero-arity()",
rule: Rule::literal,
tokens: [
literal(0, 17, [
name(0, 15, [
ident(0, 15),
]),
]),
]
}
parses_to! {
parser: DatalogParser,
input: "1(arg)",
rule: Rule::literal,
tokens: [
literal(0, 6, [
name(0, 1, [
ident(0, 1),
]),
term_list(2, 5, [
term(2, 5, [
name(2, 5, [
ident(2, 5),
]),
]),
]),
]),
]
}
parses_to! {
parser: DatalogParser,
input: "parent(john, douglas)",
rule: Rule::literal,
tokens: [
literal(0, 21, [
name(0, 6, [
ident(0, 6),
]),
term_list(7, 20, [
term(7, 11, [
name(7, 11, [
ident(7, 11),
]),
]),
term(13, 20, [
name(13, 20, [
ident(13, 20),
]),
]),
]),
]),
]
}
parses_to! {
parser: DatalogParser,
input: r#"aBcD(-0, "\n\u03bb")"#,
rule: Rule::literal,
tokens: [
literal(0, 20, [
name(0, 4, [
ident(0, 4),
]),
term_list(5, 19, [
term(5, 7, [
name(5, 7, [
ident(5, 7),
]),
]),
term(9, 19, [
name(9, 19, [
string(9, 19, [
esc_ch(10, 12, [
predef_esc(11, 12)
]),
esc_ch(12, 18, [
uni4_esc(13, 18, [
hex_digit(14, 15),
hex_digit(15, 16),
hex_digit(16, 17),
hex_digit(17, 18),
]),
]),
]),
]),
]),
]),
]),
]
}
}
|
/**
* Implements the mapping between {@link Class} and {@link TypeName} documented in {@link DefaultTypeName}.
*
* @author Martin Desruisseaux (Geomatys)
* @since 0.5
* @version 0.5
* @module
*/
final class TypeNames {
/**
* The mapping between {@link TypeName} and {@link Class} as documented in {@link DefaultTypeName}.
* When searching for a name from a class, the values will be tested in iteration order.
*
* <p>{@link #toTypeName(NameFactory, Class)} will <strong>not</strong> iterate over all entries.
* Numbers and character strings are handled in a special way, so we do not need to iterate on them.
* We arbitrarily use {@code Boolean.class} as the sentinel value for detecting when to stop iteration.</p>
*
* <p>This map shall not be modified after construction.</p>
*/
private static final Map<String,Class<?>> MAPPING = new LinkedHashMap<String,Class<?>>(16);
static {
final Map<String,Class<?>> m = MAPPING;
m.put("URI", URI.class);
m.put("DateTime", Date.class);
m.put("PT_Locale", Locale.class);
m.put("Boolean", Boolean.class); // Used as a sentinel value for stopping iteration.
// Entries below this point are handled in a special way.
m.put("FreeText", InternationalString.class);
m.put("CharacterString", String.class);
m.put("Real", Double.class);
m.put("Decimal", Double.class);
m.put("Integer", Integer.class);
};
/**
* The "OGC" namespace.
*/
private final NameSpace ogcNS;
/**
* The "class" namespace.
*/
private final NameSpace classNS;
/**
* Creates a new factory of type names.
*/
TypeNames(final NameFactory factory) {
ogcNS = factory.createNameSpace(factory.createLocalName(null, Constants.OGC), null);
classNS = factory.createNameSpace(factory.createLocalName(null, "class"), null);
}
/**
* Infers the type name from the given class.
*
* @param factory The same factory than the one given to the constructor.
* @param valueClass The value class for which to get a type name.
* @return A type name for the given class (never {@code null}).
*/
final TypeName toTypeName(final NameFactory factory, final Class<?> valueClass) {
String name;
NameSpace ns = ogcNS;
if (CharSequence.class.isAssignableFrom(valueClass)) {
name = InternationalString.class.isAssignableFrom(valueClass) ? "FreeText" : "CharacterString";
} else if (Number.class.isAssignableFrom(valueClass)) {
name = Numbers.isInteger(valueClass) ? "Integer" : "Real";
} else {
/*
* Iterate over the special cases, excluding the numbers and character sequences
* since they were verified in the above statements.
*/
final Iterator<Map.Entry<String,Class<?>>> it = MAPPING.entrySet().iterator();
Class<?> base;
do {
final Map.Entry<String,Class<?>> entry = it.next();
base = entry.getValue();
if (base.isAssignableFrom(valueClass)) {
name = entry.getKey();
return factory.createTypeName(ns, name);
}
} while (base != Boolean.class); // See MAPPING javadoc for the role of Boolean as a sentinel value.
/*
* Found no special case. Checks for the UML annotation, to be also formatted in the "OGC:" namespace.
* If no UML identifier is found, then we will format the Java class in the "class:" namespace. We use
* Class.getName() - not Class.getCanonicalName() - because we want a name readable by Class.forName(…).
*/
name = Types.getStandardName(valueClass);
if (name == null) {
ns = classNS;
name = valueClass.getName(); // See above comment.
}
}
/*
* Now create the name and remember the 'valueClass' for that name if the implementation allows that.
*/
final TypeName t = factory.createTypeName(ns, name);
if (t instanceof DefaultTypeName) {
((DefaultTypeName) t).setValueClass(ns, name, valueClass);
}
return t;
}
/**
* Returns the class for a {@code TypeName} made of the given scope and name.
* This method is the converse of {@link #toTypeName(NameFactory, Class)}.
* This method returns 3 kind of values:
*
* <ul>
* <li>{@code Void.TYPE} if the namespace or the name is unrecognized, without considering that as an error.
* This is a sentinel value expected by {@link DefaultTypeName#toClass()} for such case.</li>
* <li>{@code null} if {@code namespace} is recognized, but not the {@code name}.
* This will be considered as an error by {@link DefaultTypeName#toClass()}.</li>
* <li>Otherwise the class for the given name.</li>
* </ul>
*
* @param namespace The namespace, case-insensitive. Can be any value, but this method recognizes
* only {@code "OGC"}, {@code "class"} and {@code null}. Other namespaces will be ignored.
* @param name The name, case-sensitive.
* @return The class, or {@code Void.TYPE} if the given namespace is not recognized,
* or {@code null} if the namespace is recognized but not the name.
* @throws ClassNotFoundException if {@code namespace} is {@code "class"} but {@code name} is not
* the name of a reachable class.
*/
static Class<?> toClass(final String namespace, final String name) throws ClassNotFoundException {
Class<?> c;
if (namespace == null || namespace.equalsIgnoreCase(Constants.OGC)) {
c = MAPPING.get(name);
if (c == null) {
c = Types.forStandardName(name);
if (c == null && namespace == null) {
c = Void.TYPE; // Unknown name not considered an error if not in "OGC" namespace.
}
}
} else if (namespace.equalsIgnoreCase("class")) {
c = Class.forName(name);
} else {
c = Void.TYPE; // Not an "OGC" or "class" namespace.
}
return c;
}
/**
* Ensures that the given class is not {@link Void#TYPE}.
* This is a helper method for callers of {@link #toTypeName(NameFactory, Class)}.
*/
static boolean isValid(final Class<?> valueClass) {
if (valueClass == Void.TYPE) {
throw new IllegalArgumentException(Errors.format(Errors.Keys.IllegalArgumentValue_2, "valueClass", "void"));
}
return (valueClass != null);
}
/**
* Null-safe getter for the namespace argument to be given to {@link #toClass(String, String)}.
*/
static String namespace(final NameSpace ns) {
if (ns != null && !ns.isGlobal()) {
final GenericName name = ns.name();
if (name != null) {
return name.toString();
}
}
return null;
}
/**
* Formats the error message for an unknown type.
* This is a helper method for callers of {@link #toClass(String, String)}.
*/
static String unknown(final GenericName name) {
return Errors.format(Errors.Keys.UnknownType_1, name.toFullyQualifiedName());
}
} |
def goto_next_instruction(self):
self._get_current_list().goto_next_instruction()
current_process = self.get_process_of_current_list()
if current_process is not None and current_process.follower is not None:
move_to_next_instruction = False
while len(self.stack) > 0 and self._get_current_list().finished():
self.stack.pop()
move_to_next_instruction = True
new_current_process = self.get_process_of_current_list()
if new_current_process != current_process:
instructions_list = current_process.follower.instructions_list
if len(instructions_list) > 0:
self.add_instructions_list(instructions_list, current_process.follower)
move_to_next_instruction = False
break
if not self.finished() and move_to_next_instruction:
if not isinstance(self._get_current_list().get_current_instruction(), WhileInstruction):
self._get_current_list().goto_next_instruction()
while not self.finished() and self._get_current_list().finished():
self.stack.pop()
if not self.finished():
if not isinstance(self._get_current_list().get_current_instruction(), WhileInstruction):
self._get_current_list().goto_next_instruction()
self.host.check_if_finished() |
// Returns true when it is running on the x64 system.
inline bool IsX64() {
#ifdef _AMD64_
return true;
#else
return false;
#endif
} |
/**
* sc,scn,SC,SCN Sets the colour to use for stroking or non-stroking operations.
* @param operator the operator that is being executed.
* @param arguments list of operands
* @throws IOException if the color space cannot be read
*/
public void process(PDFOperator operator, List<COSBase> arguments) throws IOException
{
COSArray array = new COSArray();
array.addAll(arguments);
setColor(new PDColor(array));
} |
<reponame>CIDARLAB/stl_metrics
from stlLexer import stlLexer
from stlParser import stlParser
from stl import STLAbstractSyntaxTreeExtractor
from stl import Operation, RelOperation, STLFormula, Trace |
#include<stdio.h>
#include<stdlib.h>
int cmpfunc(const void * a, const void*b)
{
return (* (long long int *) a - * (long long int *) b);
}
int main()
{
long long int a, b, c, d;
scanf("%lld %lld %lld %lld",&a, &b, &c, &d);
long long int num[5];
num[0]=a, num[1]=b, num[2]=c, num[3]=d;
qsort(num, 4, sizeof(long long int), cmpfunc);
printf("%lld %lld %lld\n", num[3]-num[0], num[3]-num[1],num[3]- num[2]);
return 0;
}
|
/**
* @author Ricky Fung
*/
public abstract class Constant {
public static final String POOL_NAME_KEY = "name";
public static final String CORE_POOL_SIZE_KEY = "coreSize";
public static final String MAXIMUM_POOL_SIZE_KEY = "maximumSize";
public static final String KEEP_ALIVE_TIME_KEY = "keepAliveTime";
public static final String QUEUE_TYPE_KEY = "queueType";
public static final String QUEUE_CAPACITY_KEY = "queueCapacity";
public static final String REJECTED_TYPE_KEY = "rejectedType";
//============
public static final String DEFAULT_POOL_NAME = "dynamic";
public static final String DEFAULT_QUEUE_TYPE = "resizable";
public static final int DEFAULT_QUEUE_CAPACITY = 64;
public static final String DEFAULT_REJECTED_TYPE = RejectedExecutionType.ABORT.name();
} |
/**
* Created by nookio on 15/12/11.
*/
public abstract class BaseService<E,T> {
protected abstract E getInfo(String outTradeNo);
protected abstract E updateInfo(E e, String tradeNo, String tradeStatus, Date payedAt, BigDecimal totalFee);
protected abstract E createNewInfo(Integer payerId, Short paymentType, BigDecimal money, String tradeStatus, T ... all);
} |
During Fan Fest at the Amalie on Saturday morning, Tampa Bay Lightning owner Jeff Vinik participated in a question and answer session with fans inside the arena. Some of his statements should be reassuring to fans (insert loud and proud statement directed at Steven Stamkos here) while another should illicit confidence in a competitive variety. From TBO:
"Frankly we were losing a lot of money when we first bought the team, and now we are losing a little bit of money,'' Vinik said. "It's been such a fun experience over the past five years. Our mission to try and become the Green Bay Packers of the NHL, to try and become world class, we are gaining on both of those. But we still have a ways to go, and when we get there I will raise the targets because you can't stop chasing excellence.''
Vinik's quote shouldn't be taken just for the direct comparison to the Green Bay Packers football team. If you're thinking sports, and of course you are because you're reading a hockey blog, you're thinking of how the Packers are a small market club but routinely competitive and have the Super Bowl rings to prove how the franchise is legendary. Hell, former Packers head coach Vince Lombardi is who the NFL's championship trophy is named for.
But it's not just competition that the Packers are known for. They're known for being very much part of the community in Green Bay, Wisconsin. Hell, they are the community in Green Bay. The fans actually own the team, the players are known for being part of the community.
But the "Green Bay Packers of the NHL" is best described in detail by the man himself. Mr. Vinik's comment wasn't just an improvisational remark for a hungry fan contingent on hand on Saturday. The truth is Vinik has been invoking the analogy for almost two years (at least). In a remark, republished in Tampa Bay Business Journal, Jeff Vinik told Street & Smith's Sports Business Journal the following:
Our not immodest goal is to be the Green Bay Packers of the NHL. Will we get there? I don't know. Will it take 60 years? I don't know. But that's the direction we're trying to get to. The people of Green Bay love their team and everything it stands for, and we want our fans to believe in us and what we're doing in the community.
In this regard, I don't think the goal of building a new baseball stadium for the Tampa Bay Rays, or buying the Rays franchise for that matter (as I hear so often from locals) is really the best objective for Vinik and his team. Lightning fans, and Rays fans and Buccaneers fans, are so used to local sports owners being involved in their little niche - sports - locally and not much through general civic involvement in a public way. Vinik's intention is clearly broader than sports (regarding his land buys and recent business disclosures by franchise CEO Tod Leiweke). He wants to have success with his club - and wants us to embrace it as our club, as our team, as our sport.
The "Green Bay Packers of the NHL" remark translates into more than the franchises determination to be a talking point in the media and competitive on the field of play. The ambition of Jeff Vinik and the Lightning organization at current is to be the identity of Tampa Bay, and one that is embraced. |
from rest_framework.views import APIView
from .models import Attendance
class AttendanceView(APIView):
"""Note that attendance cannot be called later than 20 mins after the start of class """
def post(self, request, format=None):
#get the start time of the course (from the point the staff presses a button for the start) and check with the current time
return Attendance.objects.create(user=request.user.id, status=request.POST.get('status'), course=request.POST.get('course'))
|
/**
* Finds a data value for a specific search element. The format in the .nam file is:
* (key)-(element):
* with the key being a number and the element being the one searched for. The entire
* string is put in as the element parameter.
* @param element
*/
public void findData(String element) {
while (scanner.hasNextLine()) {
if (scanner.nextLine().equalsIgnoreCase(element + ":")) {
data = scanner.nextLine();
foundElement = true;
break;
} else {
foundElement = false;
}
}
} |
2018 recruit Josh Roberts verbally committed to St. John’s on Friday, he told Scout.
“It's a great fit for me,” Roberts said when asked about his decision. “I really like coach [Chris] Mullin and he will help me take my game to higher level.”
Roberts’ coach for the Southern Stampede – Cory Underwood – echoed his thoughts.
“If guys like Shamorie [Ponds] stick around, Josh’s job is pretty easy,” he said. “He’ll protect the rim, rebound, block shots sand finish off plays around the basket, which he’s capable of doing.”
Roberts visited St. John's officially last weekend.
"When I went on the visit they made me feel at home," Roberts said.
Robert picked St. John’s over significant interest from UCF, VCU, Clemson, Auburn, Georgia, New Mexico, South Carolina, Wichita State, UMass, Florida Gulf Coast and a host of others.
Through 16 on the EYBL circuit this spring and summer, Roberts, a 6-foot-8, 200-pounds power forward, averaged 6.1 points and 6.6 rebounds a game.
“I think they are very excited about his upside and his athletic ability,” Underwood said. “Josh really just started playing basketball a few years ago.”
“We pretty much threw a kid that just started playing into the fire in the EYBL,” he added. “When I think of Josh, I think of Kenneth Faried, but he surprisingly has very nice touch from the short baseline and elbow areas.”
Roberts, a three-star recruit, is St. John’s first pledge in the 2018 recruiting class. |
def mvn_log_pdf(x: np.ndarray, mu: np.ndarray, sigma_inv: np.ndarray, log_det: float) -> np.ndarray:
n = len(mu)
o = x - mu
l = ([email protected]).T
maha = np.sum(o*l, axis=-1)
ld = -0.5*(n*np.log(2*np.pi) + log_det + maha)
return ld |
def trim_polytope_set(
trimmable_polytopes: List[Polytope],
fixed_polytopes: Optional[List[Polytope]] = None
) -> List[Polytope]:
fixed_polytope = Polytope(convex_subpolytopes=[])
if fixed_polytopes is not None:
for polytope in fixed_polytopes:
fixed_polytope = fixed_polytope.union(polytope)
trimmable_polytopes = sorted(
trimmable_polytopes,
key=lambda x: x.volume,
reverse=True,
)
for index in range(len(trimmable_polytopes) - 1, -1, -1):
this_polytope = trimmable_polytopes[index]
other_polytope = fixed_polytope
for subindex, polytope in enumerate(trimmable_polytopes):
if subindex == index:
continue
other_polytope = other_polytope.union(polytope)
if other_polytope.contains(this_polytope):
del trimmable_polytopes[index]
return trimmable_polytopes |
/** Fire the change event to repaint the given block of text.
* @deprecated Please use <code>JTextComponent.getUI().damageRange()</code> instead.
*/
public void repaintBlock(int startOffset, int endOffset) {
BaseDocumentEvent evt = getDocumentEvent(startOffset,
endOffset - startOffset, DocumentEvent.EventType.CHANGE, null);
fireChangedUpdate(evt);
} |
A high powered and high-tech tool is helping investigators solve serious crimes in Manitoba.
The Leica Scanstation is a forensic laser scanner able to pick up the tiniest of details and recreate collisions and crime scenes in 3D.
RCMP have eight scanners. The Winnipeg Police Service has one. Both agencies started using them two years ago.
The technology gives police a bird's eye or panoramic view of a crime long after the scene has been cleared.
"You can actually take an investigator, a jury or any person for that matter, into the actual scene itself and walk them through,” said Joel Salinas, a retired California police officer and scanner instructor who trains police agencies around the world on the technology.
The images the scanner picks up allow police to place new kinds of digital markers into the scene. Investigators can click through rooms or go back and look at a bullet hole up close.
It measures distances with an accuracy of up to three millimeters.
“It's much tighter and more precise than any other conventional method that we have ever used,” said Sgt. Brian Harder, a forensic identification specialist investigator with Manitoba RCMP.
Winnipeg police constable George Kullman showed CTV News how it works using a mock t-bone crash, where it's believed an impaired driver in a silver car slammed into a family in a black truck.
Kullman sets up the scanner on a tripod and moves it around the collision every eight minutes to capture different angles.
"I thought it was pretty cool,” said Kullman, who is Winnipeg police’s resident expert on the technology and a collision analyst with the traffic division. “It will scan a scene 360 degrees around, 390 degrees overhead, and at each station it takes 274 images."
When Kullman brings the data back to the station for analysis, he measures skid marks and discovers the silver car had been moving at 80 kilometers an hour.
While police originally purchased the scanner to help gather evidence at traffic collisions, it’s being used more and more at scenes where violent crimes have taken place.
Winnipeg police and RCMP have used the technology in more than 130 investigations across the province, including possible hit and runs, officer-involved shootings and homicides.
Crime scene investigations require meticulous evidence gathering, and can take days of work.
The scanners haven't stopped police from taking photographs and measurements the more traditional way, but it can replicate a scene within a matter of hours, and fact check witness accounts.
Manitoba Justice says evidence produced from a scanner in one case was presented in court and deemed admissible.
"It certainly does and bolster our case in the credibility that we can present to the courts," said Sgt. Brian Harder, RCMP.
“It could be a game changer,” said Const. George Kullman, Winnipeg Police Service. “I can see a time where it will be used for every homicide certainly, and all of our serious and fatal collisions, and … serious assaults.”
It costs about $200,000 to buy and operate the scanners and train officers.
Winnipeg police purchased its scanner with money from the criminal property forfeiture fund, money collected from auctions of items seized through criminal investigations.
Manitoba RCMP said other police agencies in Canada have reached out for assistance because it has the high-tech scanners. |
/**
* A Grid that contains mergable cells
*/
public class MergableGridWidget extends BaseGridWidget<MergableGridData, IMergableGridRenderer> {
private final MergableGridWidgetMouseClickHandler mouseClickHandler;
private final MergableGridWidgetMouseDoubleClickHandler mouseDoubleClickHandler;
public MergableGridWidget( final MergableGridData model,
final ISelectionManager selectionManager,
final IMergableGridRenderer renderer ) {
super( model,
selectionManager,
renderer );
//Click handlers
mouseClickHandler = new MergableGridWidgetMouseClickHandler( this,
selectionManager,
renderer );
mouseDoubleClickHandler = new MergableGridWidgetMouseDoubleClickHandler( this,
selectionManager,
renderer );
addNodeMouseClickHandler( mouseClickHandler );
addNodeMouseDoubleClickHandler( mouseDoubleClickHandler );
}
public boolean onGroupingToggle( final double cellX,
final double cellY,
final double columnWidth,
final double rowHeight ) {
return renderer.onGroupingToggle( cellX,
cellY,
columnWidth,
rowHeight );
}
@Override
public void onNodeMouseClick( final NodeMouseClickEvent event ) {
mouseClickHandler.onNodeMouseClick( event );
}
} |
<gh_stars>0
# This file is a part of the powerscan_scenario project
#
# Copyright (C) 2018 <NAME> <<EMAIL>>
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file,You can
# obtain one at http://mozilla.org/MPL/2.0/.
from unittest import TestCase
from ..db import DBManager
from ..engine import Engine, Process
from ..scannerbase import TestingScannerBase
from .common import drop_and_create_db_if_exist
from ..common import ACTION_MENU, ACTION_SCAN, ACTION_STOP, BUTTON_MIDDLE
from .scenario import OneScenario
from time import sleep
import threading
class TestEngine(TestCase):
def test_run_and_close(self):
url = 'postgresql+psycopg2:///powerscan_scenario'
config = {'sqlalchemy_url': url, 'allow_dev': True}
scenario = OneScenario(config)
scenarios = {'test': scenario}
drop_and_create_db_if_exist(url)
dbmanager = DBManager(configuration=config, scenarios=scenarios)
base = TestingScannerBase()
engine = Engine(config, base, dbmanager)
thread = threading.Thread(target=engine.start)
thread.start()
sleep(0.1)
engine.stop()
thread.join()
def test_one_scenario(self):
url = 'postgresql+psycopg2:///powerscan_scenario'
scanner_code = 1000
config = {'sqlalchemy_url': url, 'allow_dev': True}
scenario = OneScenario(config)
scenarios = {'test': scenario}
drop_and_create_db_if_exist(url)
dbmanager = DBManager(
configuration=config, scenarios=scenarios,
isolation_level="READ UNCOMMITTED") # only unittest
session = dbmanager.session
base = TestingScannerBase()
engine = Engine(config, base, dbmanager)
thread = threading.Thread(target=engine.start)
thread.start()
base.sent_from_base(scanner_code, '')
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_MENU,
'buttons': {},
'counter': 0,
'display': ['One Scenario', Process._reload],
'sound': 'goodread',
})
base.sent_from_base(scanner_code, BUTTON_MIDDLE)
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_SCAN,
'buttons': {},
'counter': 0,
'display': ['Scan a product'],
'sound': 'goodread',
})
sleep(0.01)
main_query = session.query(scenario.TestProduct)
query_p1 = main_query.filter_by(scan='product1')
query_p2 = main_query.filter_by(scan='product2')
query_p3 = main_query.filter_by(scan='product3')
self.assertEqual(query_p1.count(), 0)
self.assertEqual(query_p2.count(), 0)
self.assertEqual(query_p3.count(), 0)
base.sent_from_base(scanner_code, 'product1')
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_SCAN,
'buttons': {},
'counter': 0,
'display': ['Scan a product'],
'sound': 'goodread',
})
sleep(0.01)
self.assertEqual(query_p1.count(), 1)
self.assertEqual(query_p1.one().qty, 1)
self.assertEqual(query_p2.count(), 0)
self.assertEqual(query_p3.count(), 0)
base.sent_from_base(scanner_code, 'product2')
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_SCAN,
'buttons': {},
'counter': 0,
'display': ['Scan a product'],
'sound': 'goodread',
})
sleep(0.01)
self.assertEqual(query_p1.count(), 1)
self.assertEqual(query_p1.one().qty, 1)
self.assertEqual(query_p2.count(), 1)
self.assertEqual(query_p2.one().qty, 1)
self.assertEqual(query_p3.count(), 0)
base.sent_from_base(scanner_code, 'product3')
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_SCAN,
'buttons': {},
'counter': 0,
'display': ['Scan a product'],
'sound': 'goodread',
})
sleep(0.01)
self.assertEqual(query_p1.count(), 1)
self.assertEqual(query_p1.one().qty, 1)
self.assertEqual(query_p2.count(), 1)
self.assertEqual(query_p2.one().qty, 1)
self.assertEqual(query_p3.count(), 1)
self.assertEqual(query_p3.one().qty, 1)
base.sent_from_base(scanner_code, 'product2')
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_SCAN,
'buttons': {},
'counter': 0,
'display': ['Scan a product'],
'sound': 'goodread',
})
sleep(0.01)
self.assertEqual(query_p1.count(), 1)
self.assertEqual(query_p1.one().qty, 1)
self.assertEqual(query_p2.count(), 1)
self.assertEqual(query_p2.one().qty, 2)
self.assertEqual(query_p3.count(), 1)
self.assertEqual(query_p3.one().qty, 1)
base.sent_from_base(scanner_code, 'product3')
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_SCAN,
'buttons': {},
'counter': 0,
'display': ['Scan a product'],
'sound': 'goodread',
})
sleep(0.01)
self.assertEqual(query_p1.count(), 1)
self.assertEqual(query_p1.one().qty, 1)
self.assertEqual(query_p2.count(), 1)
self.assertEqual(query_p2.one().qty, 2)
self.assertEqual(query_p3.count(), 1)
self.assertEqual(query_p3.one().qty, 2)
base.sent_from_base(scanner_code, 'product3')
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_SCAN,
'buttons': {},
'counter': 0,
'display': ['Scan a product'],
'sound': 'goodread',
})
sleep(0.01)
self.assertEqual(query_p1.count(), 1)
self.assertEqual(query_p1.one().qty, 1)
self.assertEqual(query_p2.count(), 1)
self.assertEqual(query_p2.one().qty, 2)
self.assertEqual(query_p3.count(), 1)
self.assertEqual(query_p3.one().qty, 3)
self.assertEqual(main_query.count(), 3)
base.sent_from_base(scanner_code, scenario.scan_stop)
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_STOP,
'buttons': {},
'counter': 0,
'display': [],
'sound': 'goodread',
})
# TODO test release job
base.sent_from_base(scanner_code, BUTTON_MIDDLE)
self.assertEqual(
base.sent_to(scanner_code),
{
'action_type': ACTION_MENU,
'buttons': {},
'counter': 0,
'display': ['One Scenario', Process._reload],
'sound': 'goodread',
})
engine.stop()
thread.join()
dbmanager.close()
|
package Nextcorev1
//ShardHolder ...
type ShardHolder interface {
Hold(val bool)
}
//ShardDisposer ...
type ShardDisposer interface {
Dispose(val bool)
}
//ShardHolderAndDisposer ...
type ShardHolderAndDisposer interface {
ShardHolder
ShardDisposer
}
|
Question: What does the following code display?
import java.awt.Color; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; public class Demo { public static void main(String[] args) { JFrame frame = new JFrame(); JLayeredPane container = new JLayeredPane(); frame.setContentPane(container); JPanel bottom = new JPanel(); bottom.setBounds(0, 0, 400, 200); bottom.setBackground(Color.WHITE); container.add(bottom); // default level is 0 JLabel intLabel = new JLabel("I'm an int"); intLabel.setBounds(0, 10, 400, 30); int layer = 10; container.add(intLabel, layer); JLabel integerLabel = new JLabel("I'm an Integer"); integerLabel.setBounds(0, 50, 400, 30); container.add(integerLabel, new Integer(10)); JLabel literalLabel = new JLabel("I'm a literal"); literalLabel.setBounds(0, 100, 400, 30); container.add(literalLabel, 10); JLabel longLabel = new JLabel("I'm a long"); longLabel.setBounds(0, 150, 400, 30); container.add(longLabel, new Long(10)); frame.setSize(400, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Answer
Explanation
If you open docs for JLayeredPane, you can see the following code snippets:
layeredPane.add(child, new Integer(10));
layeredPaneParent.setLayer(child, 10);
You can see Integer there and literal 10 here. Subconsciously, you think: who cares, 10 is the same thing as new Integer(10) because Java has autoboxing, right? WRONG!
The only right way to interact with layeredPane.add is an Integer that you box yourself. Let’s take a peek at its source code…
protected void addImpl(Component comp, Object constraints, int index) { int layer = DEFAULT_LAYER.intValue(); int pos; if(constraints instanceof Integer) { // A-ha! layer = ((Integer)constraints).intValue(); setLayer(comp, layer); } else layer = getLayer(comp); pos = insertIndexForLayer(layer, index); super.addImpl(comp, constraints, pos); comp.validate(); comp.repaint(); validateOptimizedDrawing(); }
Ironically, even though it uses int internally, it wouldn’t recognize it as a parameter.
Conclusion
Autoboxing works, except for when it doesn’t. Be defensive with APIs (even core Java) and when something is wrong do try all those ideas that seem obviously crazy at first. When writing your own API that uses type identification, remember that int and Integer are completely different beasts and both need to be included.
This example is from Swing, but it can happen anywhere. I’ve tripped on this issue before when I was implementing a CRUD framework or renderers, but did not expect it in core library.
Update
As frimble pointed out at reddit, there is one more reason why it would never work. In addition to add(Component comp, Object constraints) , Container also has add(Component comp, int index) .
Having two overloaded versions of a method, one of them accepting Integer and another for int , when both do completely different things, is even worse than what I criticized in the first place. |
def _api_get_json(self, url):
try:
response = urllib2.urlopen(url)
data = json.loads(response.read())
except urllib2.URLError, e:
self.log.error("Could not communicate with Master API becasue: %s" % e)
print "Could not communicate with Master API because %s" % e
sys.exit(1)
try:
out_data = data['data']
except Exception:
out_data = None
if data['result'] != 'success':
self.log.info("Could not retrieve data for URL=%s" % url)
return {}
if out_data:
return out_data
else:
return {} |
Will Google’s new Calico venture and Obamacare work hand-in hand? (AP Photo/Mark Lennihan)
Google unveiled its new anti-aging initiative, Calico, to much fanfare last month. The exclusive story of “Can Google Solve Death?” was splashed across the cover of TIME magazine while tech bloggers scrambled to figure out the true meaning of Google’s “strange or speculative” new venture. To hear Google execs tell the story, Calico aims at nothing less than extending human life spans by 100 years or more. Given enough time, Google might even defy the aging process and make us immortal.
And, the brilliance of all this is that President Obama’s Affordable Care Act may end up making this possible within our lifetime.
Of course, the Google guys – Larry Page and Sergey Brin – won’t talk about Obamacare and the potential role of government in making Calico a success, and you won’t find any mention of the ACA in the Google press release. Perhaps Google already saw how its earlier healthcare initiative, Google Health, encountered government obstacles along the way. Instead, Page and Brin prefer to focus on the Silicon Valley narrative – Calico is a classic story of outsider tech entrepreneurs attempting nothing less than upending the medical establishment. To Page and Brin, Calico is just another “moon shot” project along the lines of Google Glass or the Google driverless car – a pure tech-fueled initiative of Silicon Valley private sector know-how, and not a massive government project.
But consider how Obamacare could give a boost to Calico.
Right now, the people most likely to benefit from Obamacare are the people without any health insurance whatsoever – literally, tens of millions of people who live in daily fear of injuring themselves or dealing with a health problem that’s not life-threatening, but nevertheless, life-shortening. They’re making a rational economic choice by not being insured — healthcare is just too expensive now.
However, with the new health care exchanges and insurance subsidies promised by Obamacare, millions of new people could enter “the pool.” And that means they will start doing all the small things once beyond their reach — going in for annual exams, seeing their doctors more often, and exploring new government-funded programs to help them lead a healthy lifestyle.
That, however, is just from a healthcare perspective. From a Big Data perspective, millions of Americans will now be contributing their data to science.
And Big Data is in the sweet spot of Calico. It now appears that Google Calico is meant to be some kind of Big Data venture inspired in part by 23andMe, co-founded by Anne Wojcicki (the wife of Sergey Brin). One goal of 23andMe was to make it possible to create a massive genomic database and thereby understand the permutations and mutations that happen to the human genome during the aging process. Something remarkable happens when tens of millions of people are added to the system and these people are given incentives to share and explore their health information as part of a Big Data, genome-inspired project.
Yes, that’s right. Google reduces immortality to a game of data mining and increasingly clever algorithms. The search for the most relevant website becomes a transcendental search for the most relevant sections of the human genome responsible for aging. As Tech Crunch pointed out in its “WTF is Calico?” story, there are actually a burgeoning number of life-extension projects that rely heavily on Big Data for their future success. Transform the genetic code of the human body into a digital code of 1’s and 0’s, and you’re well on the way to making notions like “Immortality” purely a computational problem — like winning a chess match with Death.
Of course, that’s a hasty over-simplification of things. But it does point to the type of innovation that might be unlocked if non-traditional healthcare providers – like Google or Apple – get involved as the result of Obamacare. All of a sudden, you don’t have a bunch of legacy players – pharmaceutical companies, doctors, insurers – with legacy approaches attempting to innovate their way out of the American healthcare debacle. You get people like Arthur Levinson, former Genentech CEO and Apple chairman, who was tapped by Google to lead the Calico venture.
And, moreover, you get people like Ray Kurzweil – one of the world’s foremost experts on immortality as the result of his work on the Singularity – who just so happens to be an executive at Google these days. You can see where Google might going with this – what if health is reduced to being just a technology puzzle, a big data problem to be pondered by the world’s smartest scientists and data engineers? And Obamacare will make even more data available, from different types of people, at exactly the right time to take advantage of new advances in computing power.
Not to say that nothing could go wrong. There are Hollywood blockbuster films dedicated to the premise of tech companies giving us things – like eternal life and the eternal sunshine of the spotless mind – with insidious consequences. Calico, which is apparently short for “California Life Company,” sounds like a name of one of those sci-fi film corporations. And even Google admits that it has absolutely no idea of what to do next. They brought in top talent and want to start breaking stuff. That’s all we really know.
This is exciting stuff, hopefully so exciting that all the people trying to de-fund Obamacare will take a step back and realize that Obamacare might stimulate new Silicon Valley players to get involved and unlock the types of healthcare innovation that has never existed before. If that happens, good health will not just be for the economic elite who can afford it, but for everyone. |
/**
* Represents a room's creator, only containing "_id" and "username".
*
* @author Bradley Hilton (graywolf336)
* @version 0.0.1
* @since 0.1.0
*/
public class RoomCreator extends Identified {
private String username;
/**
* Sets the username of this room creator.
*
* @param username of the room creator
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Gets the username of this room creator.
*
* @return the username
*/
public String getUsername() {
return this.username;
}
} |
def memoryview_to_bytes(value):
if hasattr(value, 'tobytes'):
return value.tobytes()
return value |
<filename>test/ch/tsphp/tinsphp/inference_engine/test/integration/reference/ResolveConstantTest.java
/*
* This file is part of the TinsPHP project published under the Apache License 2.0
* For the full copyright and license information, please have a look at LICENSE in the
* root folder or visit the project's website http://tsphp.ch/wiki/display/TINS/License
*/
/*
* This class is based on the class ResolveConstantTest from the TSPHP project.
* TSPHP is also published under the Apache License 2.0
* For more information see http://tsphp.ch/wiki/display/TSPHP/License
*/
package ch.tsphp.tinsphp.inference_engine.test.integration.reference;
import ch.tsphp.tinsphp.inference_engine.test.integration.testutils.reference.AReferenceTypeScopeTest;
import ch.tsphp.tinsphp.inference_engine.test.integration.testutils.reference.TypeScopeTestStruct;
import org.antlr.runtime.RecognitionException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class ResolveConstantTest extends AReferenceTypeScopeTest
{
public ResolveConstantTest(String testString, TypeScopeTestStruct[] testStructs) {
super(testString, testStructs);
}
@Test
public void test() throws RecognitionException {
runTest();
}
@Parameterized.Parameters
public static Collection<Object[]> testStrings() {
return Arrays.asList(new Object[][]{
//conditionals
{"const a=1; a;", structDefault("", 1, 1, 0)},
{"const a=1;{ a;}", structDefault("", 1, 1, 0)},
{"const a=1;if(a==1){}", structDefault("", 1, 1, 0, 0)},
{"const a=1;if(true){ a;}", structDefault("", 1, 1, 1, 0, 0)},
{"const a=1;if(true){}else{ a;}", structDefault("", 1, 1, 2, 0, 0)},
{"const a=1;if(true){ if(true){ a;}}", structDefault("", 1, 1, 1, 0, 1, 0, 0)},
{"const a=1; switch(a){case 1: a;break;}", structDefault("", 1, 1, 0)},
{"const a=1; $b=0; switch($b){case 1: a;break;}", structDefault("", 1, 2, 2, 0, 0)},
{"const a=1; $b=0; switch($b){case 1:{a;}break;}", structDefault("", 1, 2, 2, 0, 0)},
{"const a=1; $b=0; switch($b){default:{a;}break;}", structDefault("", 1, 2, 2, 0, 0)},
{"const a=1; for($a=a;;){}", structDefault("", 1, 1, 0, 0, 1)},
{"const a=1; for(;a==1;){}", structDefault("", 1, 1, 1, 0, 0)},
{"const a=1; $a=0;for(;;$a+=a){}", structDefault("", 1, 2, 2, 0, 1)},
{"const a=1; for(;;){a;}", structDefault("", 1, 1, 3, 0, 0)},
{"const a=1; foreach([1] as $v){a;}", structDefault("", 1, 1, 2, 0, 0)},
{"const a=1; while(a==1){}", structDefault("", 1, 1, 0, 0)},
{"const a=1; while(true)a;", structDefault("", 1, 1, 1, 0, 0)},
{"const a=1; while(true){a;}", structDefault("", 1, 1, 1, 0, 0)},
{"const a=1; do ; while(a==1);", structDefault("", 1, 1, 1, 0)},
{"const a=1; do a; while(true);", structDefault("", 1, 1, 0, 0, 0)},
{"const a=1; try{a;}catch(\\Exception $ex){}", structDefault("", 1, 1, 0, 0, 0)},
{"const a=1; try{}catch(\\Exception $ex){a;}", structDefault("", 1, 1, 1, 2, 0, 0)},
//in expression (ok a; is also an expression but at the top of the AST)
{
"const a=1; !(1+a-a/a*a && a) || a;",
new TypeScopeTestStruct[]{
new TypeScopeTestStruct("a#", "\\.\\.", Arrays.asList(1, 1, 0, 1), null, "\\."),
new TypeScopeTestStruct(
"a#", "\\.\\.", Arrays.asList(1, 1, 0, 0, 0, 1), null, "\\."),
new TypeScopeTestStruct(
"a#", "\\.\\.", Arrays.asList(1, 1, 0, 0, 0, 0, 0, 1), null, "\\."),
new TypeScopeTestStruct(
"a#", "\\.\\.", Arrays.asList(1, 1, 0, 0, 0, 0, 1, 1), null, "\\."),
new TypeScopeTestStruct(
"a#", "\\.\\.", Arrays.asList(1, 1, 0, 0, 0, 0, 1, 0, 0), null, "\\."),
new TypeScopeTestStruct(
"a#", "\\.\\.", Arrays.asList(1, 1, 0, 0, 0, 0, 1, 0, 1), null, "\\.")
}
},
//const are global
{"const a=1; function foo(){a; return null;}", structDefault("", 1, 1, 4, 0, 0)},
//TODO TINS-161 inference OOP
// {"const a=1; class a{ private $a=a;}", structDefault("", 1, 1, 4, 0, 0, 1, 0)},
// {"const a=1; class a{ function foo(){a; return null;}}", structDefault("", 1, 1, 4, 0, 4, 0, 0)},
//same namespace
{"namespace{const a=1;} namespace{a;}", structDefault("", 1, 1, 0, 0)},
{"namespace a{const a=1;} namespace a{a;}", struct("", "\\a\\.\\a\\.", 1, 1, 0, 0)},
{
"namespace b\\c{const a=1;} namespace b\\c{a;}",
struct("", "\\b\\c\\.\\b\\c\\.", 1, 1, 0, 0)
},
{
"namespace d\\e\\f{const a=1;} namespace d\\e\\f{a;}",
struct("", "\\d\\e\\f\\.\\d\\e\\f\\.", 1, 1, 0, 0)
},
//different namespace absolute
{
"namespace a{ const a=1;} namespace x{\\a\\a;}",
struct("\\a\\", "\\a\\.\\a\\.", 1, 1, 0, 0)
},
//different namespace relative - defaut is like absolute
{"namespace a{ const a=1;} namespace{a\\a;}", struct("a\\", "\\a\\.\\a\\.", 1, 1, 0, 0)},
//different namespace relative
{
"namespace a\\b{ const a=1;} namespace a{ b\\a;}",
struct("b\\", "\\a\\b\\.\\a\\b\\.", 1, 1, 0, 0)
},
//using an alias
{
"namespace a\\b{ const a=1; } namespace x{ use a\\b as b; b\\a;}",
struct("b\\", "\\a\\b\\.\\a\\b\\.", 1, 1, 1, 0)
},
//const have a fallback mechanism to default scope
{"namespace{ const a=1;} namespace a{a;}", structDefault("", 1, 1, 0, 0)},
{"namespace{ const a=1;} namespace a\\b{a;}", structDefault("", 1, 1, 0, 0)},
{"namespace{ const a=1;} namespace a\\b\\c{a;}", structDefault("", 1, 1, 0, 0)},
{
"namespace{ const a=1;} namespace a{function foo(){a; return null;}}",
structDefault("", 1, 1, 0, 4, 0, 0)
},
//TODO TINS-161 inference OOP
// {
// "namespace{ const a=1;} namespace a{class a{ private $a=a;}}",
// structDefault("", 1, 1, 0, 4, 0, 0, 1, 0)
// },
// {
// "namespace{ const a=1;} namespace a{class a{ function foo(){a; return null;}}}",
// structDefault("", 1, 1, 0, 4, 0, 4, 0, 0)
// }
});
}
private static TypeScopeTestStruct[] structDefault(String prefix, Integer... accessToScope) {
return struct(prefix, "\\.\\.", accessToScope);
}
private static TypeScopeTestStruct[] struct(String prefix, String scope, Integer... accessToScope) {
return new TypeScopeTestStruct[]{
new TypeScopeTestStruct(prefix + "a#", scope, Arrays.asList(accessToScope), null, "\\.")
};
}
}
|
/**
* Imports data from the specified Web component by taking the specified x column
* for the x values, and the specified y column for the y values. Prior to calling this function,
* the Web component's Get method has to be called to load the data. The usage of the gotValue
* event in the Web component is unnecessary.
* <p>
* The expected response of the Web component is a JSON or CSV formatted file for this function to
* work.
* <p>
* Empty columns are filled with default values (1, 2, 3, ... for Entry 1, 2, 3, ...).
*
* @param web Web component to import from
* @param xValueColumn x-value column name
* @param yValueColumn y-value column name
*/
@SimpleFunction(description = "Imports data from the specified Web component, given the names of the " +
"X and Y value columns. Empty columns are filled with default values (1, 2, 3, ... for Entry 1, 2, ...). " +
"In order for the data importing to be successful, first the Get block must be called on the Web component " +
"to load the data, and then this block should be used on that Web component. The usage of the gotValue event " +
"in the Web component is unnecessary.")
public void ImportFromWeb(final Web web, String xValueColumn, String yValueColumn) {
YailList columns = YailList.makeList(Arrays.asList(xValueColumn, yValueColumn));
importFromWebAsync(web, columns);
} |
/*
* Given an array of ints length 3, return an array with the elements
* "rotated left" so {1, 2, 3} yields {2, 3, 1}.
*
* rotateLeft3({1, 2, 3}) --> {2, 3, 1}
* rotateLeft3({5, 11, 9}) --> {11, 9, 5}
* rotateLeft3({7, 0, 0}) --> {0, 0, 7}
*/
public class RotateLeft3Test {
public static void main(String[] args) {
RotateLeft3Test test = new RotateLeft3Test();
System.out.println(Arrays.toString(
test.rotateLeft3(new int[] {1, 2, 3})));
System.out.println(Arrays.toString(
test.rotateLeft3(new int[] {5, 11, 9})));
System.out.println(Arrays.toString(
test.rotateLeft3(new int[] {7, 0, 0})));
}
public int[] rotateLeft3(int[] nums) {
int temp = 0;
temp = nums[0];
nums[0] = nums[1];
nums[1] = nums[2];
nums[2] = temp;
return nums;
}
} |
<gh_stars>1-10
// Copyright (c) 2022 Red Hat, Inc.
// Copyright Contributors to the Open Cluster Management project
package controllers
import (
"k8s.io/apimachinery/pkg/api/equality"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
policiesv1 "open-cluster-management.io/governance-policy-propagator/api/v1"
)
var policyPredicateFuncs = predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
// nolint: forcetypeassert
policyObjNew := e.ObjectNew.(*policiesv1.Policy)
// nolint: forcetypeassert
policyObjOld := e.ObjectOld.(*policiesv1.Policy)
return !equality.Semantic.DeepEqual(policyObjNew.Status, policyObjOld.Status)
},
CreateFunc: func(e event.CreateEvent) bool {
return true
},
DeleteFunc: func(e event.DeleteEvent) bool {
return true
},
}
|
<reponame>raahoolkumeriya/codelocked
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.views import View
from .models import StreamType
from django.views.generic import TemplateView
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
#from .forms import CommentForm
from rest_framework import viewsets
from welcome.serializers import StreamSerializer
from welcome.filters import StreamFilter
import random
def health(request):
return HttpResponse(StreamType.objects.count())
class StreamView(viewsets.ModelViewSet):
queryset = StreamType.objects.all()
serializer_class = StreamSerializer
def LandingView(request, slugcatergory):
nav_items=['scripting','automation','machine_learning','other']
queryset=StreamType.objects.all()
#-------------------- random projects ---------------------- #
random_project=queryset[:15]
#count_ = StreamType.objects.all().count()
#for i in range(1,20):
# random_project.append(StreamType.objects.get(pk=random.randint(1,count_)))
#---------------------- paginator ---------------------------#
paginator = Paginator(queryset,5) # show 5 projects per page
page = request.GET.get('page')
try:
query_set = paginator.page(page)
except PageNotAnInteger:
query_set = paginator.page(1)
except EmptyPage:
query_set = paginator.page(paginator.num_pages)
#--------------------- database fetch -----------------------#
if slugcatergory == "home" :
context = {'type': query_set,
'nav_items':nav_items,
'random': set(random_project[:30])}
return render(request, 'home.html',context)
elif slugcatergory in ['scripting','automation','machine_learning','other']:
query_set=StreamType.objects.filter(category=slugcatergory)
context = {'type': query_set ,
'nav_items':nav_items,
'random': set(random_project[:30])}
return render(request, 'home.html',context)
elif slugcatergory == "allproject":
context = { 'filter': StreamFilter(request.GET, queryset=queryset) ,
'all_datasets': queryset,
'nav_items':nav_items}
return render(request, 'allproject.html',context)
else:
query_set=StreamType.objects.get(slug=slugcatergory)
context = {'type': query_set ,
'nav_items':nav_items,
'random': set(random_project[:30]) }
return render(request, 'detail.html',context)
def error_404_view(request, exception):
data = {"name": "CodeLocked.tk"}
return render(request,'error_404.html', data)
|
<reponame>kozross/linterieur
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnliftedFFITypes #-}
-- |
-- Module: Data.Diablerie.Byte
-- Copyright: (C) 2021 <NAME>
-- License: Apache 2.0
-- Maintainer: <NAME> <<EMAIL>>
-- Stability: stable
-- Portability: GHC only
--
-- Functions for searching and accumulating over 'ByteArray's (and
-- 'ByteArray#'s) in a byte-oriented manner.
--
-- = Important note
--
-- No bounds checking (or indeed, checking of any prerequisites) is done by any
-- of these functions. Use with care.
module Data.Diablerie.Byte
( -- * Wrapped operations
-- ** Search
findFirstEq,
findFirstEqIn,
findFirstNe,
findFirstNeIn,
findFirstGt,
findFirstGtIn,
findFirstLt,
findFirstLtIn,
findLastEq,
findLastEqIn,
-- ** Accumulate
countEq,
countEqIn,
-- * Raw operations
-- ** Search
findFirstEqIn#,
findFirstNeIn#,
findFirstGtIn#,
findFirstLtIn#,
findLastEqIn#,
-- ** Accumulate
countEqIn#,
)
where
import Data.Primitive.ByteArray
( ByteArray (ByteArray),
sizeofByteArray,
)
import Foreign.C.Types
( CInt (CInt),
CPtrdiff (CPtrdiff),
CSize (CSize),
)
import GHC.Exts (ByteArray#, Int#, word2Int#)
import GHC.Word (Word8 (W8#))
-- Wrapped ops
-- | A convenience wrapper for searching the entire 'ByteArray'. More precisely,
-- @findFirstEq ba w8@ is the same as @'findFirstEqIn' ba 0 ('sizeofByteArray'
-- ba) w8@.
--
-- @since 1.0
findFirstEq :: ByteArray -> Word8 -> Maybe Int
findFirstEq ba = findFirstEqIn ba 0 (sizeofByteArray ba)
-- | Identical to 'findFirstEqIn#', except using lifted types, and using a
-- 'Maybe' for the result to avoid negative-number indices.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray' argument, and @w8@ the byte to match.
--
-- * @0 '<=' off@ and @off '<' 'sizeofByteArray' ba@
-- * @0 '<=' len@ and @len + off <= 'sizeofByteArray' ba@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findFirstEqIn ba off len w8@.
--
-- * If @w8@ exists in the index range @off .. off + len - 1@, then @res@ will
-- be in a 'Just' with a value in the range @off .. off + len - 1@
-- * Otherwise, @res = 'Nothing'@.
--
-- @since 1.0
findFirstEqIn :: ByteArray -> Int -> Int -> Word8 -> Maybe Int
findFirstEqIn (ByteArray ba#) off len (W8# w8#) =
let (CPtrdiff res) =
findFirstEqIn#
ba#
(fromIntegral off)
(fromIntegral len)
(word2Int# w8#)
in case signum res of
(-1) -> Nothing
_ -> Just . fromIntegral $ res
-- | A convenience wrapper for searching the entire 'ByteArray'. More precisely,
-- @findFirstNe ba w8@ is the same as @'findFirstNeIn' ba 0 ('sizeofByteArray'
-- ba) w8@.
--
-- @since 1.0
findFirstNe :: ByteArray -> Word8 -> Maybe Int
findFirstNe ba = findFirstNeIn ba 0 (sizeofByteArray ba)
-- | Identical to 'findFirstNeIn#', except using lifted types, and using a
-- 'Maybe' for the result to avoid negative-number indices.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray' argument, and @w8@ the byte to differ from.
--
-- * @0 '<=' off@ and @off '<' 'sizeofByteArray' ba@
-- * @0 '<=' len@ and @len + off <= 'sizeofByteArray' ba@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findFirstEqIn ba off len w8@.
--
-- * If a byte different to @w8@ exists in the index range @off .. off + len -
-- 1@, then @res@ will be 'Just' the index of the first such byte, in the
-- range @off .. off + len - 1@
-- * Otherwise, @res = 'Nothing'@.
--
-- @since 1.0
findFirstNeIn :: ByteArray -> Int -> Int -> Word8 -> Maybe Int
findFirstNeIn (ByteArray ba#) off len (W8# w8#) =
let (CPtrdiff res) =
findFirstNeIn#
ba#
(fromIntegral off)
(fromIntegral len)
(word2Int# w8#)
in case signum res of
(-1) -> Nothing
_ -> Just . fromIntegral $ res
-- | A convenience wrapper for searching the entire 'ByteArray'. More precisely,
-- @findFirstGt ba w8@ is the same as @'findFirstGtIn' ba 0 ('sizeofByteArray'
-- ba) w8@.
--
-- @since 1.0
findFirstGt :: ByteArray -> Word8 -> Maybe Int
findFirstGt ba = findFirstGtIn ba 0 (sizeofByteArray ba)
-- | Identical to 'findFirstGtIn#', except using lifted types, and using a
-- 'Maybe' for the result to avoid negative-number indices.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray' argument, and @w8@ the byte to match.
--
-- * @0 '<=' off@ and @off '<' 'sizeofByteArray' ba@
-- * @0 '<=' len@ and @len + off <= 'sizeofByteArray' ba@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findFirstGtIn ba off len w8@.
--
-- * If @res > -1@, then @'Data.Primitive.ByteArray.indexByteArray' ba res '>' w8@.
-- * If @res > -1@, then for any @0 <= i < res@, @'Data.Primitive.ByteArray.indexByteArray' ba i '<='
-- w8@.
-- * If @res = -1@, then every byte in @ba@ is equal to, or less than, @w8@.
--
-- @since 1.0
findFirstGtIn :: ByteArray -> Int -> Int -> Word8 -> Maybe Int
findFirstGtIn (ByteArray ba#) off len (W8# w8#) =
let (CPtrdiff res) =
findFirstGtIn#
ba#
(fromIntegral off)
(fromIntegral len)
(word2Int# w8#)
in case signum res of
(-1) -> Nothing
_ -> Just . fromIntegral $ res
-- | A convenience wrapper for searching the entire 'ByteArray'. More precisely,
-- @findFirstLt ba w8@ is the same as @'findFirstLtIn' ba 0 ('sizeofByteArray'
-- ba) w8@.
--
-- @since 1.0
findFirstLt :: ByteArray -> Word8 -> Maybe Int
findFirstLt ba = findFirstLtIn ba 0 (sizeofByteArray ba)
-- | Identical to 'findFirstLtIn#', except using lifted types, and using a
-- 'Maybe' for the result to avoid negative-number indices.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray' argument, and @w8@ the byte to match.
--
-- * @0 '<=' off@ and @off '<' 'sizeofByteArray' ba@
-- * @0 '<=' len@ and @len + off <= 'sizeofByteArray' ba@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findFirstGtIn ba off len w8@.
--
-- * If @res > -1@, then @'Data.Primitive.ByteArray.indexByteArray' ba res '<' w8@.
-- * If @res > -1@, then for any @0 <= i < res@, @'Data.Primitive.ByteArray.indexByteArray' ba i '>='
-- w8@.
-- * If @res = -1@, then every byte in @ba@ is equal to, or greater than, @w8@.
--
-- @since 1.0
findFirstLtIn :: ByteArray -> Int -> Int -> Word8 -> Maybe Int
findFirstLtIn (ByteArray ba#) off len (W8# w8#) =
let (CPtrdiff res) =
findFirstLtIn#
ba#
(fromIntegral off)
(fromIntegral len)
(word2Int# w8#)
in case signum res of
(-1) -> Nothing
_ -> Just . fromIntegral $ res
-- | A convenience wrapper for searching the entire 'ByteArray'. More precisely,
-- @findLastEq ba w8@ is the same as @'findLastEqIn' ba 0 ('sizeofByteArray'
-- ba) w8@.
--
-- @since 1.0
findLastEq :: ByteArray -> Word8 -> Maybe Int
findLastEq ba = findLastEqIn ba 0 (sizeofByteArray ba)
-- | Identical to 'findLastEqIn#', except using lifted types, and using a
-- 'Maybe' for the result to avoid negative-number indices.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray' argument, and @w8@ the byte to match.
--
-- * @0 '<=' off@ and @off '<' 'sizeofByteArray' ba@
-- * @0 '<=' len@ and @len + off <= 'sizeofByteArray' ba@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findLastEqIn ba off len w8@.
--
-- * If @w8@ exists in the index range @off .. off + len - 1@, then @res@ will
-- be in a 'Just' with a value in the range @off .. off + len - 1@
-- * Otherwise, @res = 'Nothing'@.
--
-- @since 1.0
findLastEqIn :: ByteArray -> Int -> Int -> Word8 -> Maybe Int
findLastEqIn (ByteArray ba#) off len (W8# w8#) =
let (CPtrdiff res) =
findLastEqIn#
ba#
(fromIntegral off)
(fromIntegral len)
(word2Int# w8#)
in case signum res of
(-1) -> Nothing
_ -> Just . fromIntegral $ res
-- | A convenience wrapper for counting the entire 'ByteArray'. More precisely,
-- @countEq ba w8@ is the same as @'countEqIn' ba 0 ('sizeofByteArray' ba)
-- w8@.
--
-- @since 1.0
countEq :: ByteArray -> Word8 -> Int
countEq ba = countEqIn ba 0 (sizeofByteArray ba)
-- | Identical to 'countEqIn#', except using lifted types.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length argument, @ba@ the
-- 'ByteArray' argument, and @w8@ the byte to count.
--
-- * @0 '<=' off@ and @off '<' 'sizeofByteArray' ba@
-- * @0 '<=' len@ and @len + off <= 'sizeofByteArray' ba@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @countEqIn ba off len w8@.
--
-- * @0 '<=' res@ and @res '<' len@.
--
-- @since 1.0
countEqIn :: ByteArray -> Int -> Int -> Word8 -> Int
countEqIn (ByteArray ba#) off len (W8# w8#) =
let (CInt res) =
countEqIn#
ba#
(fromIntegral off)
(fromIntegral len)
(word2Int# w8#)
in fromIntegral res
-- Raw ops
-- | Searches a byte array from an offset for the index of the
-- first occurrence of a byte.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray#' argument, and @w8@ the byte to match.
--
-- * @0 '<=' off@ and @off '<' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' len@ and @len + off '<=' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' w8@ and @w8 '<' 255@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findFirstEqIn# ba off len w8@.
--
-- * If @w8@ exists in the index range @off .. off + len - 1@, then @res@ will
-- be the index of the first match, in the range @off .. off + len - 1@
-- * Otherwise, @res = -1@
--
-- @since 1.0
foreign import ccall unsafe "find_first_eq"
findFirstEqIn# ::
-- | The memory area to search
ByteArray# ->
-- | Offset from the start
CSize ->
-- | How many bytes to check
CSize ->
-- | What byte to match (only low 8 bits)
Int# ->
-- | Location as index, or -1 if not found
CPtrdiff
-- | Searches a byte array from an offset for the index of the
-- first non-occurrence of a byte.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray#' argument, and @w8@ the byte to differ from.
--
-- * @0 '<=' off@ and @off '<' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' len@ and @len + off '<=' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' w8@ and @w8 '<' 255@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findFirstEqIn# ba off len w8@.
--
-- * If a byte different to @w8@ exists in the index range @off .. off + len -
-- 1@, then @res@ will be the index of the first such byte, in the range @off
-- .. off + len - 1@
-- * Otherwise, @res = -1@.
--
-- @since 1.0
foreign import ccall unsafe "find_first_ne"
findFirstNeIn# ::
-- | The memory area to search
ByteArray# ->
-- | Offset from the start
CSize ->
-- | How many bytes to check
CSize ->
-- | What byte to differ from (only low 8 bits)
Int# ->
-- | Location as index, or -1 if not found
CPtrdiff
-- | Searches a byte array from an offset for the index of the
-- first occurrence of a byte greater than the argument.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray#' argument, and @w8@ the byte argument.
--
-- * @0 '<=' off@ and @off '<' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' len@ and @len + off '<=' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' w8@ and @w8 '<' 255@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findFirstGtIn# ba off len w8@.
--
-- * If @res > -1@, then @'GHC.Exts.indexByteArray#' ba res '>' w8@.
-- * If @res > -1@, then for any @0 <= i < res@, @'GHC.Exts.indexByteArray#' ba i '<='
-- w8@.
-- * If @res = -1@, then every byte in @ba@ is equal to, or less than, @w8@.
--
-- @since 1.0
foreign import ccall unsafe "find_first_gt"
findFirstGtIn# ::
-- | The memory area to search
ByteArray# ->
-- | Offset from the start
CSize ->
-- | How many bytes to check
CSize ->
-- | Byte target (only low 8 bits)
Int# ->
-- | Location as index, or -1 if not found
CPtrdiff
-- | Searches a byte array from an offset for the index of the
-- first occurrence of a byte less than the argument.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray#' argument, and @w8@ the byte argument.
--
-- * @0 '<=' off@ and @off '<' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' len@ and @len + off '<=' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' w8@ and @w8 '<' 255@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findFirstGtIn# ba off len w8@.
--
-- * If @res > -1@, then @'GHC.Exts.indexByteArray#' ba res '<' w8@.
-- * If @res > -1@, then for any @0 <= i < res@, @'GHC.Exts.indexByteArray#' ba i '>='
-- w8@.
-- * If @res = -1@, then every byte in @ba@ is equal to, or greater than, @w8@.
--
-- @since 1.0
foreign import ccall unsafe "find_first_lt"
findFirstLtIn# ::
-- | The memory area to search
ByteArray# ->
-- | Offset from the start
CSize ->
-- | How many bytes to check
CSize ->
-- | Byte target (only low 8 bits)
Int# ->
-- | Location as index, or -1 if not found
CPtrdiff
-- | Searches a byte array from an offset for the index of the
-- last occurrence of a byte.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length
-- argument, @ba@ the 'ByteArray#' argument, and @w8@ the byte to match.
--
-- * @0 '<=' off@ and @off '<' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' len@ and @len + off '<=' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' w8@ and @w8 '<' 255@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @findLastEqIn# ba off len w8@.
--
-- * If @w8@ exists in the index range @off .. off + len - 1@, then @res@ will
-- be in the range @off .. off + len - 1@
-- * Otherwise, @res = -1@
--
-- @since 1.0
foreign import ccall unsafe "find_last_eq"
findLastEqIn# ::
-- | The memory area to search
ByteArray# ->
-- | Offset from the start
CSize ->
-- | How many bytes to check
CSize ->
-- | What byte to match (only low 8 bits)
Int# ->
-- | Location as index, or -1 if not found
CPtrdiff
-- | Counts the occurrences of a specific byte in a byte array from an offset.
--
-- = Prerequisites
--
-- Let @off@ be the offset argument, @len@ be the length argument, @ba@ the
-- 'ByteArray#' argument, and @w8@ the byte to count.
--
-- * @0 '<=' off@ and @off '<' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' len@ and @len + off '<=' 'GHC.Exts.sizeofByteArray#' ba@
-- * @0 '<=' w8@ and @w8 '<' 255@
--
-- = Outcomes
--
-- Let @res@ be the result of a call @countEqIn# ba off len w8@.
--
-- * @0 '<=' res@ and @res '<' len@.
--
-- @since 1.0
foreign import ccall unsafe "count_eq"
countEqIn# ::
-- | The memory area to count
ByteArray# ->
-- | Offset from the start
CSize ->
-- | How many bytes to check
CSize ->
-- | What byte to count (only low 8 bits)
Int# ->
-- | How many times the byte occurs
CInt
|
/**
*
* @file openmp_task.h
*
* @copyright 2018 King Abdullah University of Science and Technology (KAUST).
* All rights reserved.
***
* @brief AL4SAN OpenMP task header
*
* AL4SAN is a software package provided by King Abdullah University of Science and Technology (KAUST)
*
* @version 1.1.0
* @author <NAME>
* @date 2018-10-18
*
**/
#ifndef _TASKS_H_
#define _TASKS_H_
//BEGIN_C_DECLS
#include "omp.h"
#include "control/al4san_common.h"
BEGIN_C_DECLS
#define AL4SAN_OPENMP_UNDEFINED 0xFF0000
#define AL4SAN_OPENMP_UNDEFINED_MASK 0x0000FF
//#define AL4SAN_DEP 101
#define ON 1
#define OFF 0
//#define ARG_END 0
#define NUM_SHAREDS 8
#define AL4SAN_OPENMP_NMAXARGS 30
#define NUM_WORK 4
/*typedef enum { AL4SAN_INPUT=(1<<0),
AL4SAN_OUTPUT=(1<<1),
AL4SAN_INOUT=(AL4SAN_INPUT|AL4SAN_OUTPUT),
AL4SAN_VALUE=(1<<2),
AL4SAN_SCRATCH=(1<<3)
}al4san_openmp_dependency_t;
typedef enum { AL4SAN_PRIORITY=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_LABEL=AL4SAN_OPENMP_UNDEFINED
}al4san_openmp_task_flags_t;
typedef enum {
//Data region
AL4SAN_REGION_0=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_1=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_2=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_3=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_4=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_5=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_6=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_7=AL4SAN_OPENMP_UNDEFINED,
//ldu region
AL4SAN_REGION_L=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_D=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REGION_U=AL4SAN_OPENMP_UNDEFINED,
//flags
AL4SAN_LOCK_TO_THREAD=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_SEQUENCE=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_THREAD_COUNT=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_THREAD_SET_TO_MANUAL_SCHEDULING=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_LOCK_TO_THREAD_MASK=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_COLOR=AL4SAN_OPENMP_UNDEFINED,
//data dep
AL4SAN_NODEP=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_NOLOCALITY=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_ACCUMULATOR=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_NOACCUMULATOR=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_GATHERV=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_NOGATHERV=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REF=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_AFFINITY=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_DONT_TRACK=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_PASSED_BY_REF=AL4SAN_OPENMP_UNDEFINED,
//arry
AL4SAN_DATA_ARRAY=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_DATA_MODE_ARRAY=AL4SAN_OPENMP_UNDEFINED,
//args
AL4SAN_CL_ARGS_NFREE=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_CL_ARGS=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_REDUX=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_COMMUTE=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_SSEND=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_ACCESS_MODE_MAX=AL4SAN_OPENMP_UNDEFINED,
//callback
AL4SAN_CALLBACK=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_CALLBACK_WITH_ARG=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_CALLBACK_ARG=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_PROLOGUE_CALLBACK=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_PROLOGUE_CALLBACK_ARG=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_PROLOGUE_CALLBACK_POP=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_PROLOGUE_CALLBACK_POP_ARG=AL4SAN_OPENMP_UNDEFINED,
//rank
AL4SAN_EXECUTE_ON_NODE=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_EXECUTE_ON_DATA=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_EXECUTE_ON_WORKER=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_WORKER_ORDER=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_SCHED_CTX=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_HYPERVISOR_TAG=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_POSSIBLY_PARALLEL=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_FLOPS=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_TAG=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_TAG_ONLY=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_NODE_SELECTION_POLICY=AL4SAN_OPENMP_UNDEFINED,
//CUDA async option
AL4SAN_CUDA_FLG=AL4SAN_OPENMP_UNDEFINED,
AL4SAN_LOCALITY=AL4SAN_OPENMP_UNDEFINED
} al4san_openmp_undefined;*/
//****************llvm struct*********************
typedef long kmp_intptr_t;
typedef int kmp_int32;
typedef char bool;
typedef struct ident {
kmp_int32 reserved_1; /**< might be used in Fortran; see above */
kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags; KMP_IDENT_KMPC identifies this union member */
kmp_int32 reserved_2; /**< not really used in Fortran any more; see above */
#if USE_ITT_BUILD
/* but currently used for storing region-specific ITT */
/* contextual information. */
#endif /* USE_ITT_BUILD */
kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for C++ */
char const *psource; /**< String describing the source location.
The string is composed of semi-colon separated fields which describe the source file,
the function and a pair of line numbers that delimit the construct.
*/
} ident_t;
typedef struct kmp_depend_info {
//kmp_intptr_t base_addr;
void* base_addr;
size_t len;
struct {
bool in:1;
bool out:1;
} flags;
} kmp_depend_info_t;
struct kmp_task;
typedef kmp_int32 (* kmp_routine_entry_t)( kmp_int32, struct kmp_task * );
typedef struct shar{
void *ptr[NUM_SHAREDS];
void *workspace[NUM_WORK];
int workflage[NUM_WORK];
int pcounter;
int wkcounter;
}pshareds;
typedef struct kmp_task { /* GEH: Shouldn't this be aligned somehow? */
pshareds* shareds; /**< pointer to block of pointers to shared vars */
//void * shareds;
kmp_routine_entry_t routine; /**< pointer to routine to call for executing task */
kmp_int32 part_id; /**< part id for the task */
int ts;
void *cl_arg;
size_t cl_arg_size;
} kmp_task_t;
#ifdef __cplusplus
extern "C" {
#endif
kmp_int32 __kmpc_global_thread_num ( ident_t * );
kmp_task_t*
__kmpc_omp_task_alloc( ident_t *loc_ref, kmp_int32 gtid, kmp_int32 flags,
size_t sizeof_kmp_task_t, size_t sizeof_shareds,
kmp_routine_entry_t task_entry );
void __kmpc_proxy_task_completed_ooo ( kmp_task_t *ptask );
kmp_int32 __kmpc_omp_task_with_deps ( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t * new_task,
kmp_int32 ndeps, kmp_depend_info_t *dep_list,
kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list );
kmp_int32
__kmpc_omp_task( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t * new_task );
#ifdef __cplusplus
}
#endif
//************************************************
typedef struct al4san_openmp_arg_list_s
{
kmp_task_t *task;
} AL4SAN_Openmp_arg_list;
typedef struct AL4SAN_Openmp_Task
{
int num_arg;
int arg_depenency[AL4SAN_OPENMP_NMAXARGS];
int arg_size[AL4SAN_OPENMP_NMAXARGS];
} AL4SAN_Openmp_task_t;
struct al4san_openmp_pack_arg_data
{
char *arg_buffer;
size_t arg_buffer_size;
size_t current_offset;
int nargs;
};
#define AL4SAN_OPENMP_ASSERT_MSG(x, msg, ...) do {\
if(!(x))\
{\
fprintf(stderr, "[al4san][abort][%s()@%s:%d] " msg "\n", __func__, __FILE__, __LINE__, ## __VA_ARGS__); \
abort();\
}\
}while(0)
#define AL4SAN_OPENMP_REALLOC(ptr, size) do { void *_new_ptr = realloc(ptr, size); AL4SAN_OPENMP_ASSERT_MSG(_new_ptr != NULL, "Cannot reallocate %ld bytes\n", (long) (size)); ptr=_new_ptr;} while (0)
//#define AL4SAN_CODELETS_NAME(name) OPENMP_##name##_func
//TO be used instead of AL4SAN_CODELETS_NAME
//#define AL4SAN_TASK(name) OPENMP_##name##_func
#define AL4SAN_OPENMP_TASK_HEADER(name)
//callback
//#define AL4SAN_CALLBACK(name) NULL
#define al4san_openmp_matrix_get_nx(num) NULL
#define al4san_openmp_matrix_get_ny(num) NULL
/*#define GET_MACRO(_1,_2,_3,NAME,...) NAME
#define AL4SAN_CODELETS(...) GET_MACRO(__VA_ARGS__, AL4SAN_CODELETS3, AL4SAN_CODELETS2)(__VA_ARGS__)
#define AL4SAN_CODELETS3(name, cpu_func_name, cuda_func_name) \
void cpu_func_name(AL4SAN_Openmp_arg_list *al4san_arg); \
int OPENMP_##name##_func (kmp_int32 gtid, kmp_task_t *task) { AL4SAN_Openmp_arg_list al4san_arg; al4san_arg.task=task; cpu_func_name(&al4san_arg); return 0; }
#define AL4SAN_CODELETS2(name, cpu_func_name) \
void cpu_func_name(AL4SAN_Openmp_arg_list *al4san_arg); \
int OPENMP_##name##_func (kmp_int32 gtid, kmp_task_t *task) { AL4SAN_Openmp_arg_list al4san_arg; al4san_arg.task=task; cpu_func_name(&al4san_arg); return 0; }
*/
/*
* Preparing work's function:
* @param[in] First argument is task name.
* @param[in] Second argument user cpu function name
*/
//TO be used instead of AL4SAN_CODELETS
#define AL4SAN_OPENMP_TASK_CPU(name, cpu_func_name)\
void cpu_func_name(AL4SAN_arg_list *al4san_arg); \
int OPENMP_##name##_func (kmp_int32 gtid, kmp_task_t *task){\
AL4SAN_arg_list al4san_arg; \
AL4SAN_Openmp_arg_list openmparg;\
openmparg.task=task;\
al4san_arg.Openmp_arg_list= (AL4SAN_Openmp_arg_list*) &openmparg;\
cpu_func_name(&al4san_arg);\
al4san_openmp_workspace_destroy(&al4san_arg);\
return 0; }
/*
* Preparing work's function:
* @param[in] First argument is task name.
* @param[in] Second argument user gpu function name
*/
#define AL4SAN_OPENMP_TASK_GPU(name, gpu_func_name)
/*
* Preparing work's function:
* @param[in] First argument is task name.
* @param[in] Second argument cpu anf gpuuser function name
*/
#define AL4SAN_OPENMP_TASK_CPU_GPU(name, cpu_func_name, gpu_func_name)\
void cpu_func_name(AL4SAN_arg_list *al4san_arg); \
int OPENMP_##name##_func (kmp_int32 gtid, kmp_task_t *task){\
AL4SAN_arg_list al4san_arg; \
AL4SAN_Openmp_arg_list openmparg;\
openmparg.task=task;\
al4san_arg.Openmp_arg_list= (AL4SAN_Openmp_arg_list*) &openmparg;\
cpu_func_name(&al4san_arg);\
al4san_openmp_workspace_destroy(&al4san_arg);\
return 0; }
END_C_DECLS
#endif /* _TASKS_H_ */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.