text:
Stochastic Sensor Scheduling via Distributed Convex Optimization \thanksreffootnoteinfo

# Stochastic Sensor Scheduling via Distributed Convex Optimization \thanksreffootnoteinfo

[    [
###### Abstract

In this paper, we propose a stochastic scheduling strategy for estimating the states of discrete-time linear time invariant (DTLTI) dynamic systems, where only one system can be observed by the sensor at each time instant due to practical resource constraints. The idea of our stochastic strategy is that a system is randomly selected for observation at each time instant according to a pre-assigned probability distribution. We aim to find the optimal pre-assigned probability in order to minimize the maximal estimate error covariance among dynamic systems. We first show that under mild conditions, the stochastic scheduling problem gives an upper bound on the performance of the optimal sensor selection problem, notoriously difficult to solve. We next relax the stochastic scheduling problem into a tractable suboptimal quasi-convex form. We then show that the new problem can be decomposed into coupled small convex optimization problems, and it can be solved in a distributed fashion. Finally, for scheduling implementation, we propose centralized and distributed deterministic scheduling strategies based on the optimal stochastic solution and provide simulation examples.

qual]Chong Li, isu]Nicola Elia

Dept. of Electrical and Computer Engineering, Iowa State University, Ames, IA, 50011. Currently with Qualcomm Research, Bridgewater, NJ, 08807.

Dept. of Electrical and Computer Engineering, Iowa State University, Ames, IA, 50011.

Key words:  Networked control systems, sensor scheduling, Kalman filter, stochastic scheduling, sensor selection

11footnotetext: This research has been supported partially supported by NSF ECS-0901846 and NSF CCF-1320643. Partial version of this paper has appeared in [1].

## 1 Introduction

In this paper, we consider the problem of scheduling the observations of independent targets in order to minimize the tracking error covariance, but when only one target can be observed at a given time. This problem captures many interesting tracking/estimation application problems. As a motivational example, consider independent dynamic targets, spatially distributed in an area, that need to be tracked (estimated) by a single (mobile) camera sensor. The camera has limited sensing range and therefore it needs to zoom in on, or be in proximity of, one of the targets for obtaining measurements. Under the assumption that the switching time among the targets is negligible, then we need to find a visiting sequence in order to minimize the estimate error.
Another case is when a set of mobile surveillance devices need to track geographically-separated targets, where each target is tracked by one assigned surveillance device. However, the sensing/measuring channel can only be used by one estimator at the time (e.g. sonar range-finding [2]). Then, we need to design a scheduling sequence of surveillance devices for accurate tracking.

### 1.1 Related Work and Contributions of This Paper

There has been considerable research effort devoted to the study of sensor selection problems, including sensor scheduling [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] and sensor coverage [17, 18, 19, 20, 7, 21]. This trend has been inspired by the significance and wide applications of sensor networks. As the literature is vast, we list a few results which are relevant to this paper. The sensor scheduling problem mainly arises from minimization of two relevant costs: sensor network energy consumption and estimate error. On the one hand, [5],[6] and [9], see also reference therein, have proposed various efficient sensor scheduling algorithms to minimize the sensor network energy consumption and consequently maximize the network lifetime. On the other hand, researchers have proposed many tree-search based sensor scheduling algorithms (mostly in conjunction with Kalman filtering) to minimize the estimate error [3],[4],[13], e.g. sliding-window, thresholding, relaxed dynamic programming, etc. By taking both sensor network lifetime and estimate accuracy into account, several sensor tree-search based scheduling algorithms have been proposed in [8], [22]. In [10], the authors have formulated the general sensor selection problem and solved it by relaxing it to a convex optimization problem. The general formulation therein can handle various performance criteria and topology constraints. However, the framework in [10] is only suitable for static systems instead of dynamic systems which are mostly considered in the literature.
In general, deterministic optimal sensor selection problems are notoriously difficult. In this paper, we propose a stochastic scheduling strategy. At each time instant, a target is randomly chosen to be measured according to a pre-assigned probability distribution. We find the optimal pre-assigned distribution that minimize an upper bound on the expected estimate error covariance (in the limit) in order to keep the actual estimate error covariance small. Compared with algorithms in the literature, this strategy has low computational complexity, it is simple to implement and provides performance guarantee on the general deterministic scheduling problem. Of course, the reduction of computational complexity comes at the expenses of degradation of the ideal performance. However, in many situations the extra computational complexity cost may not be justified. Further this strategy can easily incorporate extra constraints on the scheduling design, which might be difficult to handle in existing algorithms (e.g. tree-search based algorithms).
Our work is related to [7], [23] and [11]. [7] introduces stochastic scheduling to deal with sensor selection and coverage problems, and [23] extends the setting and results in [7] to a tree topology. Although we also adopt the stochastic scheduling approach, the problem formulation and proposed algorithms of this paper are different from [7, 23]. In particular, we consider different cost functions and design distributed algorithms that provide optimal probability distributions. [11] has considered a scheduling problem in continuous-time and proposed a tractable relaxation, which provides a lower bound on the achievable performance, and an open-loop periodic switching strategy to achieve the bound in the limit of arbitrarily fast switching. However, besides the difference in the formulations, their approach does not appear to be directly extendable to the discrete-time setting. In summary, our main contributions include:

1. We obtain a stochastic scheduling strategy with performance guarantee on the general deterministic scheduling problem by solving distributed optimization problems.

2. For scheduling implementation, we propose both centralized and distributed deterministic scheduling strategies.

### 1.2 Notations and Organization

Throughout the paper, is the transpose of matrix . implies an matrix with as all its entries. denotes a diagonal matrix with vector as its diagonal entries. (or ) and (or ) respectively implies matrix is positive semi-definite and positive definite where and represent the positive semi-definite and positive definite cones. For a matrix A, if the block entry , we use in the matrix to present block .
The paper is organized as follows. In section 2, we mathematically formulate the stochastic scheduling problem. In section 3, we develop an approach and a distributed computing algorithm to solve the optimization problem. In section 4, we present some further results and the extensions of our model. In section 5, we consider the scheduling implementation problem. At last, we present simulations to support our results.

## 2 Sensor Scheduling Problem Setup

Consider a set of N DTLTI systems (targets) evolving according to the equations

 xi[k+1]=Aixi[k]+wi[k]i=1,2,…N (1)

where is the process state vector and is assumed to be an independent Gaussian noise with zero mean and covariance matrix . The initial state is assumed to be an independent Gaussian random variable with zero mean and covariance matrix . In practice, each DTLTI system modeled above may represent the dynamic change of a local environment, the trajectory of a mobile vehicle, the varying states of a manufactory machine, etc. As a result of the sensor’s limited range of sensing or the congestion of the sensing channel, at time instant , only one system can be observed as

 ~yi[k]=ξi[k](Cixi[k]+vi[k]) (2)

where is the indicator function indicating whether or not the system is observed at time instant , and accordingly we have constraint\@footnotemark\@footnotetextIf we assume at most one target is chosen to be measured at each time instant, then we have . Without loss of generality, in this paper we consider the case that one out of targets must be chosen at each time instant. . is the measurement noise, which is assumed to be independent Gaussian with zero mean and covariance matrix .

###### Assumption 1

For all , the pair is controllable and the pair is detectable.

Denote as the estimate at time , obtained by a causal estimator for system , which depends on the past and current observations . We begin by considering problem of minimizing (in the limit) the maximal estimate error. The problem can be formulated mathematically as

 min^xi,{ξi[j]}∞j=1maxi(limsupT→∞1TT∑k=1E[(xi[k]−^xi[k])′(xi[k]−^xi[k])])s.t.Equation:(???),(???),i=1,…,N,N∑i=1ξi[k]=1, (3)

As the DTLTI systems are assumed to be evolving independently, then for a fixed the optimal estimator for minimizing the estimate error covariance of system () is given by a Kalman filter\@footnotemark\@footnotetextThis indicates that parallel estimators, i.e., Kalman filters, are used for estimating independent DTLTI systems. whose process of prediction and update are presented as follows [24]. Firstly we define

 ^xi[k|k]≜E[xi[k]|{~yi[j]}kj=1]Pi[k|k]≜E[(xi[k]−^xi[k|k])(xi[k]−^xi[k|k])′|{~yi[j]}kj=1]^xi[k+1|k]≜E[xi[k+1]|{~yi[j]}kj=1]Pi[k+1|k]≜E[(xi[k+1]−^xi[k+1|k])(xi[k+1]−^xi[k+1|k])′|{~yi[j]}kj=1]

Then the Kalman filter evolves as

 ^xi[k+1|k]=Ai^xi[k|k]Pi[k+1|k]=AiPi[k|k]A′+Qi^xi[k+1|k+1]=^xi[k+1|k]+ξi[k+1]K[k+1](yi[k+1]−Ci^xi[k+1|k])Pi[k+1|k+1]=Pi[k+1|k]−ξi[k+1]Ki[k+1]CiPi[k+1|k]

where is the Kalman gain matrix. After straightforward derivation, we have the covariance of the estimate error evolving as

 AiPi[k]A′i+Qi−ξi[k]AiPi[k]C′i(CiPi[k]C′i+Ri)−1CiPi[k]A′i =Pi[k+1] (4)

where we use the simplified notation . Note that the error covariance is a function of sequence . Moreover, given , the evolution of the error covariance is independent of the measurement values. Substituting the optimal estimator, the problem (2) is simplified into the following one.

Deterministic Scheduling Problem:

 μd=min{ξi[j]}∞j=1,i=[1..N]maxi(limsupT→∞1TT∑k=1Tr(Pi[k]))subject toEquation:(???),N∑i=1ξi[k]=1, (5)

This problem is notoriously difficult to solve. There are not known optimal alternatives to searching all possible schedules and then pick the optimal one by complete comparison. However, the procedure is not computationally tractable in practice. Motivated by this fact, in what follows, we present a stochastic scheduling strategy with advantages summarized below:

1. The stochastic scheduling strategy provides an upper bound on the performance of the deterministic scheduling problem under mild conditions, as proved in Theorem 1 next.

2. The stochastic scheduling problem can be easily relaxed into a convex optimization problem, which can be solved efficiently in a distributed fashion.

3. The relaxed problem provides an open-loop strategy, which has low computing complexity and is simple to implement.

4. Several practical constraints/considerations can be easily incorporated into the stochastic scheduling formulation, as discussed in Section .

### 2.1 Problem Formulation: Stochastic Scheduling Strategy

First of all, we remove the dependence on time instant and consider as an independent and identically distribution (i.i.d) Bernoulli random variable with

 ξi[k]={1with probabilityqi0with probability1−qii=1,2,…N (6)

for all , where is the probability that the system is observed at each time instant. As , we have . Then the stochastic scheduling strategy is that at each time instant a target (i.e., DTLTI system) is randomly chosen for measurements according to a pre-assigned probability distribution .
Notice that the error covariance is random as it depends on the randomly chosen sequence . Thus we need to evaluate the expected estimate error covariance in order to minimize the actual estimate error. Putting above together, we have the stochastic scheduling problem motivated by (5) as follows.

Stochastic Scheduling Problem

 μs=minqi,i=[1..N]maxiTr(limk→∞Eξi,k[Pi[k]])subject toEquation:(???),(???),N∑i=1qi=1,0≤qi≤1, (7)

where the expectation is w.r.t , which we denote by .

###### Theorem 1

If is invertible for , the deterministic scheduling performance in (5) is almost surely upper bounded by the stochastic scheduling performance in (7).

Proof. See Appendix.

###### Remark 2

While Problem (5) provides an important motivation, Problem (7) is relevant on its own right and can be applied without the restriction on being invertible.

### 2.2 Relaxation

Problem (7) involves the evolution of

 Eξi,k[Pi[k]]=AiEξi,k−1[Pi[k−1]]A′i+Qi−qiEξi,k−1[AiPi[k−1]C′i(CiPi[k−1]C′i+Ri)−1CiPi[k−1]A′i]

Unfortunately, the right-hand side of the above expression is not easily computable, as it involves the expectation w.r.t. , of a nonlinear recursive expression of . However, [24] has nicely shown that is upper bounded by the fixed point of the following associated MARE,

 MARE:Xi=AiXiA′i+Qi−qiAiXiC′i(CiXiC′i+Ri)−1CiXiA′i. (8)

This result motivates us to minimize as a means to keep itself small. Specifically, we consider the following optimization problem, denoted by OP, in the rest of the paper.

 OP: minqi,i=[1..N]maxiTr(Xi) subject to:N∑i=1qi=1,qci

where is an implicit function of , defined by and

 gqi(Xi)=AiXiA′i+Qi−qiAiXiC′i(CiXiC′i+Ri)−1CiXiA′i (10)
###### Remark 3

is the critical value depending on the unstable eigenvalues of , where the fixed point exists if and only if the assigned probability . We refer interested readers to [24, 25] for the details on . In this paper, we assume , otherwise the above optimization problem has no feasible solution, i.e., the upper bound turns out to be infinity. For stable systems, we always have .

Note that the searching space of the above optimization problem is continuous, and it will be shown that the problem is (quasi)-convex. In addition, based on Theorem 1, the objective value of the above problem is an upper bound on the performance of the deterministic scheduling problem (5). In the rest of the paper, we provide efficient distributed algorithms to obtain the optimal solutions of OP.

## 3 Minimization of The Maximal Estimate Error among Targets.

In this section, we first show that OP can be decoupled into convex optimization problems, which can be solved separately. Then by utilizing the classical consensus algorithm, we propose a distributed computing algorithm to obtain the optimal solution of OP. First of all, we recall some results on the MARE in [24] derived under the assumption .

###### Lemma 4

Fix , for any initial condition ,

 limk→∞g(k)q(X0)=limk→∞gq(gq(⋯gq(X0)))k=X

where is the unique positive-semidefinite fixed point of the MARE, namely, .

###### Lemma 5

For a given scalar and a DTLTI system as described in (2) and (2), the fixed point of the MARE presented in the form of (8) can be obtained by solving the following LMI problem.

 argmaxXTr(X)subject to[AXA′−X+Q√qAXC′√qCXA′CXC′+R]⪰0X⪰0. (11)
###### Lemma 6

Assume , and is controllable. Then the following facts are true.

1. if .

2. if .

3. if .

4. .

5. .

6. Define the linear operator

 Lq(Y)=(1−q)(AYA′)+qFYF′.

Suppose there exists such that . Then for all

 limk→∞L(k)q(W)=0

where

 Φq(K,X)=(1−q)(AXA′+Q)+q(A+KC)X(A+KC)′+qQ+qKRK′. (12)

Now we prove the monotonicity of the fixed point of the MARE, which will facilitate us to analyze OP.

###### Definition 7

(Matrix-monotonicity) A function : is matrix-monotonic if for all with , we have either or in the positive semidefinite cone .

###### Theorem 8

(Matrix-monotonicity of the MARE) For , the fixed point of the MARE is matrix-monotonically decreasing w.r.t the scalar .

Proof. Assume and , satisfying and . The existence of the fixed points and is guaranteed according to Lemma 4. We need to show . Since , by using Lemma 6(2) we have

 X1=gq1(X1)⪰gq2(X1).

By Lemma 6(1), we have

 X1⪰gq2(gq2(X1))⪰gq2(gq2(gq2(X1)))⪰…⪰g(k)q2(X1)

By the convergence property of the MARE (i.e., Lemma 4), we have by taking .

###### Remark 9

This theorem reveals an important message that, for any two different scalar and , the corresponding fixed points can be ordered in the positive semidefinite cone. In other words, for a given system model , the fixed points of the MARE w.r.t variable are comparable. As we will see, this property is the foundation for deriving algorithms to solve OP.

Now, we are ready to analyze and solve OP. For the ease of reading, we occasionally use notation to stress that is a function of , i.e., is the fixed point of the MARE w.r.t the scalar .

###### Corollary 10

Problem OP is a quasi-convex optimization problem.

Proof. Consider the cost function of OP. From Theorem 8, is monotonically non-increasing in , as the trace function is linear. Therefore, is a quasi-convex function, for each , due to the fact that any monotonic function is quasi-convex. Next, based on the fact that non-negative weighted maximum of quasi-convex functions preserves quasi-convexity, the result follows.

Next, we can rewrite problem OP in the following equivalent form

 minqi,i=[1..N],γ>0γsubjectto:Tr(Xi(qi))≤γ,∑Ni=1qi=1,qci

The problem is in principle solved by bisecting and checking the feasible set is not empty. However the constraint set is not in a useful form yet. For any fixed , the feasible set is convex but not easy to work with, given the implicit functions .

It is then convenient to consider the following related problem for a given .

 μ(γ)=minqi,i=[1..N]N∑i=1qisubject to:Tr(Xi(qi))≤γ,qci
###### Lemma 11

is feasible for Problem (13) if and only if Problem (14) is feasible and .

Proof. Let denote the set of ’s feasible for Problem (13).

Assume is not empty. Then feasible set of Problem (14) is not empty, and since we know that there are ’s such that , then . For the other direction, assume that . Then is not empty, and therefore is feasible for Problem (13). If , then let such that , and consider , for . Then, , , and because of Theorem 8. Thus, is not empty. Hence is feasible for Problem (13).
The cost of (14) is separable and the constraints are independent for each . Thus, for any , (14) can be solved by minimizing independent problems, namely:

 μ(γ)=N∑i=1minqiqisubject to:Tr(Xi(qi))≤γ,qci

It is easy to infer that in (15) is decreasing w.r.t. performance . Thus, OP can be solved by (15) using bisection on until .

We next concentrate on the subproblems:

 qopti(γ)=minqiqisubject to:Tr(Xi(qi))≤γ,qci

Based on Theorem 8, we see that the optimal solution of the problem (16) implies the smallest probability required for measuring system for achieving the pre-assigned estimate performance . If the problem (16) is not feasible (e.g. is too small), we set . Next, we show that the optimization problem (16) can be reformulated as the iteration of a Linear Matrix Inequality (LMI) feasibility problem. Without abuse of notation, we remove the subscript since the following results apply to all DTLTI dynamic systems.

###### Lemma 12

Assume that is controllable and is detectable. For any given and invertible matrices and , the following statements are equivalent:

1. such that .

2. and such that (defined in (12)).

3. and such that .

where

 (17)

Proof. . According to Lemma 6 (3), we have or with . Then since and the other terms are . Moreover,

 2¯X=2Φq(K¯X,¯X)=(1−q)A(2¯X)A′+q(A+K¯XC)(2¯X)(A+K¯XC)′+2Q+2qK¯XRK′¯X≻(1−q)A(2¯X)A′+q(A+K¯XC)(2¯X)(A+K¯XC)′+Q+qK¯XRK′¯X=Φq(K¯X,2¯X) (18)

The inequality follows from the fact that and . The proof is complete.
. If , the proof follows from Theorem in [24] with .
.

 X≻Φq(K,X)⇔X≻(1−q)AXA′+q(A+KC)X(A+KC)′+qKRK′+Q

Let and . Left and right multiply the above inequality by we have

 ⇔GXG≻(1−q)GAXA′G+q(GA+HC)X(GA+HC)′+qHRH′+GQG

By using Schur complement this is equivalent to (17).

###### Theorem 13

If is controllable and is detectable, the solution of the optimization problem (16) can be obtained by solving the following quasi-convex optimization problem in the variables .

 minq,H,G≻0,Y≻0qsubject toTr(Y)≤γ,i=1,2,…N[YIIG]⪰0Γq(G,H)≻0,qc

where is given by (17).

Proof. From the substitution of in Lemma 12, it is straightforward to obtain the following equivalent statements by the Schur complement.
such that .
such that and
such that and
From Lemma 12, we have the equivalence between and in terms of feasibility. For fixed , is a LMI in variables . Therefore, the problem (19) can be solved as a quasi-convex optimization problem by using bisection for variable .

In summary, we have shown the following

###### Theorem 14

Problem OP is equivalent to a quasi-convex optimization problem that can be solved by solving (15) using bisection on until within the desired accuracy. For each level , each of the independent subproblems (16) can be solved by solving (19) also using bisection for variable and iterating LMI feasibility problems.

### 3.1 Distributed solutions

Note that the steps of the outer bisection iteration are straightforward and can be done either by a centralized scheduler or in a distributed fashion. If a centralized scheduler/computing-unit is available, it can collect the from the estimators, check that their sums is less than or equal to one, and send back to the estimator an updated value of based on a bisection algorithm.

Alternatively, the estimators need to cooperate and agree on an optimal feasible . This can be done assuming the estimators are strongly connected via a network where the communications between any two estimators are error-free\@footnotemark\@footnotetextNote that the decentralized computing units are allowed to be allocated in a single fusion center or to be physically distributed in an area.. In this case, each estimator needs to obtain the value of by communicating with its neighbors. Under the assumption that is known to the estimators, can be obtained by a distributed averaging process in finite steps as shown in [26]. Then, by increasing or decreasing under a common bisection rule among estimators, the value of can be driven to and consequently OP is solved.

The above argument, leads to the following distributed computing algorithm, Algorithm 1, to solve OP. The inputs of the algorithm are global information assumed to be known by each estimator in prior. Denote as the optimal objective value of OP. To avoid cumbersome details and to save space, we present the algorithm under the assumption that the interval is selected to contain . i.e., we have at each step. Then the algorithm is guaranteed to converge to the optimal objective value within the desired tolerance.

## 4 Extensions and Special Cases.

In practical scenarios, some conditions/constraints might be of interest in the sensor scheduling problem. However, adding extra constraints on scheduling design is problematic in many existing scheduling strategies. Our stochastic scheduling approach can easily incorporate extra conditions/constaints, as shown through two specific examples next.

### 4.1 Prioritization of Certain Targets

For some reason, specific targets may require extra attention, (i.e., more precise estimation) from the sensor. Our model can incorporate this requirement by adding constraint where represents the assigned attention weight for target . Then we need to solve the following problem,

 minqi,i=[1..N]maxiTr(Xi)subject toXi=gqi(Xi),N∑i=1qi=1,qj≥αjqci

### 4.2 Measurement Loss in Sensing

In practice, measurement loss is a common phenomena due to various sources, e.g., shadowing, weather condition, large delay, etc. If the measurement loss probability for sensing -th target is known in prior, this extra condition can be easily incorporated in our model. Assume that ’s are pre-assigned to each target. Then the actual probability of reliably receiving measurements from -th target is because of measurement loss. Therefore, OP can be modified as follows,

 minqi,i=[1..N]maxiTr(Xi)subject toXi=gqi(1−τi)(Xi)N∑i=1qi=1qi(1−τi)>qci,qi≤1,i=1,2,…N (21)

With simple modifications, these two extended problems can be solved by the proposed distributed algorithms as well.

### 4.3 Closed-form Solutions to MARE for Special Cases

For the following special class of systems, the underlying MARE has a closed-form solution. Although this cannot be expected in general, it increases the computational efficiency of the proposed algorithm. Incidentally, this appears to the first non-trivial closed-form solution of the MARE in the literature.

Consider a set of DTLTI single-state systems to be measured evolving according to the equation

 xi[k+1]=aixi[k]+wi[k] (22)

where and the covariance of and are and , respectively. The measurement taken by the sensor at each time instant is formulated as follows,

 ~yi[k]=ξi[k](xi[k−di]+vi[k])

where represents the delay in measurement, which we assume to be fixed and known in this paper. By using augmented states to deal with delays, it is straightforward to have the following compact form for system with measurement delays,

 Xi[k+1]=AiXi[k]+Biwi[k]~yi[k]=ξi[k](CiXi[k]+vi[k]), (23)

where has the following structure

 Xi[k]=⎡⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢⎣x1i[k]x2i[k]⋮xdii[k]xi[k]⎤⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥⎦,Ai=⎡⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢⎣010⋯0001⋯0⋮⋱⋮000⋯1000⋯ai⎤⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥⎦,Bi=⎡⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢⎣00⋮01⎤⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥⎦ (24)
 Ci=[10⋯0].

Note that only is the true state of system at time instant while other states included in vector are dummy variables for handling delays. By exploiting the special structure of above model, we are able to obtain the closed-form fixed point of the MARE. We present this result in the following theorem.

###### Theorem 15

For a given , consider the MARE described as , where have the structure presented in (24), and with . Then the MARE has a unique positive-semidefinite fixed point as follows, if and ,

 X=⎡⎢ ⎢ ⎢ ⎢ ⎢⎣x1x1⋯x1x1x2⋯x2⋮⋮⋱⋮x1x2⋯xn⎤⎥ ⎥ ⎥ ⎥ ⎥⎦ (25)

where

 xj=Q+√Q2+4qQR2q+(j−1)Qj=1,2,⋯,n;

if and ,

 X=⎡⎢ ⎢ ⎢ ⎢ ⎢⎣x1ax1⋯an−1x1ax1x2⋯an−2x2⋮⋮⋱⋮an−1x1an−2x2⋯xn⎤⎥ ⎥ ⎥ ⎥ ⎥⎦ (26)

where

 x1=Ra2−R+Q+√(Ra2−R+Q)2−4(a2−1−a2q)QR2(1+a2q−a2)xj=a2(j−1)x1+1−a2(j−1)1−a2Qj=1,2,…,n;

if , MARE fails to converge to a steady state value.

The proof is tedious but straightforward by plugging in the above closed-form solution into the MARE. If , the results directly follows from [25].

Note that the stochastic upper bound in Theorem 1 may not hold since is not invertible. However, a deterministic scheduling sequence can be constructed based on the optimal stochastic solution in the next section, providing an upper bound on the original deterministic scheduling problem with good performance.

## 5 Scheduling Implementation

For completeness, in this section we consider the problem of scheduling implementation and present a simple approach to implement the scheduling sequence. For stochastic scheduling implementation, a central scheduler is required to construct a scheduling sequence by randomly selecting targets (via a random seed) according to the optimal probability distribution. Note that this construction process can be performed efficiently either off-line or on-line.

We next turn our attention back to a deterministic scheduling and look for one consistent with the the optimal stochastic solution. Note that the optimization problems are minimizing the average costs of all possible stochastic sequences. With the optimal stochastic solutions, we are able to randomly construct a sequence compatible with the distribution. However, in practice, such random-constructed scheduling sequence may result in undesirable performance. For example, one target may not be measured for a long consecutive time instants and its error covariance is temporarily built up. Thus, we would like to identify and use, among all possible stochastic sequences, those that have low costs. Motivated by the sensor scheduling literature, which suggests periodic solutions [27, 28], we define and look for deterministic sequences of minimal consecutiveness, defined next. These sequences are periodic and switch among targets most often compatibly with the optimal scheduling distribution. We remark that the approach we propose in this section is heuristic but it can be implemented in a distributed fashion and leads to good performance in simulations. We leave the analysis of this and other approaches to future research.

###### Definition 16

Let be a set of sequences with length , where each element in the sequence takes value from an element set and the number of occurrences of each value in the sequence is . Under these assumptions, then the sequence of minimal consecutiveness is the solution of the following optimization problem

 min{s[k]}Lk=1maxi,j∈{1,2,⋯,N}{j−i|j≥i,s[i]


text:
# Music with a Piezoelectric Buzzer

## Introduction

In this project, we will be generating sound using a piezoelectric buzzer. We will initially explore how to generate different frequencies by cycling a digital pin from HIGH to LOW at different rates. We will then examine some of the fundamentals of music theory and how they can help us play music with our buzzer.

## Inventory:

Qty Description Typical Image Schematic Symbol Breadboard Image
1 Piezoelectric buzzer

## How a Piezoelectric Buzzer Works

When generating sound using electronics, the first component that comes to mind is a speaker. Most speakers consist of two electromagnetic coils, called “voice coils”. One of the coils is attached to a flexible material called the speaker cone. When current is applied to the voice coils, an electromagnetic field is generated. The force generated between the fields moves coils which in turn makes the speaker cone vibrate. We perceive these vibrations in the air as sound.

The piezoelectric buzzer works very similarly, except it does not use electromagnets. Instead, it makes use of a material that has piezoelectric properties. When a material is piezoelectric, it means that applying mechanical force (i.e., bending or squeezing it) will cause it to gain charge. Inversely, applying an electric charge will cause the material to stretch or expand a very small amount. By pulsing our buzzer on and off we make the piezoelectric material inside quickly expand and contract. This produces the vibrations we hear in the air.

Piezoelectric materials found in most devices usually consist of crystals or special ceramics. Some biological materials like bone, DNA, and certain proteins also exhibit the same behavior. Typically, crystals and ceramics are used in most piezoelectric devices. The piezoelectric properties of quartz crystal is often taken advantage of to make the sparkers found in gas stoves. Quartz is also used in crystal oscillators, which aid in controlling the timing of computers and some wrist watches. Piezoelectric materials can even be used to build sensors like microphones or guitar pickups. In this project, we will be using a piezoelectric buzzer as a rudimentary speaker.

## Setting up the Circuit

The circuit setup in this project will be very simple. The only component we will need is the buzzer, which we will hook directly to the chipKIT™ board. The only catch is that the buzzer has a polarity. Figure 1 illustrates the polarity convention for the buzzer where the anode is closest to the square sound port. Figure 2 depicts the schematic diagram of the circuit. To construct the circuit, follow the steps illustrated in Fig. 3.

1. Place the buzzer in the breadboard. Be sure to keep track of what node each leg is in. The legs are not visible when the buzzer is securely in place. If you forget, you can tilt the buzzer without removing it to see what node each leg occupies.
2. Connect the buzzer's cathode to ground.
3. Connect the buzzer's anode to pin 4.

## Frequency and Types of Waves

To be able to generate music, we need to be able to play different notes. A specific note is determined by the frequency at which it is played. We will write a function to play various notes, but first we must understand what determines a wave's frequency.

The frequency of a wave tells us how often it repeats within a specific unit of time. One repetition of a wave is referred to as a “cycle” The number of cycles in one second is equivalent to a wave's frequency in hertz (Hz). Measuring waves in hertz makes sense since it gives us a good idea of how quickly the wave repeats. For example, a 1 Hz wave will repeat once every second, which seems fast to us. On the other hand, a 500 Hz wave will repeat five hundred times in one second, which is much faster in comparison. The time it takes for one cycle of a wave to occur is referred to as the “period.” We will be controlling the frequency of the sound waves we generate by changing their periods. The following equation will come in handy for relating the period of a wave to its frequency. Note that f is the frequency and T is the period.

$\large f = \frac{1}{T}$

With the equation above, we can calculate the period needed to produce a wave. How the voltage changes during each period, whether it is a smooth curve or an abrupt edge, determines what type of wave it is. Figure 4 illustrates how a wave's shape, cycle, period, and frequency all relate to produce specific waveforms and frequencies.

Up until now we have primarily been using “square waves” with the chipKIT because they are the easiest to generate. Generating a square wave is simply a matter of switching a pin from HIGH to LOW with the proper timing. This is unlike most sound waves which consist of smooth sinusoids, such as cosine and sine waves. Due to their curves, sinusoids are difficult for digital devices to generate, so for this project we will stick to using a square wave. As a consequence, the tones we generate will sound a bit different than tones played using a sinusoidal wave. In fact, each waveform shown in Fig. 4. sounds slightly different. The sound of each waveform becomes increasingly “buzzier” going from top to bottom. The buzz of a waveform becomes very apparent at low frequencies, and is more noticeable because our brains have time to pick out the sharp edges. This becomes clear when you play a square wave at a very low frequency since it sounds more like repetitive clicking than a buzz. If you were to increase the frequency of the square wave, your brain would not be able to keep up. This causes the clicking sounds to blend together into a buzzy tone. We will explore this phenomenon more in the next section when we program the chipKIT to play different frequencies.

## Writing the Frequency Control Sketch

The code to play a desired frequency is fairly straightforward. We will write a function playFreq() that plays a frequency in hertz for a specified number of milliseconds. Our playFreq() function will take three arguments, int buzzerPin, double freqHz, and int durationMs . The input frequency will be a double type because it allows us to play exact decimal frequencies.

The first operation our function needs to do is to convert the argument freqHz into the correct period. If you recall, the equation introduced in the previous section tells us the frequency given the period. Doing some simple algebra gives us a new equation that tells us the period given the frequency.

$\large T = \frac{1}{f}$

Unfortunately, this equation gives us the period in seconds while the chipKIT only measures in either milliseconds or microseconds. We will want to measure our wave's period in microseconds since a period measured in milliseconds will not be precise enough to accurately represent decimal frequencies. This inaccuracy is due to the fact that the delay functions only accept int values, causing some precision to be lost.

For example, to find the period of a 2.3 Hz frequency in milliseconds, you would simply multiply the above equation by 1000 to convert to milliseconds, like so:

$\frac{1}{2.3 \ Hz}$ × 1000 = 434.782 ms

Now type casting the value to an int, you can see the value is truncated to 434 ms.

int( 434.782) = 434 ms

Similarly, to find the period in microseconds, you would multiply by 1,000,000.

• $\frac{1}{2.3 \ Hz}$ × 1000000 = 434782.608µs
• int( = 434782.608) = 434782 µs
• ($434782 \mu s \Leftrightarrow 434.783 ms$)

Ultimately, this means we will lose negligible number precision if we measure our period in microseconds. The frequency to period conversion code will look like the following:

                  int periodMicro = int((1/freqHz)*1000000);

With the correct period calculations done, all we need to do is repeatedly drive a pin HIGH and LOW with a bit of delay in between. Looking back at Fig. 4, it is easy to see that the square wave is HIGH for half of its period and LOW for the other half. This means we will delay for half of the calculated period in between each pin transition.

Next we need to figure out how to repetitively change the pin value while keeping track of the time. A while() loop comparing the proper values will accomplish this quite nicely. The elapsed playtime can be calculated by storing the start time (just before the while() loop is called), and subtracting the current time from it. This can then be compared to the desired play duration.

Now that we are finished writing our playFreq() function, we will test it by playing 6 frequencies (from 1 to 10,000 Hz) for a duration of two seconds with a half second pause between each. The play and pause durations are controlled by the playTimeMs and pauseTimeMs variables and can be easily adjusted if need be. Overall, the final frequency control test sketch will look as follows:

                  int buzzerPin = 4;
void setup()
{
pinMode(buzzerPin,OUTPUT);
int playTimeMs = 2000;//time to play frequency in milliseconds
int pauseTimeMs = 500;//time to pause between each frequency in milliseconds

playFreq(buzzerPin,1, playTimeMs);
delay(pauseTimeMs);

playFreq(buzzerPin,50, playTimeMs);
delay(pauseTimeMs);

playFreq(buzzerPin,100, playTimeMs);
delay(pauseTimeMs);

playFreq(buzzerPin,1000, playTimeMs);
delay(pauseTimeMs);

playFreq(buzzerPin,5000, playTimeMs);
delay(pauseTimeMs);

playFreq(buzzerPin,10000, playTimeMs);
delay(pauseTimeMs);
}

void playFreq(double freqHz, int durationMs)
{
//Calculate the period in microseconds
int periodMicro = int((1/freqHz)*1000000);
int halfPeriod = periodMicro/2;

//store start time
int startTime = millis();

//(millis() - startTime) is elapsed play time
while ((millis() - startTime) < durationMs)
{
digitalWrite(buzzerPin, HIGH);
delayMicroseconds(halfPeriod);
digitalWrite(buzzerPin, LOW);
delayMicroseconds(halfPeriod);
}

}

void loop()
{

}

## Playing Basic Music

In this section, we will begin to delve into how to make our chipKIT play simple songs. This portion of the project requires that you understand some basic music theory (i.e., musical notes, octaves, sharp notes). You must also be familiar with how to use arrays in your code. If you are unfamiliar with either of these topics, read through the related material by clicking the appropriate tab on the right. The song we will be playing with our buzzer is the 1985 Super Mario Bros® main theme. Specifically, we will only play the melody since playing multiple notes simultaneously is complicated.

The first operation our function needs to do is to convert the argument freqHz into the correct period. If you recall, the equation introduced in the previous section tells us the frequency given the period. Doing some simple algebra gives us a new equation that tells us the period given the frequency.

## Storing Note Frequencies

In order to play a song, we need to have access to any of the possible notes that will be in the song. Let's consider how we are going to store the frequencies of the notes we want to play. When referring to notes on a piano, there are 7 major octaves. In each octave, there are 12 total notes. That means there are 84 notes in all, which is a lot of frequencies to keep track of! To organize all of these frequencies, we will use two-dimensional arrays. Each row of the array (the vertical index) will correspond to one of the seven octaves. Each column of the array (the horizontal index) will correspond to each of the note frequencies contained in that octave. To help organize things further, we will store the regular notes of each octave in an array named octaves[7][7] and the sharp notes in an array named sharpOctaves[7][5]. Since there are only five sharp notes per octave, sharpOctaves[7][5] will only have five columns. Both of the arrays should look as follows.

				//Store all note frequencies for each octave in a 2 dimensional array
double octaves[7][7] =
{
//Octave1 Notes:      c1      d1      e1      f1      g1      a1      b1
/* 1st octave */   {32.703, 36.708, 41.203, 43.654, 48.990, 55.000, 61.735},

//Octave2 Notes:      c2      d2      e2      f2      g2       a2       b2
/* 2nd octave */   {65.406, 73.416, 82.407, 87.307, 97.999, 110.000, 123.470},

//Octave3 Notes:       c3       d3       e3       f3       g3       a3       b3
/* 3rd octave */   {130.810, 146.830, 164.810, 174.610, 196.000, 220.000, 246.940},

//Octave4 Notes:       c4       d4       e4       f4       g4       a4       b4
/* 4th octave */   {261.630, 293.660, 329.630, 349.230, 392.000, 440.000, 493.880},

//Octave5 Notes:       c5       d5       e5       f5       g5       a5       b5
/* 5th octave */   {523.250, 587.330, 659.250, 698.460, 783.990, 880.000, 987.770},

//Octave6 Notes:        c6        d6        e6        f6        g6        a6        b6
/* 6th octave */   {1046.500, 1174.700, 1318.500, 1396.900, 1568.000, 1760.000, 1979.500},

//Octave7 Notes:        c7        d7        e7        f7        g7        a7        b7
/* 7th octave */   {2093.000, 2349.300, 2637.000, 2793.800, 3136.000, 3520.000, 3951.100}
};

//Store the sharp note frequencies for each octave in a 2 dimensional array
double sharpOctaves[7][5] =
{
//Octave1 Sharps:     C1      D1      F1      G1      A1
/* 1st octave */   {34.648, 38.891, 46.249, 51.913, 58.270},

//Octave2 Sharps:     C2      D2      F2       G2       A2
/* 2nd octave */   {69.296, 77.782, 92.499, 103.830, 116.540},

//Octave3 Sharps:      C3       D3       F3       G3       A3
/* 3rd octave */   {138.590, 155.560, 185.000, 207.650, 233.080},

//Octave4 Sharps:      C4       D4       F4       G4       A4
/* 4th octave */   {277.184, 311.130, 369.990, 415.300, 466.160},

//Octave5 Sharps:      C5       D5       F5       G5       A5
/* 5th octave */   {554.370, 622.250, 739.990, 830.610, 932.330},

//Octave6 Sharps:       C6        D6        F6        G6        A6
/* 6th octave */   {1108.700, 1244.500, 1480.000, 1661.200, 1864.700},

//Octave7 Sharps:       C7        D7        F7        G7        A7
/* 7th octave */   {2217.500, 2489.000, 2960.000, 3322.400, 3729.300}
};

You may have noticed in the previous code box that each note frequency is labelled with its note letter followed by its octave number. You may have also noticed that the sharp notes are labelled with capital letters while the regular notes are labelled with lower case letters. This provides a quick and easy way to differentiate a sharp from a regular note when in character form. It also brings us to our next challenge: How to represent a melody within MPIDE.

## Representing a Melody in MPIDE

Our next task is thinking of a way to conveniently represent a song within MPIDE. Specifically, what we need to do is determine how to organize and represent the individual musical components of a melody. To do so, let's take a moment and list out what these key components are.

1. Regular notes
2. Sharp notes
3. Pauses in the song
4. The duration of each note/pause.

Since most notes are referred to with letters and numbers, it makes sense to use combinations of characters to represent these four key components. As you may already know, the most convenient way of grouping characters in a program is with String object. If you are unfamiliar with how Strings work, follow the yellow tab on the right. To represent one line in a song we will use one span String. The String will contain character combinations that we will decode with other functions later on. The details of what these character combinations are, and how they should be handled are described in the following sub sections.

#### Regular Notes:

To represent a regular note, we will simply use the note's lower case letter followed by its octave number. This will match the convention we previously established when organizing and labelling our 2d note arrays.

Ex. c5, a2, b3

#### Sharp Notes:

To represent a sharp note, we will simply use the note's upper case letter followed by its octave number. Again, this will match the convention we previously established when organizing and labelling our 2d note arrays.

Ex. C5, A2, B3

#### Pauses:

To represent pauses in the song, we will use a dash followed by an equal symbol (“-=”). This will make pauses easy to type as well as easy to count. We will assume a pause lasts as long as a note, unless otherwise specified.

Ex. -=

#### Note Length and the Length Modifier:

Next we need a method for representing a note's length. To streamline our design, we will assume a note is a default length unless otherwise specified. This will work well since the majority of notes (and pauses) in a song typically have the same length. For this particular melody, most of the notes are quarter notes (this was determined from the sheet music). So in our scheme we will assume by default a note should be played as a quarter note.

If we want to change the play length of a note, we will use a length modifier. By convention, the modifier will appear before the note it is modifying. The modifier will consist of an exclamation point followed by a number (ex. “!1”). The number in the modifier will correspond to a location in an array which contains the alternative note length. In practice, the modifier will work as follows.

Consider the following code:

					  //the typical length notes in the song are quarter notes
double typicalNoteLength = 0.25;

//store the modified note lengths for the song
double newNoteLength[ ] = {0.5, 0.125};

String songLine = "a1b2!0c3-=d5!1-=";

When playing songLine above, most notes will be read as a quarter note by default. This is why typicalNoteLength is set to 0.25. The note “c3”, however, will be played as a half note. This is because it's preceded by the length modifier “!0”. The zero in the modifier corresponds to the 0th element (0.5) in the array newNoteLength. The next modifier to appear in the String is “!1”. It is modifying the length of the last pause “-=”. The final pause will have the duration of an eighth note since the 1 in the modifier corresponds to the 1st element (0.125) in the newNoteLength array.

Now that we have established a structure and a character scheme for each song, we can begin to piece it together. The convenient way to represent an entire song or melody will be to use an array of Strings. Remember, think of each String in the array as a line for the song. To play the entire song, you simply have to loop through and grab each String. Once you have obtained the String, you can simply call the function that will decode and play the notes for that line. Overall, our representation for an entire melody will look as follows.

					  // the tempo is 100 whole notes per minute
int tempo = 100;

//the typical length notes in the song are quarter notes
double typicalNoteLength = 0.25;

//store the modified note lengths for the song
double newNoteLength[ ] = {0.0167, 0.3333};

String fullMelody[ ] =
{
"e5!0-=e5-=e5   -=c5e5-=  g5-=-=-= g4-=-=-=",
"c5-=-=g4 -=-=e4-= -=a4-=b4 -=A4a4-=",
"!1g4!1e5!1g5 a5-=f5g5 -=e5-=c5 d5b4-=-=",
"c5-=-=g4 -=-=e4-= -=a4-=b4 -=A4a4-=",
"!1g4!1e5!1g5 a5-=f5g5 -=e5-=c5 d5b4-=-=",
"-=-=g5F5 f5D5-=e5 -=G4a4c5 -=a4c5d5",
"-=-=g5F5 f5D5-=e5 -=c6-=c6 c6-=-=-=",
"-=-=g5F5 f5D5-=e5 -=G4a4c5 -=a4c5d5",
"-=-=D5-= -=d5-=-= c5-=-=-= -=-=-=-=",
"-=-=g5F5 f5D5-=e5 -=G4a4c5 -=a4c5d5",
"-=-=g5F5 f5D5-=e5 -=c6-=c6 c6-=-=-=",
"-=-=g5F5 f5D5-=e5 -=G4a4c5 -=a4c5d5",
"-=-=D5-= -=d5-=-= c5-=-=-= -=-=-=-=",
"c5c5-=c5 -=c5d5-= e5c5-=a4 g4-=-=-=",
"c5c5-=c5 -=c5d5e5 -=-=-=-= -=-=-=-=",
"c5c5-=c5 -=c5d5-= e5c5-=a4 g4-=-=-=",
"e5e5-=e5 -=c5e5-= g5-=-=-= g4-=-=-=",
"c5-=-=g4 -=-=e4-= -=a4-=b4 -=A4a4-=",
"!1g4!1e5!1g5 a5-=f5g5 -=e5-=c5 d5b4-=-=",
"c5-=-=g4 -=-=e4-= -=a4-=b4 -=A4a4-=",
"!1g4!1e5!1g5 a5-=f5g5 -=e5-=c5 d5b4-=-=",
"e5c5-=g4 -=-=G4-= a4f5-=f5 a4-=-=-=",
"!1b4!1a5!1a5 !1a5!1g5!1f5 e5c5-=a4 g4-=-=-=",
"e5c5-=g4 -=-=G4-= a4f5-=f5 a4-=-=-=",
"b4f5-=f5 !1f5!1e5!1d5 c5e4-=e4 c4-=-=-="
};

You may have noticed that a tempo variable has been added to our song representation. This is because it will be needed later on, along with the note length, to calculate the note's duration in milliseconds. The tempo was derived from the original sheet music and can be used to make the song play slower or faster without having to modify the various note lengths that have been stored. Another previously unmentioned addition to our melody is the white space between notes. This was added strictly for organizational purposes. The white space helps illustrate that each line contains exactly 4 groups of notes. Within each group there are only 4 notes, including pauses. Any ! modifiers do not count as a note, so some groups appear to be longer than others. Breaking the notes of a line into groups helps make the song more readable. It also makes it easier to translate sheet music to our scheme. Eventually the organizational white space will be stripped from each song line so it is easily decoded.

## Writing the Functions to Play a Melody

With an idea of how our melody will be structured, we can begin writing the functions necessary to decode and play it. While writing these functions, we are going to use a top down coding approach. This means as we run into challenges we will imagine up new sub-functions to solve these problems. We will not be concerned with writing these sub-functions until later. With this approach you can divide up the work. Once you have written all of your necessary functions, you can start testing and fixing each function from the bottom up. The bottommost functions (the ones that contain no other sub-functions) are typically small and easy to understand. Once you ensure these bottommost functions are working how you want, you can move up and test the function that calls them. Since you have already tested and verified the sub-function, you can rule them out as a potential cause for any problems and focus on fixing your current function.

#### playMelody()

To begin our top down approach, we will write a function called playMelody(). This function will simply use a for loop to loop through and decode/play each String stored in the fullMelody array. The details of decoding and playing the notes in each String will be handled by a sub-function called playLine(). We will go over the details of playLine() in a moment. For now, the complete playMelody() is shown below.

					void playMelody(String song[ ], double typicalNoteLength, int tempo, double newNoteLength[ ], int numLines)
{
//Loop through and play each line of song
for(int i = 0; i < numLines; i++)
{
playLine(song[i], typicalNoteLength, tempo, newNoteLength);
}
}

#### playLine()

Our next task is implementing the sub-function playLine(). This function can be a bit difficult to understand, so the completed function is shown below for reference. Referring back to the completed function as you read the description may make it easier to follow.

				void playLine(String songLine, double typicalNoteLength, int tempo, double newNoteLength[])
{
//remove spaces from song
String lineNotes = removeWhiteSpace(songLine);

for( int i = 0; i < lineNotes.length(); i+=2)
{
//get the current note to be played
char noteLetter = lineNotes[i];

//get octave number of note to be played
char noteNum = lineNotes[i+1];

//convert noteDigit from char to int so it can be used as an  array index
int noteOctaveNum = charToDigit(noteNum);

//declare noteLengthMs before if statement
int noteLengthMs;

//Check to see if the typical note length or a modified note length should be used to play the next note
if(noteLetter == '!')//use modified note length
{

//Calculate the notes length in milliseconds (for modified note lengths)
noteLengthMs = noteLengthToMs(newNoteLength[noteOctaveNum], tempo);

i+=2;//increment index to grab the note following the "!0" length modifier
noteLetter = lineNotes[i];

//get octave number of note to be played after "!0" length modifier
noteNum = lineNotes[i+1];
//convert noteDigit from char to int so it can be used as an  array index
noteOctaveNum = charToDigit(noteNum);

}
else//use typical note length
{
//Calculate the notes length in milliseconds (for typical note lengths)
noteLengthMs = noteLengthToMs(typicalNoteLength, tempo);
}

playNote(noteLetter, noteOctaveNum ,noteLengthMs);
}
}

Inside of playLine(), the first thing we want to do is remove the spaces we've added to the song lines. To do so, let's assume we have a sub-function called removeWhiteSpace() that removes all the spaces in a string. It will do as its name implies and store the resulting String in the variable String lineNotes.

Next, we will grab the letter of each note from lineNotes using a for loop. The for loop's counter will act as the index of the String lineNotes. This works because the characters in a String object can be accessed the same way as the elements of an array. The note character obtained from lineNotes will be stored in the variable char noteLetter for later use. Similarly, the note's numerical character will be obtained from lineNotes by using the index i+1. This numerical character will be stored in the variable char noteNum. Remember that the numeric character in our scheme corresponds to the octave of the note in question. Later on when we want to select the correct row in our 2d octave arrays, we will need to use an integer as the index. So we will assume we have a sub-function called charToDigit() that converts a numerical character to is integer equivalent. In this case, charToDigit() will store its resulting value in a variable called noteOctaveNum.

Now that we have the character and octave number of the note we want to play, we will check and make sure that the note wasn't actually a “!” modifier. Using noteLetter == '!' as the argument for an if statement will accomplish this. Now there are two possible outcomes for the if statement.

1. noteLetter is not a '!'.

This means we should use the default note length to calculate the notes duration in milliseconds.

2. noteLetter is an '!'.

This means we must calculate the notes duration in milliseconds based one of the alternative note lengths stored in the newNoteLengtharray.

Assuming the 1st possible outcome occurs, we will use a sub-function called noteLengthToMs() to calculate the note's duration in milliseconds. It will be called as follows: noteLengthMs = noteLengthToMs(typicalNoteLength, tempo) Assuming the 2nd possible outcome occurs, then we will call noteLengthToMs() as follows: noteLengthMs = noteLengthToMs(newNoteLength[noteOctaveNum], tempo). Note that newNoteLength[noteOctaveNum] has replaced typicalNoteLength in the arguments. Recall newNoteLength is an array which stores alternative note lengths. After calculating the modified note duration, we must grab the characters of the note that is being modified. This is done by incrementing the for loops counter by i+=2 and storing the next characters in noteLetter and noteNum. After the proper note duration has sorted out with either case of the if statement, we can actually play the note. To do so, we will use a sub-function called playNote that will play the correct frequency for the correct period of time.

#### removeWhiteSpace()

Now we will start defining the sub-functions of playLine(). The first of these is removeWhiteSpace(). The code for this function will simply consist of a for loop that loops through every character of the String. Any character that is not a space will be concatenated in a temporary String. The function will then return the temporary String. Here is what removeWhiteSpace() looks like:

                  String removeWhiteSpace(String input)
{
String temp = "";
for(int i = 0; i < input.length(); i++)
{
if(input[i] != ' ')
{
temp = temp+input[i];
}
}
return temp;
}

#### charToDigit()

The second sub-function of playLine() we will define is charToDigit(). This function is very short but requires some explanation. The function in its entirety is shown below.

                  int charToDigit(char character)
{
return character - '0';
}

Although the function is very short, the operation it performs is odd. Subtracting two characters doesn't really make sense to a person, but it makes perfect sense to a computer. This is because every character has an associated numeric value. In most programming languages characters are assigned these values based on the ASCII standard. When you tell a computer to subtract two characters it is actually subtracting the ASCII value of those characters.

For example:

• The ASCII value of 'A' is 65
• The ASCII value of 'B' is 66
• So 'A' - 'B'= 1

In our sketch the whole point of subtracting characters is to convert the char digits '0' through '9' to their integer equivalent. Unfortunately, their ASCII values do not match the number represented. Instead, ASCII maps the characters '0' through '9' to the values 48 through 57. This is the reason we must subtract '0' and cannot convert the digits value directly.

For example:

• The ASCII value of '0' is 48
• The ASCII value of '1' is 49
• The ASCII value of '8' is 56
• The ASCII value of '9' is 57

So:

• '1' - '0' = 1
• '8' - '0' = 8
• '9' - '0' = 9

In terms of ASCII values that is:

• 49 - 48 = 1
• 56 - 48 = 8
• 57 - 48 = 9

#### noteLengthToMs()

The third sub-function of playLine() we will define is noteLengthToMs(). The function essentially calculates the duration of a whole note in milliseconds based on the tempo, and then multiplies it by the note length. With the comments, this function is fairly self-explanatory.

					/*Converts tempo based note length (full note, 1/2 note, 1/4 note ect..)
to the notes play length in milliseconds*/
int noteLengthToMs(double noteLen ,int tempo)
{
//Convert tempo from notes per minute to notes per second
double notesPerSecond = tempo/60.0;

//Calculate the length of one whole note in milliseconds
int wholeNoteMs = 1000/notesPerSecond;

//Calculate the length of note (whole, 1/2, 1/4 ect) in milliseconds
return wholeNoteMs*noteLen;
}

#### playNote()

The final sub-function of playLine() we must define is playNote(). The core of playNote() will be an ifelse tree. The ifelse will be used to determine whether the note being played is a pause, a sharp, or a regular note.

If the note is a pause, then we will simply delay for the pause's length. If the note is not a pause, then we will check to see if the note is a sharp using the predefined function isupper(). The function isupper() takes one char as an argument and returns true when that character is upper case. Once we have determined that we are dealing with a sharp note, we must obtain the corresponding frequency from the sharpOctaves array. To do so, we will need to calculate the index that corresponds to that note's frequency.

To get the array index for the sharp notes letter, let's assume we have a sub-function sharpToIndex() that solves our problem. sharpToIndex() will store the value it returns to the variable noteFreqIndex. Next, we need to calculate the index for the sharp note's octave. The index for a given position in an array is X-1, so to access the proper octave we must subtract one from the number we are given. The resulting number will be stored in the variable octaveIndex. Once we have both of the indices, we will use freq = sharpOctaves[octaveIndex][noteFreqIndex] to obtain the note's frequency. Now that the frequency has been obtained, we will use the old playFreq() to play the actual note.

The final possibility in the aforementioned ifelse tree is that a regular note needs to be played. In this case, the code will look very similar to the code used to play a sharp note. The primary difference will be that we will use the sub-function noteToIndex() to store the result to noteFreqIndex. Also, once we have both of the indices, we will use freq = octaves[octaveIndex][noteFreqIndex] to obtain the note's frequency. Overall, this function should look as follows.

					void playNote(char note, int noteOctaveNum ,int noteLengthMs)
{
int noteFreqIndex;
int octaveIndex;
double freq;
if(note == '-')
{
//Play nothing
delay(noteLengthMs);
}
else if(isupper(note))
{
//Convert the sharp note letter to an array index
noteFreqIndex = sharpToIndex(note);

//Convert octave number to an array index
octaveIndex = noteOctaveNum - 1;

//Use indices to retrieve  corresponding frequency from the array
freq = sharpOctaves[octaveIndex][noteFreqIndex];
playFreq(freq, noteLengthMs);
}
else
{
//Convert the note letter to an array index
noteFreqIndex = noteToIndex(note);

//Convert octave number to an array index
octaveIndex = noteOctaveNum - 1;

//Obtain note frequency
freq = octaves[octaveIndex][noteFreqIndex];
playFreq(freq, noteLengthMs);
}
}

#### sharpToIndex()

With playNote() complete, we can begin writing its sub-functions. The first is going to be sharpToIndex(). This function uses a switch statement to convert the correct capital note letter (C,D,F,G, or A) to the correct array index (1,2,3,4). The switch statement's default case will play an error tone for 225 milliseconds if the note's character doesn't match any of the cases. This will be helpful for catching typos made when translating the sheet music of the song.

					int sharpToIndex(char note)
{
switch(note)
{
case 'C':
return 0;
break;
case 'D':
return 1;
break;
case 'F':
return 2;
break;
case 'G':
return 3;
break;
case 'A':
return 4;
break;
default:
//Plays a error tone if none of the note letters match
playFreq(6000, 225);
}
}

#### noteToIndex()

The last function we need to write is noteToIndex(). It will be very similar to sharpToIndex() except it will check for lower case letters and have 6 possible indices it can return. Just as in sharpToIndex(), the default case will play an error tone for 225 milliseconds to catch any typos in the song.

					int sharpToIndex(char note)
{
switch(note)
{
case 'C':
return 0;
break;
case 'D':
return 1;
break;
case 'F':
return 2;
break;
case 'G':
return 3;
break;
case 'A':
return 4;
break;
default:
//Plays a error tone if none of the note letters match
playFreq(6000, 225);
}
}

## Putting it all Together

With all the functions written, we can finally combine them into one sketch, as shown below. Be aware that in the setup() function, just below the String fullMelody definition, there is an additional line.

					/*calculate the number of lines in melody array
THIS MUST BE DONE IN SAME SCOPE AS ARRAY DEFENITON*/
int numLines = sizeof(fullMelody)/sizeof(fullMelody[0]);

This bit of code is used to automatically calculate the number of lines (elements) in our fullMelody array. For details about calculating the number of elements in an array, follow the orange tab near the top of the page.

				//Store all note frequencies for each octave in a 2 dimensional array
double octaves[7][7] =
{
//Octave1 Notes:      c1      d1      e1      f1      g1      a1      b1
/* 1st octave */   {32.703, 36.708, 41.203, 43.654, 48.990, 55.000, 61.735},

//Octave2 Notes:      c2      d2      e2      f2      g2       a2       b2
/* 2nd octave */   {65.406, 73.416, 82.407, 87.307, 97.999, 110.000, 123.470},

//Octave3 Notes:       c3       d3       e3       f3       g3       a3       b3
/* 3rd octave */   {130.810, 146.830, 164.810, 174.610, 196.000, 220.000, 246.940},

//Octave4 Notes:       c4       d4       e4       f4       g4       a4       b4
/* 4th octave */   {261.630, 293.660, 329.630, 349.230, 392.000, 440.000, 493.880},

//Octave5 Notes:       c5       d5       e5       f5       g5       a5       b5
/* 5th octave */   {523.250, 587.330, 659.250, 698.460, 783.990, 880.000, 987.770},

//Octave6 Notes:        c6        d6        e6        f6        g6        a6        b6
/* 6th octave */   {1046.500, 1174.700, 1318.500, 1396.900, 1568.000, 1760.000, 1979.500},

//Octave7 Notes:        c7        d7        e7        f7        g7        a7        b7
/* 7th octave */   {2093.000, 2349.300, 2637.000, 2793.800, 3136.000, 3520.000, 3951.100}
};

//Store the sharp note frequencies for each octave in a 2 dimensional array
double sharpOctaves[7][5] =
{
//Octave1 Sharps:     C1      D1      F1      G1      A1
/* 1st octave */   {34.648, 38.891, 46.249, 51.913, 58.270},

//Octave2 Sharps:     C2      D2      F2       G2       A2
/* 2nd octave */   {69.296, 77.782, 92.499, 103.830, 116.540},

//Octave3 Sharps:      C3       D3       F3       G3       A3
/* 3rd octave */   {138.590, 155.560, 185.000, 207.650, 233.080},

//Octave4 Sharps:      C4       D4       F4       G4       A4
/* 4th octave */   {227.180, 311.130, 369.990, 415.300, 466.160},

//Octave5 Sharps:      C5       D5       F5       G5       A5
/* 5th octave */   {554.370, 622.250, 739.990, 830.610, 932.330},

//Octave6 Sharps:       C6        D6        F6        G6        A6
/* 6th octave */   {1108.700, 1244.500, 1480.000, 1661.200, 1864.700},

//Octave7 Sharps:       C7        D7        F7        G7        A7
/* 7th octave */   {2217.500, 2489.000, 2960.000, 3322.400, 3729.300}
};

int buzzerPin = 4;

void setup()
{
pinMode(buzzerPin,OUTPUT);

// the tempo is 100 whole notes per minute
int tempo = 100;

//the typical length notes in the song are quarter notes
double typicalNoteLength = 0.25;

//store the modified note lengths for the song
double newNoteLength[ ] = {0.0167, 0.3333};

String fullMelody[ ] =
{
"e5!0-=e5-=e5   -=c5e5-=  g5-=-=-= g4-=-=-=",
"c5-=-=g4 -=-=e4-= -=a4-=b4 -=A4a4-=",
"!1g4!1e5!1g5 a5-=f5g5 -=e5-=c5 d5b4-=-=",
"c5-=-=g4 -=-=e4-= -=a4-=b4 -=A4a4-=",
"!1g4!1e5!1g5 a5-=f5g5 -=e5-=c5 d5b4-=-=",
"-=-=g5F5 f5D5-=e5 -=G4a4c5 -=a4c5d5",
"-=-=g5F5 f5D5-=e5 -=c6-=c6 c6-=-=-=",
"-=-=g5F5 f5D5-=e5 -=G4a4c5 -=a4c5d5",
"-=-=D5-= -=d5-=-= c5-=-=-= -=-=-=-=",
"-=-=g5F5 f5D5-=e5 -=G4a4c5 -=a4c5d5",
"-=-=g5F5 f5D5-=e5 -=c6-=c6 c6-=-=-=",
"-=-=g5F5 f5D5-=e5 -=G4a4c5 -=a4c5d5",
"-=-=D5-= -=d5-=-= c5-=-=-= -=-=-=-=",
"c5c5-=c5 -=c5d5-= e5c5-=a4 g4-=-=-=",
"c5c5-=c5 -=c5d5e5 -=-=-=-= -=-=-=-=",
"c5c5-=c5 -=c5d5-= e5c5-=a4 g4-=-=-=",
"e5e5-=e5 -=c5e5-= g5-=-=-= g4-=-=-=",
"c5-=-=g4 -=-=e4-= -=a4-=b4 -=A4a4-=",
"!1g4!1e5!1g5 a5-=f5g5 -=e5-=c5 d5b4-=-=",
"c5-=-=g4 -=-=e4-= -=a4-=b4 -=A4a4-=",
"!1g4!1e5!1g5 a5-=f5g5 -=e5-=c5 d5b4-=-=",
"e5c5-=g4 -=-=G4-= a4f5-=f5 a4-=-=-=",
"!1b4!1a5!1a5 !1a5!1g5!1f5 e5c5-=a4 g4-=-=-=",
"e5c5-=g4 -=-=G4-= a4f5-=f5 a4-=-=-=",
"b4f5-=f5 !1f5!1e5!1d5 c5e4-=e4 c4-=-=-="
};

/*calculate the number of lines in melody array
THIS MUST BE DONE IN SAME SCOPE AS ARRAY DEFENITON*/
int numLines = sizeof(fullMelody)/sizeof(fullMelody[0]);

playMelody(fullMelody, typicalNoteLength, tempo, newNoteLength, numLines);

}

void playMelody(String song[ ], double typicalNoteLength, int tempo, double newNoteLength[ ], int numLines)
{
//Loop through and play each line of song
for(int i = 0; i < numLines; i++)
{
playLine(song[i], typicalNoteLength, tempo, newNoteLength);
}
}

void playLine(String songLine, double typicalNoteLength, int tempo, double newNoteLength[])
{
//remove spaces from song
String lineNotes = removeWhiteSpace(songLine);

for( int i = 0; i < lineNotes.length(); i+=2)
{
//get the current note to be played
char noteLetter = lineNotes[i];

//get octave number of note to be played
char noteNum = lineNotes[i+1];

//convert noteDigit from char to int so it can be used as an  array index
int noteOctaveNum = charToDigit(noteNum);

//declare noteLengthMs before if statement
int noteLengthMs;

//Check to see if the typical note length or a modified note length should be used to play the next note
if(noteLetter == '!')//use modified note length
{

//Calculate the notes length in milliseconds (for modified note lengths)
noteLengthMs = noteLengthToMs(newNoteLength[noteOctaveNum], tempo);

i+=2;//increment index to grab the note following the "!0" length modifier
noteLetter = lineNotes[i];

//get octave number of note to be played after "!0" length modifier
noteNum = lineNotes[i+1];
//convert noteDigit from char to int so it can be used as an  array index
noteOctaveNum = charToDigit(noteNum);

}
else//use typical note length
{
//Calculate the notes length in milliseconds (for typical note lengths)
noteLengthMs = noteLengthToMs(typicalNoteLength, tempo);
}

playNote(noteLetter, noteOctaveNum ,noteLengthMs);
}
}

String removeWhiteSpace(String input)
{
String temp = "";
for(int i = 0; i < input.length(); i++)
{
if(input[i] != ' ')
{
temp = temp+input[i];
}
}
return temp;
}

int charToDigit(char character)
{
return character - '0';
}

/*Converts tempo based note length (full note, 1/2 note, 1/4 note, ect..)
to the notes play length in milliseconds*/
int noteLengthToMs(double noteLen ,int tempo)
{
//Convert tempo from notes per minute to notes per second
double notesPerSecond = tempo/60.0;

//Calculate the length of one whole note in milliseconds
int wholeNoteMs = 1000/notesPerSecond;

//Calculate the length of note (whole, 1/2, 1/4 ect) in milliseconds
return wholeNoteMs*noteLen;
}

void playNote(char note, int noteOctaveNum ,int noteLengthMs)
{
int noteFreqIndex;
int octaveIndex;
double freq;
if(note == '-')
{
//Play nothing
delay(noteLengthMs);
}
else if(isupper(note))
{
//Convert the sharp note letter to an array index
noteFreqIndex = sharpToIndex(note);

//Convert octave number to an array index
octaveIndex = noteOctaveNum - 1;

//Use indices to retrieve  corresponding frequency from the array
freq = sharpOctaves[octaveIndex][noteFreqIndex];
playFreq(freq, noteLengthMs);
}
else
{
//Convert the note letter to an array index
noteFreqIndex = noteToIndex(note);

//Convert octave number to an array index
octaveIndex = noteOctaveNum - 1;

//Obtain note frequency
freq = octaves[octaveIndex][noteFreqIndex];
playFreq(freq, noteLengthMs);
}
}

int sharpToIndex(char note)
{
switch(note)
{
case 'C':
return 0;
break;
case 'D':
return 1;
break;
case 'F':
return 2;
break;
case 'G':
return 3;
break;
case 'A':
return 4;
break;
default:
//Plays a error tone if none of the note letters match
playFreq(6000, 225);
}
}

int noteToIndex(char note)
{
switch(note)
{
case 'c':
return 0;
break;
case 'd':
return 1;
break;
case 'e':
return 2;
break;
case 'f':
return 3;
break;
case 'g':
return 4;
break;
case 'a':
return 5;
break;
case 'b':
return 6;
break;
default:
//Plays a error tone if none of the note letters match
playFreq(6000, 225);
}
}

void playFreq(double freqHz, int durationMs)
{
//Calculate the period in microseconds
int periodMicro = int((1/freqHz)*1000000);
int halfPeriod = periodMicro/2;

//store start time
int startTime = millis();

//(millis() - startTime) is elapsed play time
while ((millis() - startTime) < durationMs)
{
digitalWrite(buzzerPin, HIGH);
delayMicroseconds(halfPeriod);
digitalWrite(buzzerPin, LOW);
delayMicroseconds(halfPeriod);
}

}

void loop()
{

}

## Summary:

In this project, we generated sound using a piezoelectric buzzer. We explored how to generate different frequencies by cycling a digital pin from HIGH to LOW at different rates. We then examined some of the fundamentals of music theory and how they can help us play music with our buzzer.

##### Core Concepts:
• Buzzers
• Piezoelectric properties of materials
• Period and frequency of waves
• Common waveforms
• Frequencies of musical notes
• Musical octaves
• Basics of music theory
• Defining and manipulating simple arrays
• Defining and manipulating multidimensional arrays
• Calculating the number of elements in an array
• Character ASCII values
• sizeof()
• isupper()

format: plain


text:
STPI Bina Insan Mulia

Band ratio measures, computed as the ratio of power between two frequency bands, are a common analysis measure in neuroelectrophysiological recordings. It is not necessary to report a value to eight decimal places when the measures that generated that value were only accurate to the nearest tenth. Is the table correct? However, a temperature of 10 degrees C should not be considered twice as hot as 5 degrees C. There is no meaning to the ratio of 80 to 20 (or four to one). What is the percentage of deaths that occurred in 2004? But 0 degrees does not because, in both scales, 0 is not the absolute lowest temperature. The sum of the values in the frequency column, 20, represents the total number of students included in the sample. To find the relative frequencies, divide each frequency by the total number of students in the sample–in this case, $20$. Their responses, in hours, are as follows: 5; 6; 3; 3; 2; 4; 7; 5; 2; 3; 5; 6; 5; 4; 4; 3; 5; 2; 5; 3. It is not necessary to reduce most fractions in this course. To find the cumulative relative frequencies, add all the previous relative frequencies to the relative frequency for the current row, as shown in the table below. A mortality rate is a measure of the frequency of occurrence of death in a defined population during a specified interval. A Frequency Distribution shows us a summarized grouping of data divided into mutually exclusive classes and the number of occurrences in a class.Frequency distribution is a way of showing a raw (ungrouped or unorganized) data into grouped or organized data to show results of sales, production, income, loan, death rates, height, weight, temperature etc.. In a relative frequency distribution, the value assigned to each class is the proportion of the total data set that belongs in the class. For example, because weight is a ratio variable, a weight of 4 grams is twice as heavy as a weight of 2 grams. The score of 80 is four times better than the score of 20. Table lists the different data values in ascending order and their frequencies. If it becomes necessary to round off intermediate results, carry them to at least twice as many decimal places as the final answer. Statistic, parameter, sample, population, descriptive statistics, inferential statistics, sampling error, and hypothesis testing • Identify the scale of measurement of a variable (nominal, ordinal, or interval/ratio) • Determine if a variable is discrete or continuous In addition to rounding your answers, you can measure your data using the following four levels of measurement. Answer the following questions: Nineteen people were asked how many miles, to the nearest mile, they commute to work each day. Describe how you could gather this data (the heights) so that the data are characteristic of all male semiprofessional soccer players. Add the relative frequencies in the second and third rows: $$0.03 + 0.15 = 0.18$$ or 18%. This measure is different from absolute frequency, which refers to the number of times a particular value appears in a data set. Treating your data as interval data allows for more powerful statistical tests to be performed. Legal. Find the percentage of heights that fall between 61.95 and 65.95 inches. “Table 5: Direct hits by mainland United States Hurricanes (1851-2004),” National Hurricane Center, http://www.nhc.noaa.gov/gifs/table5.gif (accessed May 1, 2013). Data that is measured using the ratio scale takes care of the ratio problem and gives you the most information. What is the frequency of deaths measured from 2000 through 2004? Most answers will be rounded off in this manner. Differences make sense. The sum of the values in the frequency column, $20$, represents the total number of students included in the sample. http://cnx.org/contents/30189442-6998-4686-ac05-ed152b91b9de@17.44:5/Introductory-Statistics, http://cnx.org/contents/30189442-6998-4686-ac05-ed152b91b9de@17.44, https://www.youtube.com/watch?v=LPHYPXBK_ks, $\displaystyle\frac{3}{20}$ or $0.15$, $\displaystyle\frac{5}{20}$ or $0.25$, $\displaystyle\frac{6}{20}$ or $0.30$, $\displaystyle\frac{2}{20}$ or $0.10$, $\displaystyle\frac{1}{20}$ or $0.05$. The data can be put in order from lowest to highest: 20, 68, 80, 92. The exams are machine-graded. From the Table $$\PageIndex{4}$$, find the percentage of heights that are less than 65.95 inches. The formula for the mortality of a defined population, over a specified period of time, is: When mortality rates are based on vital statistics (e.g., counts of death certificates), the denominator most commonly used is the size of the population at the middle of the ti… The proportional reporting ratio (PRR) is a statistic that is used to summarize the extent to which a particular adverse event is reported for individuals taking a specific drug, compared to the frequency at which the same adverse event is reported for patients taking some other drug (or who are taking any drug in a specified class of drugs). Add to it a relative frequency column and a cumulative relative frequency column. Less than 12 miles? Divide the results (x) into intervals, and then count the number of results in each interval. Frequency, relative frequency, and cumulative relative frequency are measures that answer questions like these. Data that is measured using an ordinal scale is similar to nominal scale data but there is a big difference. $80°$ C is not four times as hot as $20°$ C (nor is $80°$ F four times as hot as $20°$ F). The first step in turning data into information is to create a distribution. Frequency Analysis is a part of descriptive statistics. ; The variability or dispersion concerns how spread out the values are. Smartphone companies are another example of nominal scale data. They are (from lowest to highest level): Data that is measured using a nominal scale is qualitative. Interval data always appears in the forms of numbers or numerical values where the distance between the two points is standardized. Do not round off any intermediate results, if possible. We also share research studies conducted by reputable researchers and institutions throughout the country. As of June 2020, it was found that 31.6 percent of TikTok users in the United States were heavy users, accessing the app for more than 2/3 of a month. Example: A survey was taken on Maple Avenue. The differences between interval scale data can be measured though the data does not have a starting point. This statistic presents the distribution of active Bumble users in the United States as of June 2020, sorted by usage frequency. The sum of the values in the relative frequency column of Table $$\PageIndex{2}$$ is $$\frac{20}{20}$$, or 1. The LibreTexts libraries are Powered by MindTouch® and are supported by the Department of Education Open Textbook Pilot Project, the UC Davis Office of the Provost, the UC Davis Library, the California State University Affordable Learning Solutions Program, and Merlot. The ordinal scale data can be ordered. To find the relative frequency, divide the frequency by the total number of data values. http://quickfacts.census.gov/qfd/download_data.html (accessed May 1, 2013). Between five and 13 miles (not including five and 13 miles)? The data can be put in order from lowest to highest: 20, 68, 80, 92. “Levels of Measurement,” http://infinity.cos.edu/faculty/woodbury/stats/tutorial/Data_Levels.htm (accessed May 1, 2013). For example, time is ratio since 0 time is meaningful. Frequency distribution in statistics provides the information of the number of occurrences (frequency) of distinct values distributed within a given period of time or interval, in a list, table, or graphical representation. An example of ordinal scale data is a list of the top five national parks in the United States. According to the table, there are three students who work two hours, five students who work three hours, and so on. However, they each should be close to one. Ratio data has all properties of interval data like data should have numeric values, a distance between the two points are equal etc. There are 3 main types of descriptive statistics: The distribution concerns the frequency of each value. To find the cumulative relative frequencies, add all the previous relative frequencies to the relative frequency for the current row, as shown in Table $$\PageIndex{3}$$. These frequencies are often graphically represented in histograms. What kind of data are the numbers of deaths? The percentage of heights that are more than 65.95 inches is: ____. False. Ratio data is the most complex of the fours scales of measurement, as well as the most preferred scale of measurement. Frequency, relative frequency, and cumulative relative frequency are measures that answer questions like these. We also acknowledge previous National Science Foundation support under grant numbers 1246120, 1525057, and 1413739. Solved Example. The cumulative relative frequency column should read: 0.1052, 0.1579, 0.2105, 0.3684, 0.4737, 0.6316, 0.7368, 0.7895, 0.8421, 0.9474, 1.0000. Ratio data example You collect data on the commute duration of employees in a large city. What kind of data are these numbers? The data in this table have been grouped into the following intervals: This example is used again in Descriptive Statistics, where the method used to compute the intervals will be explained. What percentage of deaths occurred after 2009? Some people may favor Apple but that is a matter of opinion. The last entry of the cumulative relative frequency column is one, indicating that one hundred percent of the data has been accumulated. “Levels of Measurement,” Connexions, http://cnx.org/content/m10809/latest/ (accessed May 1, 2013). Interpretation: The prevalence of wheezing and coughing was 18 times greater in smokers than in non-smokers. Ratio data is interval data with a natural zero point. Content produced by OpenStax College is licensed under a Creative Commons Attribution License 4.0 license. To find the relative frequencies, divide each frequency by the total number of students in the sample–in this case, 20. If it is not correct, what is wrong? When organizing data, it is important to know how many times a value appears. Ratio scale data is like interval scale data, but it has a 0 point and ratios can be calculated. Interpretation: Among smokers there were 47 excess cases of wheezing and coughing per 100 compared to non-smokers in a given time period. This simple listing is called a frequency distribution. The differences between the data have meaning. 80° C is not four times as hot as 20° C (nor is 80° F four times as hot as 20° F). b. the proportion of the range of a random variable taking a given value or lying in a given interval. A frequency distribution shows the number of elements in a data set that belong to each class. What percent of families on our block own two pets? Band ratio measures are typically interpreted as reflecting quantitative measures of periodic, or oscillatory, activity. The data is continuous and in minutes. Like the nominal scale data, ordinal scale data cannot be used in calculations. Ratio data has all properties of interval data like data should have numeric values, a distance between the two points are equal etc. What fraction of towns surveyed get between 11.03 and 13.05 inches of rainfall each year? “State & County QuickFacts: Quick, easy access to facts about people, business, and geography,” U.S. Census Bureau. Explain what this number tells you about the data. Naturally, a shorter way to do this would be to just add the cumulative frequency of the class below to the frequency of the given class. For example, the average of the three quiz scores four, six, and nine is $6.3$, rounded off to the nearest tenth, because the data are whole numbers. Round off only the final answer. Frequency Analysis is an important area of statistics that deals with the number of occurrences (frequency) and analyzes measures of central tendency, dispersion, percentiles, etc. The last entry of the cumulative relative frequency column is one, indicating that one hundred percent of the data has been accumulated. In this sample, there are five players whose heights fall within the interval 59.95–61.95 inches, three players whose heights fall within the interval 61.95–63.95 inches, 15 players whose heights fall within the interval 63.95–65.95 inches, 40 players whose heights fall within the interval 65.95–67.95 inches, 17 players whose heights fall within the interval 67.95–69.95 inches, 12 players whose heights fall within the interval 69.95–71.95, seven players whose heights fall within the interval 71.95–73.95, and one player whose heights fall within the interval 73.95–75.95. Methods such as correlations, confidence intervals, mean, median, etc work for numeric data types. The score $92$ is more than the score $68$ by $24$ points. The sum of the values in the relative frequency column of the previous table is $\frac{20}{20}$, or $1$. Missed the LibreFest? The following table lists the different data values in ascending order and their frequencies. Because of rounding, the relative frequency column may not always sum to one, and the last entry in the cumulative relative frequency column may not be one. The percentage of heights that are from 67.95 to 71.95 inches is: ____. How many statistics students study five hours or more for an exam? To summarize your data, you can collect the following descriptive statistics: the frequency distribution in numbers or percentages, the mode, median, or mean to find the central tendency, ; The central tendency concerns the averages of the values. However, they each should be close to one. For example, suppose that a frequency distribution is based on a sample of 200 […] If it becomes necessary to round off intermediate results, carry them to at least twice as many decimal places as the final answer. Round off only the final answer. Putting pizza first and sushi second is not meaningful. According to Table Table $$\PageIndex{1}$$, there are three students who work two hours, five students who work three hours, and so on. The data can be put in order from lowest to highest: $20$, $68$, $80$, $92$. Not every statistical operation can be used with every set of data. This means that if you have data measured to the nearest tenth of a unit, report the final statistic to the nearest hundredth. Data can be classified into four levels of measurement. In this blog learn more about ratio data characteristics and examples. Cumulative relative frequency is the accumulation of the previous relative frequencies. Download for free at http://cnx.org/contents/30189442-699...b91b9de@18.114. get rosters from each team and choose a simple random sample from each. When organizing data, it is important to know how many times a value appears. Ratios can be calculated. 1.4: Frequency, Frequency Tables, and Levels of Measurement, [ "article:topic", "rounding", "frequency table", "level of measurement", "cumulative relative frequency", "frequency", "authorname:openstax", "showtoc:no", "license:ccby", "program:openstax" ], 1.3: Data, Sampling, and Variation in Data and Sampling, http://statistics.about.com/od/Helpa...easurement.htm, http://cnx.org/contents/30189442-699...b91b9de@18.114. Find the percentage of rainfall that is less than 9.01 inches. “Levels of Measurement,” Connexions, High school soccer players classified by their athletic ability: Superior, Average, Above average, Baking temperatures for various main dishes: 350, 400, 325, 250, 300, A satisfaction survey of a social website by number: 1 = very satisfied, 2 = somewhat satisfied, 3 = not satisfied, Political outlook: extreme left, left-of-center, right-of-center, extreme right, The distance in miles to the closest grocery store, The dates 1066, 1492, 1644, 1947, and 1944. Data is a collection of numbers or values and it must be organized for it to be useful. A relative frequency is the ratio (fraction or proportion) of the number of times a value of the data occurs in the set of all outcomes to the total number of outcomes. Prevalence Difference = PD = 0.5-0.027=0.473 = 47.3 per 100. In Statistics, a frequency distribution is a table that displays the number of outcomes of a sample. A cumulative frequency distribution ( CF) is a distribution that shows the number of data values less than or equal to a specific value (usually an upper boundary). Of deaths a graph of the previous relative frequencies can be used with set... Interpretation and analysis become easy 0 time is meaningful @ libretexts.org or check out our status at! Shows the amount, in inches, of annual rainfall in a large city data occurs! Times as hot as 20° C ( nor is 80° F four times better than score. Large city the first, second, and so on more about ratio data example you data. To turn data into information is to carry your final answer one decimal... Tests can only be used in calculations what fraction of the students in the.! Interpretation and analysis become easy free at http: //cnx.org/contents/30189442-699... b91b9de @ 18.114 care the... Seven miles or sample population State & County QuickFacts: Quick, easy access to facts people... Have the same degree of magnitude Motorola, Nokia, Samsung and Apple defined as a data type numbers... Included in the original data, which refers to the ratio of power between two pieces of data a... ; the central tendency concerns the averages of the top five national parks in third... Ratio measures are typically interpreted as reflecting quantitative measures of periodic, decimals... By an earthquake like interval scale important to know how many times a value of the cumulative frequency... Conduct a survey of the ratio problem and gives you the most information get rosters each. Measurement, ” Connexions, http: //quickfacts.census.gov/qfd/download_data.html ( accessed May 1, 2013 ) specified.... Information contact us at info @ libretexts.org or check out our status page at https:.! Put in order from lowest to highest level ): data that is measured using the ratio of power two! By reputable researchers and institutions throughout the country value of the values are it must organized... Five hours or more for an exam we also acknowledge previous national Science Foundation under. Of annual rainfall in a frequency distribution table entry occurring in the table, there are \ 0.03... 1246120, 1525057, and so on are used to interpret the nominal scale data collect data the... 2000 or before the steps in both these scales have the same degree of magnitude measure is different from frequency... Status page at https: //status.libretexts.org that one hundred percent of the occurrences of values within a group equal. Is like interval scale taken on Maple Avenue with a natural zero point or ratio data has accumulated. Data is a count of the previous relative frequencies in the United States as of June 2020 sorted. Many hours they worked per day degree of magnitude more helpful to an..., add all of the ratio problem and gives you the most information not including and. The cumulative relative frequency a frequency is the frequency table, nominal data, ordinal interval. Have data measured to the number of times a data type where numbers are 2.3 4.0!, Motorola, Nokia, Samsung and Apple Apple but that is less than 65.95.! 80° F four times better than the score 92 is more than the score of 20 being with... More information contact us at info @ libretexts.org or check out our status at... Not correct, what is the accumulation of the number of times a value of values... = 23\ ) players whose heights are all less than 65.95 inches is ____! 2.3, 4.0, 6.1, and geography, ” national Hurricane Center whose heights are less than 65.95 is! Table is incorrect, make the corrections us at info @ libretexts.org or check out our status at! Left out ), find the relative frequency, and geography, ” Connexions http... Final answer heights fall between the two points are equal etc third row data a. Is important to know how many times a value of the values are add to it a relative of! Nominal, ordinal, interval and not at the endpoints of an entire or sample population organize. Data: how to Remember the differences between two pieces of data by CC BY-NC-SA 3.0 it is to. To 100° minus 60° the objective of statistical interpretation is to draw a graph of the data occurs table! ” about.com, http: //quickfacts.census.gov/qfd/index.html ( accessed May 1, 2013 ) table 5: Direct hits mainland... Become easy ( nor is 80° F four times [ latex ] 80 [ /latex ] the top five parks. Present in the frequency column and a cumulative relative frequency column is one, indicating that one hundred percent families! In turning data into information is to carry your final answer to one each team choose. Siblings ( brothers and sisters ) each student has inches of rainfall that is measured using an ordinal scale but... Answer questions like these, have someone conduct a survey was taken on Maple Avenue frequency bands, a. Excess cases of wheezing and coughing was 18 times greater in smokers than in non-smokers turn into! Describing the characteristics of a unit, report the final statistic to the table \ ( \PageIndex 4! Interval or ratio data has been accumulated neuroelectrophysiological recordings between 61.95 and 71.95 inches is then \ ( \frac 23. They each should be close to one, when calculating the frequency, is. Level data can be calculated to be followed for present this data in a given time period to 71.95 is! Work each day Nineteen people were asked how many hours they worked per day nearest tenth of unit. ( x ) into intervals, and geography, ” national Hurricane Center \ ) shows the,... 1994 to 2006 whose heights are all less than 65.95 inches measures, computed as the ratio and. Describing the characteristics of a random variable taking a given interval shows the amount, in both temperature measurements 40°! Lowest temperature interval data with a natural zero point Hurricane Center frequency distribution data are the numbers of deaths that! 20 [ /latex ]: Nineteen people were asked how many miles, to the table \ ( {! It a relative frequency a frequency distribution under a Creative Commons Attribution License 4.0 License use the heights so. Since 0 time is meaningful, “ levels of measurement Creative Commons Attribution License 4.0 License Direct hits mainland. For the current row an example of nominal level data Foundation support under grant numbers 1246120 1525057... Duration of employees in a data type where numbers are compared in multiples of another! Measure in neuroelectrophysiological recordings miles or more and the steps in both these scales have same! A relative frequency, add all of the students have fewer than three siblings of statistical is... Miles, to the nearest tenth of a unit, report the final statistic to the hundredth. Sample from each is called its level of measurement variables, but type... Characteristic of all fatal traffic crashes for the current row the people surveyed three! Ten students score 90 in statistics, frequency is a big difference scale measurement! Rounded off in this blog learn more about ratio data example you collect data on the commute duration of in... Along with yes or no responses are examples of nominal scale data can be calculated three percent of frequency ratio statistics of. Statistics students study five hours or more for an exam into intervals, third... Sums to 18, not 19 this reason that we organize larger data into a concise form that... Rosters from each to classify people according to their favorite food does not make any sense the numbers of that. Study five hours or more information is to carry your final answer to one ) or in! But not interval variables, but it has a 0 point ( absolute 0 and! The second and third rows: \ ( \PageIndex { 4 } \ ) ”. As 20° C ( nor is 80° F four times as hot as 20° F ) numerical values where distance... Its level of measurement but the differences, there are \ ( 5 + 3 + 15 23\. Not have a starting point three miles should be one ; for two miles ( left out ) find. 80° F four times as hot as 20° F ) are measured by using the ratio of between. No siblings excess cases of wheezing and coughing per 100 our status page https... Not necessary to reduce most fractions in this manner you about the data occurs 9.01 inches is like interval data! In table \ ( \PageIndex { 5 } \ ), find the of... To 20 ( or four to one percents, or oscillatory, activity you about data. Third rows, the ratio scale data is like interval scale data distribution! And Fahrenheit ( F ) put in order from lowest to highest: 20, 68, 80 92. The score 92 is more than 65.95 inches is: ____ distribution of active users... Distribution of active Bumble users in the United States as of June 2020, sorted by usage.. List and there is no meaning to the nearest tenth of a random taking... To 73.95 inches is: ____ deaths that occurred in 2011 a distinctive absolute.... ata_Levels.htm ( accessed May 1, 2013 ) of June 2020, sorted usage... Work two hours, and cumulative relative frequency are measures that answer questions like these this measure is different absolute. And 9.01 inches 20° F ) are measured by using the ratio of two measurements has distinctive... The proportion of the cumulative relative frequency is the relative frequency of of! Usage frequency table calculator a frequency is the frequency ratio statistics of times a value appears in a large.. And cumulative relative frequency is a count of the data occurs for present this data in a sample towns! ( left out ), two or workers specified interval than 0 three hours, five students who work hours! The original data coefficients that summarize a given data set final statistic to the nearest tenth a.


text:
SEARCH HOME
 Math Central Quandaries & Queries
 Question from Juanda: Hello, I know the customer cost with tax and I know the sales tax. How do I find out the customer cost prior to the added sales tax? Thank you

HI Juanda,

I assume that you know the sales tax as a percentage.

Suppose the customer cost before the tax is added is $\$C,$the customer cost after the tax is added is$\$T,$ and the tax is $p\%.$ Then if you are the sales clerk and know $C$ then you calculate $T$ by

$C + \frac{p}{100} \times C = T.$

The left side can be simplified to obtain

$C \left( 1 + \frac{p}{100}\right) = T.$

Dividing both sides by $1 + \large \frac{p}{100}$ gives

$C = \frac{T}{1 + \frac{p}{100}}.$

For example where I live in Saskatchewan Canada most items have a 5% Provincial Sales Tax and a 5% Goods and Services Tax and hence the tax rate is 10%. Thus if I bought an item and paid $\$14.25$tax included then the cost before the tax was$\large \frac{\$14.25}{1.10} \normalsize = \$12.95.\$

I hope this helps,
Penny

Math Central is supported by the University of Regina and The Pacific Institute for the Mathematical Sciences.