There are several different tools available to model a filter’s frequency response. For the most part, filter response modeling is a very straight forward. We can develop a modeling equation base on the frequency response of a passive, RC low pass filter.
Passive First Order RC Low Pass Filter Circuit
The passive RC low pass filter is a simple voltage divider circuit where the impedance of the capacitor changes based on frequency. Using the resistor and capacitor impedances we can create the filter transfer function. From this transfer function we can create our own filter modeling equation.
The voltage divider equation is given by:
The transfer function, H, is simply VOUT divided by the VIN.
Having the transfer function equation simplified and expressed in frequency (ω), we can find the transfer function magnitude to plot the frequency response.
A filter’s cutoff frequency is defined as the frequency where the filter output is 3dB lower than the input. For the passive RC low pass filter this is defined as:
Substituting the cutoff frequency equation the transfer function magnitude response becomes:
Note that the transfer function magnitude is only an expression of frequency that forms a generic frequency response equation. Normally a filter frequency response is expressed in dB, which uses the log function. Using several log identities we are able to create a simple frequency response equation.
Calculating 20*log of the magnitude transforms our result into dB.
From the simple passive RC low pass filter we have created a single equation that calculates the filter frequency response in dB that only requires the filter cutoff frequency. To model a high pass filter, f and fc are flipped.
As an example, the filter response model below uses the above equation in JavaScript and plots the filter frequency response using chart.js based on your inputs.
Generally I have found library support for the Arduino environment to be excellent. I’ve used a lot of different available libraries to support everything from sensors to networking protocols. I am currently using the ESP32 built-in CAN Bus support (known as the Two-wire Automotive Interface(TWAI)) for a distributed hardware system being developed for virtual pipe organs. My last post found a small bug in the Arduino CAN Bus library by Sandeep Mistry when setting the bit rate. Different ESP32 revisions ran at different rates because a configuration register previous reserve bit was being set. Recently I have found another bug when attempting to configure the extended ID acceptance filter.
The acceptance filter is used to only pass wanted received CAN Bus messages. Only accepted messages are stored in the receive FIFO. Acceptance filters are based on an CAN Bus ID and a mask. Filtering is ideal for reducing processor load by only passing desired CAN Bus messages.
The acceptance filter has two, 32-bit registers, acceptance code value and acceptance mask value. The code value specifies the ID bit pattern to match and the mask value allows the user to select the bits they want to match. The ESP32 Technical Manual Version 5.2 acceptance filter algorithm is shown below.
In the algorithm when a message bit and acceptance code bit matches then the XNOR output is true (1) and that bit is accepted. For bits the user wants to ignore the acceptance mask bit should be true (1) and that bit is accepted. For an extended CAN Bus ID, if all 29-bits are accepted, then the message is passed to the receive FIFO.
Previously with this library I used acceptance filtering on the 11-bit ID, which worked well. For this VPO system I’ve decided to used the CAN Bus extended 29-bit ID instead. For the Arduino CAN Bus library the method to setup the acceptance filtering is filterExtended() where the 29-bit ID and mask values are supplied. The Sandeep Mistry library version 0.3.1 filterExtended method is given below.
int ESP32SJA1000Class::filterExtended(long id, long mask)
{
id &= 0x1FFFFFFF;
mask &= ~(mask & 0x1FFFFFFF);
modifyRegister(REG_MOD, 0x17, 0x01); // reset
writeRegister(REG_ACRn(0), id >> 21);
writeRegister(REG_ACRn(1), id >> 13);
writeRegister(REG_ACRn(2), id >> 5);
writeRegister(REG_ACRn(3), id << 3);
writeRegister(REG_AMRn(0), mask >> 21);
writeRegister(REG_AMRn(1), mask >> 13);
writeRegister(REG_AMRn(2), mask >> 5);
writeRegister(REG_AMRn(3), (mask << 3) | 0x1f);
modifyRegister(REG_MOD, 0x17, 0x00); // normal
return 1;
}
The first issue is the forming of the 29-bit mask value. The mask value is AND’d with the inverted mask value resulting in a value of 0. This requires that all ID bits must matched for the message to be accepted. The mask value result should have 1’s in the bits you are not interested in. Changing the ‘&=’ to just ‘=’ solves this problem.
The second problem is writing the acceptance mask register(3). The current library puts 1’s in the lowest 5 bits. These five bits are:
Bit 0 – unused
Bit 1 – unused
Bit 2 – RTR
Bit 3 – ID0
Bit 4 – ID1
By setting the lowest 5 bits to 1, the acceptance filter is now ignoring ID[1:0] and RTR. The code should only set RTR = 1, leaving ID[1:0] to the inverted mask bits values, and always use 0 for unused register bits. The updated code is shown below.
int ESP32SJA1000Class::filterExtended(long id, long mask)
{
id &= 0x1FFFFFFF;
mask = ~(mask & 0x1FFFFFFF);
modifyRegister(REG_MOD, 0x17, 0x01); // reset
writeRegister(REG_ACRn(0), id >> 21);
writeRegister(REG_ACRn(1), id >> 13);
writeRegister(REG_ACRn(2), id >> 5);
writeRegister(REG_ACRn(3), id << 3);
writeRegister(REG_AMRn(0), mask >> 21);
writeRegister(REG_AMRn(1), mask >> 13);
writeRegister(REG_AMRn(2), mask >> 5);
writeRegister(REG_AMRn(3), (mask << 3) | 0x04);
modifyRegister(REG_MOD, 0x17, 0x00); // normal
return 1;
}
Overall this library works well for my application. There have been just a few surprises along the way. With these changes I was successful in filtering extended ID CAN Bus messages.
I am building an ESP32 based system that uses CAN bus communication to transfer data between processors. The ESP32 firmware is being developed using the Arduino programming environment. My plan is to purchase ESP32 modules and plug them on interface boards that are interconnected using the CAN bus. The maximum system is about 16 processors.
Controller Area Network (CAN) bus was officially released in 1986 at the Society of Automotive Engineers conference. It was designed as an in-vehicle communications backbone between engine control unit processor, sensors, actuators, indicators, displays, and other vehicle components. CAN bus defines the OSI network model physical and data link layers.
The physical network is a multi-drop bus that uses a single twisted pair wire with approximately one twist per inch and 120 ohm terminations at the ends. The Digikey blog CAN bus image below shows four CAN bus nodes (controller and transceiver), cabling, and terminations.
The CAN bus 2.0 has two frame versions, standard 2.0A and extended 2.0B. The difference between these frame types is the arbitration field with the length of the identifier (11-bits vs. 29-bits) and the control field. The picture from Typhoon HIL Documentation shows the two frame formats.
CAN bus operates on a decentralized networking principle where all nodes are equal. Any node can transmit a data frame when the bus is free. Each frame contains identification information and supports variable data lengths from 0 up to 8 bytes. CAN bus supports a multitude of bits rates from 25kb/s to 1000kb/s and up to 5.0Mb/s for CAN FD. Because it is a decentralized network, there exists bus arbitration and robust error detection used to create a reliable network.
I selected the ESP32 because it has a built in CAN bus 2.0A/B controller (called two-wire automotive interface (TWAI)) that supports bit rates from 12.5kb/s to 1000kb/s and there are available Arduino libraries. The ESP32 does not support CAN FD protocol. The lowest rates 12.5kb/s to 20kb/s are only available on the ESP32 revision 2 or later. To use the ESP32 you must add a CAN bus physical layer transceiver interface.
I setup a ESP32 CAN bus test with two devices. This simple setup should have been straight forward. There are examples with the Sandeep Mistry Arduino CAN bus library (version 0.3.1) I am using and multiple examples on the Internet. I ran into two problems using this library. The first was solved quickly while the second took some digging.
The first problem was with an include file. I’m using the latest Arduino IDE (2.3.2) with ESP32 support. I got a complier error stating that “esp_intr.h” could not be found. A quick search showed a change was needed in the ESP32SJA1000.cpp file changing the reference to #include “esp_intr_alloc.h.” This allowed the code to compile.
// Copyright (c) Sandeep Mistry. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#ifdef ARDUINO_ARCH_ESP32
//#include "esp_intr.h"
#include "soc/dport_reg.h"
#include "driver/gpio.h"
#include "esp_intr_alloc.h"
#include <rom/gpio.h>
#include "ESP32SJA1000.h"
In my test I had two ESP32 connected via CAN bus transceivers with the correct terminations. The two devices would not communicate even after testing several different bit rates. I used two different manufacturer’s modules, purchased at different times so I tried two devices from the same manufacturer’s and that worked! Then I tried the other manufacturer’s modules and that worked! But the two different manufacturers modules would not work together.
Finally I hooked up my oscilloscope and measured the bit times. I configured the system to run at 1Mb/s. On the newer ESP32 modules the bit rate was only 0.5Mb/s. The bit rate was correct on the older ESP32 modules.
Espressif Systems in newer ESP32 revisions support CAN bus bit rates less than 25kb/s. This update has caused an issue with the Sandeep Mistry Arduino CAN bus library (and I suspect other libraries as well). The library writes all bits to the REG_IER register that in newer ESP32 revisions has a bit that enables a divide by 2 CAN bit rate. The fix is to modify the REG_IER bit for ESP32 revisions 2 or greater. The modification is needed in the ESP32SJA1000.cpp begin() method after REG_IER write as shown below. After making these changes the CAN bus is now interoperable between different ESP revisions and manufacturer’s modules.
modifyRegister(REG_BTR1, 0x80, 0x80); // SAM = 1
writeRegister(REG_IER, 0xff); // enable all interrupts
if (ESP.getChipRevision() >= 2) {
modifyRegister(REG_IER, 0x10, 0); // From rev2 used as "divide BRP by 2"
}
Besides learning about the CAN bus library capabilities I wanted to stress test the CAN bus to determine how well it will work in my application. The stress test uses four senders and one receiver (I only had 5 CAN bus transceivers for the test) to pass messages.
The receiver tracks each individual sender identified by the unique 11-bit ID and verifies all messages are received by checking a message counter. When an error occurs a serial message is printed and the new message counter is used.
// CAN Receiver Stress Test
// Standard message (11 bit ID)
// Variable time between messages and message length
// Constant ID and message counter to check for lost messages
// Multiple senders
#include <CAN.h>
#define MAX_SENDERS 16
struct messageCheck {
int id11;
uint8_t messageNum;
} receivedData[MAX_SENDERS];
uint8_t seqNum;
int id11;
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println("CAN Stress Receiver");
CAN.setPins(22,21);
// start the CAN bus at 1000 kbps
if (!CAN.begin(1000E3)) {
Serial.println("Starting CAN failed!");
while (1);
}
// voltage translator OE
pinMode(12, OUTPUT);
digitalWrite(12, HIGH); // has 10K pull down
// initialize test structure
for(int i = 0; i < MAX_SENDERS; i++) {
receivedData[i].id11 = 0;
receivedData[i].messageNum = 0;
}
}
void loop() {
// try to parse packet
int packetSize = CAN.parsePacket();
if (packetSize) {
id11 = CAN.packetId();
// first packet id in list
int i = 0;
while(receivedData[i].id11 != 0) {
if(receivedData[i].id11 == id11) {
break;
}
i++;
}
if(i < MAX_SENDERS) {
if(receivedData[i].id11 == 0) { // new to list
receivedData[i].id11 = id11;
receivedData[i].messageNum = CAN.read();
}
else { // id found
receivedData[i].messageNum++;
seqNum = CAN.read();
if(receivedData[i].messageNum != seqNum) { // error
receivedData[i].messageNum = seqNum;
Serial.print("Error ID "); Serial.println(receivedData[i].id11);
}
}
}
else { // some other error occured
Serial.println("i >= MAX_SENDERS Error");
}
}
}
Each sender transmits data at random times between 1 and 50ms and each frame has random number of bytes between 1 (message counter) and 8. The message counter, which is always present, is used to track message delivery by the receiver.
// CAN Sender Stress Test
// Standard message (11 bit ID)
// Variable time between messages and message length
// Constant ID and message counter to check for lost messages
#include <CAN.h>
#include "esp_mac.h"
int id11 = 0; // 11 bit ID, use MAC address
uint8_t messageNum = 0; // first byte of message data, increments over time for testing
uint8_t bytesRandom; // random number of additional bytes to send 0 to 7
long waitRandom; // random wait time in MS before sending next message
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println("CAN Sender Stress Test");
CAN.setPins(22,21);
// start the CAN bus at 500 kbps
if (!CAN.begin(1000E3)) {
Serial.println("Starting CAN failed!");
while (1);
}
// voltage translator OE
pinMode(12, OUTPUT);
digitalWrite(12, HIGH); // has 10K pull down
uint8_t mac[8];
esp_efuse_mac_get_default(mac);
for(int i = 0; i < 8; i++) {
id11 += mac[i];
}
id11 &= 0x07ff;
randomSeed(analogRead(39));
}
void loop() {
// wait random ms
waitRandom = random(1,50);
delay(waitRandom);
// send packet: id is 11 bits, packet can contain up to 8 bytes of data
Serial.print("Sending packet ID ... "); Serial.print(id11, HEX);
bytesRandom = (uint8_t)random(7); // random number of additional bytes
CAN.beginPacket(id11); // ID
CAN.write(messageNum++); // message count used to measure reliability during stress test
for(int i = 0; i < bytesRandom; i++) { // add random number of bytes
CAN.write((uint8_t)random());
}
CAN.endPacket();
Serial.println(" done");
}
Overall I’m pleased with CAN bus performance and reliability. I connected an oscilloscope and observe random message timing and message collision events. I can disconnect/reconnect/reset senders and the receiver properly detects a node message error. I have run the test for hours without any dropped messages at 1Mb/s bit rate on a very short bus (<2feet). Future testing includes adding more nodes and increasing the bus wire length.
Sometimes when working with an embedded system sending information to a serial port is useful. It can be used to provide system telemetry data, user feedback, or to aid with debugging a program. With most embedded development environments there is support for the old C standard printf(). Generally to use printf() a user needs to provide the putchar() routine that directs character output to your serial port. The STM32CubeIDE is no different and has printf() support. DigiKey provides a nice tutorial on the subject including enabling the floating point support.
There are only two steps needed to provide basic printf() support. First create a UART project instance in STM32CubeIDE. Use the Connectivity Category and select the UART you want to use. This assigns the processor GPIO pins for the TX and RX signals and creates a UART instance and handle. Under Parameter Settings set the desired basic settings such as baud rate, word length, parity, and stop bits.
The next step is to redirect printf() output to use the UART instance. First include the standard IO (stdio.h) header file. Based on your complier, the second part creates the interface to output a single character to the UART instance using the STM32 hardware abstraction layer (HAL) function. With the STM32 environment, you need the UART handle from the created UART instance (e.g., hlpuart1 in the sample code). The necessary code segment is shown below and is placed in the Private Function Prototypes (PFP) code area.
/* USER CODE BEGIN PFP */
#ifdef __GNUC__ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #endif
One issue with using printf() is that the CPU is involved with moving each formatted character to the UART. The printf() function actually performs two activities. First a character string is created based on the formatting string and arguments in the printf() function call. The second activity is moving that character string to the UART one byte at a time.
One way to improve the printf() CPU I/O efficiency is create the output formatted character string but use DMA to move the character string bytes to the UART. Using a DMA channel eliminates the need for the CPU to move the individual character string bytes to the UART.
In the STM32 IDE when configuring the UART you can assign a DMA channel to the UART transmitter. For an out going message the DMA transfer is setup as memory to peripheral (transmit) with a byte data width.
When you are ready to send a message first use sprintf() to create the formatted character string in a memory buffer. Once the string has been created start the transmit DMA using the HAL DMA api call (HAL_UART_Transmit_DMA). A small code segment is shown below using sprintf() and the HAL DMA api.
/* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
// check if ready to output // flag set by timer interrupt, use DMA to transmit data if(outputState == XMITNOW) { sprintf(currentOutBuffer, "%llu, %lu, %08lX, %llu, %llu, %llu, %llu\n", ++outSequence, outputADCSums->pdCount, outputADCSums->error, outputADCSums->violet, outputADCSums->blue, outputADCSums->red, outputADCSums->green);
HAL_UART_Transmit_DMA(&hlpuart1, (uint8_t *)currentOutBuffer, strlen(currentOutBuffer)); outputState = OUTPUT_IDLE; } } /* USER CODE END 3 */
The STM32 IDE programming environment and HAL api greatly simplifies using a DMA channel to transmit formatted character strings without involving the CPU. Hopefully this example gets you started using DMA for your data transfers.
I have discussed using a backtracking algorithm to solve sudoku puzzles multiple times in previous posts. My first sudoku backtracking puzzle solver was programmed in Python with a Tkinter user interface. This worked well except the UI required the user to click a cell and enter a puzzle value into a popup window. I then implemented the same algorithm using an Excel VBA. This time the user entered each puzzle value directly into workbook cells but was about 10 times slower than the Python version. In this version I am using Javascript and a table within a web (this) page.
As a quick review the backtracking algorithm is a method for solving problems recursively by testing incremental solutions. If the solutions fails, then you “backtrack” the solution and attempt another solution. To solve a sudoku puzzle using the backtracking algorithm you place a value in the first empty puzzle square and test if that solution is valid (unique row, column, and 3×3 square value). If the value is not valid, then the next value is tried. If the test solution is valid, then the next empty square is filled with a value and tested until a valid solution is found. If you have tried all values without a valid solution, then you move back one “completed” square and try the next value. This continues until all empty squares have a value that meet the sudoku puzzle requirements.
The conversion from Python and Excel VBA to Javascript was straight forward. The only item I haven’t resolved is showing the solution progress live as with the Python and Excel VBA versions. This slight issue has a positive effect where the puzzle is solved more quickly without any UI updates. Also no fancy web table formatting was done.
Below is a blank sudoku puzzle. Click any table cell and place the known puzzle value. Once you have entered all the know puzzle values click “Solve Puzzle” to see the solution. A solution time is shown with the solved puzzle. You can clear the puzzle and enter new values by clicking “Clear Puzzle.” Enjoy!
Sudoku Puzzle Solver
Enter your puzzle values then click “Solve Puzzle”
When transmitting data over a coax cable it is important to determine the amount of signal attenuation that occurs for data recovery purposes. Signal attenuation changes based on the cable construction, signal frequency, and cable length. Prior to ordering cable and measuring the attenuation a good first step is to approximate your application’s signal attenuation. Although cable datasheets provide a wealth of information, generally your application’s cable length and data frequency will not be listed.
This page helps to calculate a coax cable’s approximate attenuation for a selected signal frequency and cable length. The calculation uses a generic, cable attenuation approximation model that is built using data from the manufacturer’s cable datasheet. A JavaScript based cable attenuation calculator is provided that accepts vendor’s cable attenuation parameters as inputs and calculates the signal attenuation for a specified cable length.
Cable Attenuation Approximation Model
Cable attenuation for any coaxial cable can be approximated using the equation below where frequency (f) is in MHz. Once the coefficients a, b, and c are known, finding the cable attenuation for a selected frequency is easy by applying the formula below.
The coefficients a, b, and c are found by solving a set of linear equations using information found in the vendor’s datasheet. These equations are the different attenuation values (α1, α2, and α3 ) at different frequencies (f1, f2, and f3) for a common cable length. The cable datasheet usually provides these values but you can also measure these values in the lab.
Cramer’s Rule (method of determinates) is used to solve for coefficients a, b, and c using the linear equation frequency and attenuation values.
These coefficients create an attenuation based on frequency for the common cable length used in the linear equations. To calculate the cable attenuation for a different cable length first convert your answer to dB per unit length and then multiple by the application cable length.
Model Verification
To validate the above model we used Belden RG-174 catalog data. The vendor supplied data is for a 1000 feet of RG-174 coax cable at three different frequencies.
n
Frequency (fn)
Attenuation (αn) for 1000 Feet
1
1 MHz
19dB
2
10MHz
33dB
3
100MHz
84dB
RG-174 1000′ Frequency vs. Attenuation
Solving the linear equations yields the coefficient values of a = 12.871, b = 6.020, and c = 0.109 for 1000 feet of cable. Data from the Belden catalog shows that 100 feet of RG-174 has an attenuation of 5.8dB at 50MHz. Our model approximates the 100 feet, 50MHz attenuation at 6.09dB.
Cable Attenuation Calculator
In the form below, enter your cable parameters (Input Data: common cable length, and frequency vs. attenuation values) for three different frequencies/attenuations at a common cable length. Enter your application’s data frequency and cable length (Find For:) and then click Calculate to display the Solution: for coefficients, Δ determinate, and your attenuation value.
When using this model with calculated coefficients, don’t forget to convert the attenuation into unit length and then multiply by your cable length. For the validation model example the result using a, b, and c is 60.9dB / 1000′ × 100′ = 6.09dB.
Notes
Normally attenuation values are entered as negative values in dB. You can use either positive or negative numbers to calculate the cable attenuation. Also the length units are arbitrary. You can use feet, meters, km, etc. as long as the units are consistent. Finally frequency values are always entered in units of MHz.
I have worked on many embedded systems during my career. Some of those projects used a processor while others required custom approaches such as using a field programmable gate array (FPGA). I’ve been using FPGAs since the early 1990’s where initially they where configured using schematic entry. Later we moved to VHDL to create behavioral descriptions of the circuits. Today a more common FPGA hardware description language is Verilog.
For an upcoming proof of principle project I determined that a processor only solution wasn’t flexible enough to meet some of the strict timing requirements as well as not supporting potential system changes based on testing.
Some of the project requirements included the measurement of multiple input signal properties, controlling a digital to analog converter (DAC), and sending the measurement results to another computer via USB.
While searching for a simple FPGA development board and programming environment I discovered the Alchitry FPGA board set and development environment with the hardware being sold by SparkFun.
The current hardware offering has three different FPGA development boards. Two of the boards use the AMD (Xilinx) Artix 7 FPGA (Au and Au+) and the third board uses the Lattice iCE40 HX (Cu). Each board has different resources but all include a connector system for adding additional boards that add a USB 3.0 interface (Ft Element), multiple IO types (Io Element), and an IO breakout (Br Prototype Element). For my project the Au FPGA Development Board with the Br Prototype Element Board gave me the resources and connectivity that I needed. The picture below shows the SparkFun Alchitry Au FPGA kit that includes the Au, Io, and Br boards plus a female header set.
The Alchitry Labs development environment is an abstraction layer called Lucid to help simplify FPGA programming. The Alchitry Labs IDE actually converts Lucid structure into Verilog before interfacing with the FPGA vendor’s tools to create your FPGA image. The Alchitry Labs IDE has an extensive library of components (e.g., I2C Controller) as well has having an interface to the FPGA vendor’s tools to create specialized IP cores (e.g., clocking module).
One of the project’s features is to control a DAC. For that task I decided to use an Adafruit MCP4725 breakout board that has an I2C interface. The MCP4725 is a 12-bit DAC that supports a 3.4Mbps fast mode I2C interface. This requires the FPGA to operate as an I2C controller. The Alchitry Au has a QWIIC/STEMMA QT connector to support a 3V3 I2C connectivity and the IDE has an I2C controller component.
In this I2C controller example I am using Architry Labs Version 1.2.7. For my project there are basically four steps to control an I2C DAC:
Add the Alchitry I2C Controller component (Lucid source file)
Create MCP4275 module to write new DAC value (voltage)
Create a test driver to verify operation
To add a predefine component in the IDE use Project > Add Components. A popup window appears where you select under Protocols the I2C Controller. This adds a file, i2c_controller.luc, under Components in the IDE left pane.
To define the pinout you need to know which pins are assigned to SCL and SDA. The Au environment as an IO abstraction that matches the Br pinout, which is show below (from the SparkFun website). You can either add the pinout to an existing Constraints file (alchitry.acf) or create a new one and add the lines below. I did not add a pullup resistor to each line since the MCP4725 breakout already has pullup resistors. I am using the Au QWIIC connector on Au board requiring the signals to be assigned as scl = A24 and sda = A23. The letter is the bank and the number is the pin within the bank (e.g., A23 is bank A, pin 23, lower right of bank A).
pin scl A24; pin sda A23;
To create the MCP4725 module add a new file, File > New File. In the popup add the file name and select Lucid Source and then Create File.
The module interface is listed below. The signal vdata[12] is the 12-bit voltage value and write is a single clock signal (high = write) that starts the DAC write over I2C. The module has feedback to indicate if the module can accept a new value via the busy signal. Busy HIGH indicates the module is current writing a DAC value and cannot accept a new value.
module mcp4275 ( input clk, // clock input rst, // reset input vdata[12], // 12-bit voltage data to write input write, // write value to mcp4275 output busy, // busy indicator 1 = busy inout sda, // i2c data output scl // i2c clock )
This module has the I2C controller (qwiic) that uses a FSM (state) to send the data (voltage value) to the MCP4725 as well as a memory element to save the vdata input in case it changes during FSM execution (dff newvalue[12]).
.clk(clk) { .rst(rst) { fsm state = {IDLE, START, ADDRESS, BYTE2, BYTE3, STOP}; // mcp4725 states write i2c_controller qwiic(.sda(sda)); // i2c controller dff newvalue[12]; // value to be written to DAC } }
For this example we are only performing a single write of a 12-bit value to the DAC over I2C. Future enhancements include creating a fully supported MCP4724 interface that includes writing and reading from the MCP4725 EEPROM. For now we are only interested in changing the DAC voltage value. To start we assign some of the default signal values in the always block. The module is busy when not in the IDLE state.
The core of this module is the FSM that executes the steps required to write the new voltage value to the DAC. The description on how to use the I2C Controller component is found in the Component source code. As a summary, to use the I2C Controller you set the start signal to high for 1 clock cycle and then write or read as many bytes as desired. Once finished, set the stop signal high for 1 clock cycle.
To write to the MCP4725 we are using the fast mode write method has shown in the datasheet in Figure 6-1. This method transmits 3 bytes – Byte 1: the 7-bit address with the R/W bit set to 0, Byte 2: the upper 4-bits of data with the command bits (C2, C1 = 0) and normal power (PD2, PD1 = 0), and Byte3: lower 8-bits of data.
The FSM Lucid code is shown below. The FSM is IDLE until the module input write bit is set to 1, which saves the input data to a 12-bit DFF and then moves to the next state START. If the controller isn’t busy, the I2C controller start bit is set to 1 and the next state is ADDRESS. When the controller isn’t busy, each of the three bytes is sent in order. Once all three bytes have been transmitted, the I2C controller stop is issued. There are two items to note. First, in each non IDLE state the controller is check for busy before writing the next byte or stopping the controller. Second, although available, the write ack is never checked. I2C has support an acknowledgement after each byte is written to the peripheral.
// fsm for updating mcp4275 output // using fast mode write method (datasheet Figure 6-1) case(state.q) { state.IDLE: // send new dac data if(write) { // transmit new DAC data over i2c state.d = state.START; newvalue.d = vdata; // capture new DAC data }
The final item is to test the design. At the top level I created a counter. Whenever the 12-bit counter value changes, the value is written to the DAC. This creates a sawtooth waveform since the counter wraps around from 0xFFF to 0. The code for the test driver is shown below.
.clk(clk) { // The reset conditioner is used to synchronize the reset signal to the FPGA // clock. This ensures the entire FPGA comes out of reset at the same time. reset_conditioner reset_cond;
.rst(rst) { counter dacoutput(#SIZE(12), #DIV(8)); // test data driver, voltage 12-bit value dff newvalue[12](#INIT(12h555)); // value to be written to DAC mcp4275 voltage(.sda(sda)); // write new voltage value } }
always { reset_cond.in = ~rst_n; // input raw inverted reset signal rst = reset_cond.out; // conditioned reset
led = 8h00; // turn LEDs off led = newvalue.q[11:4]; // upper 8 bits of DAC voltage value usb_tx = usb_rx; // echo the serial data
if(newvalue.q != dacoutput.value && voltage.busy == 0) { // transmit new DAC data over i2c newvalue.d = dacoutput.value; // capture new DAC data voltage.write = 1; } } }
The results were as expected. The only issue I encountered was related to my original FSM structure using signals to interface to the I2C controller. Most of the FSM states were optimized out, thus not executing the desired sequence. That problem was solved by interfacing directly with the I2C controller component signals. The output waveform is shown below. The sawtooth period matches the expected rate (100MHz clock / 256 (counter #DIV(8)) / 2^12 (counter size) = 95.367Hz).
Improvements to the DAC module include making a fully featured MCP4725 interface as well as modifying (creating my own) I2C controller to support the 3.4Mbps fast mode I2C interface. Currently the I2C controller operates at a single frequency based on the user specified divider. To enter the fast mode I2C a command is sent at the “normal I2C rate” then scl is increased to 3.4MHz.
I found both the hardware and Lucid programming environment to be excellent, as well as Alchitry support. The Au development board provides plenty for hardware resources and IO. The SparkFun boards are well made and of high quality. The hardware costs are very reasonable even for a hobbyist. The Lucid programming environment does simplify FPGA behavioral programming and interfaces well with the vendor’s FPGA tools. The Alchitry cores support the majority of a user’s needs. I recommend this board set and programming environment for both hobbyist and professionals developers.
I’ve started using STMicroelectronics STM32 microcontrollers in my client’s embedded applications. Recently I needed to interface an STM32G0x0 MCU with a Knowles SPH0645LM4H-1 MEMS microphone using I2S interface.
The STM32G0x0 MCU is an entry level, 32-bit Arm® Cortext®-M0+ MCU that runs up to 64MHz. This MCU series is cost effective and part of the ST STM32 value line. My client selected the STM32G030F6, which has 32Kbytes of Flash and 8Kbytes of RAM packaged in a 20-pin TSSOP. This MCU has I2C, USART, SPI/I2S communication interfaces, a 12-bit ADC, multiple GPIOs, timers, DMA, and RTC.
The Knowles SPH0645LM4H-1 is a miniature, low power, bottom ported MEMS microphone with a 24-bit I2S standard digital interface. The microphone supports 16kHz to 64kHz sampling. This microphone can be configured for either a right or left channel by an external signal. The key microphone feature is the output is already in PCM format so no additional CODEC hardware or PDM firmware conversion is needed in this application.
I2S (Inter-IC Sound) is a serial bus communication standard used for communicating with digital audio devices. Philip Semiconductor introduced the standard in 1986. The interface has three signals, serial clock (SCLK), word select (WS) and serial data (SD). SCLK is a continuous signal and is 32 or 64 times the audio sample rate based on word size. For example working with 32-bit data frames for a 16KHz audio, SCLK is 2 (audio words left and right) x 32-bits (size of each audio word) x 16kHz (sample rate) = 1.024MHz. WS is used to select left (low) and right (high) channel. SD is the audio data that is either 16 or 32 bit data word. Below is the I2S SCLK/WS/SD relationships from the Knowles datasheet. The Knowles data is 24-bit left shifted in a 32-bit word format.
STM32G030F6 I2S Setup
The STMicroelectronics development environment, STM32CubeIDE, has a configuration tool to setup the STM32 I/O as well as to set the clock configuration. Once you setup the hardware components this tool generates the support code and data structures.
For this application the Multimedia I2S1 interface to configuration for half-duplex master mode. This has the STM32 send the SCLK and WS signals and can either send or received data (half-duplex).
The I2S parameter setup configurations the transmission mode, communication standard, data and frame format, audio frequency, and the clock polarity. In our application the transmission mode is Mode Master Receive since the processor is the master and the microphone is the data source.
For the communication standard the selections include I2S Philips, MSB First, LSB First, and a couple of PCM framing selections. Originally I used the MSB first standard but discovered that the data was under shifted (MSB was bit 30 not 31 as expected). A look at the STM32 reference manual showed why.
The STMicroelectronics RM0454 Reference Manual (rev 5) shows waveforms for both the I2S Philips standard the MSB justified formats. Both the I2S Philips and the MSB justified framing sets WS on the falling clock edge. In the I2S Philips standard data changes on the next rising SCLK edge and read on the falling edge creating a null 1/2 bit time before the first data bit. With MSB justified format there is no gap. Data changes on the SCLK falling edge along with WS and read on the next rising edge. By using the MSB justified format the STM32 read the first bit before being transmitted by the microphone.
Below is the I2S interface measured with an oscilloscope (channel 1 = SCLK, channel 2 = WS, channel 3 = SD). It is clear that WS changes to the left channel on the falling edge of SCLK and the first data bit from the microphone appears on the next rising edge.
Next is to configure the Data and Frame Format. The SPH0645LM4H-1 data format is 24-bits in a 32-bit frame. Of the 24-bits only the most significant 18-bits are valid and the remaining bits (lowest 6-bits of the 24-bit word) are set to zero by the microphone. The remaining data byte (8-bits) are tri-stated and with a 100K pulldown resistors are read as zero by the STM32. Our choice must include a 32 Bits Frame since that is the output of the microphone, but we can select 16, 24, or 32 data bits.
The 24 and 32-bit choices requires two reads from the receive data register while using 16-bits of data in a 32-bit frame requires only 1 read and the second 16-bits are automatically set to zero. For this test I selected 16-bits in a 32-bit frame.
The code is very simple when using the provide blocking call to receive I2S data. The call is made to HAL_I2S_Receive, which takes the I2S handle pointer created by the auto code generation tools when configuring the processor, a pointer to a data buffer, the number of samples, and a timeout value. Since the I2S interface is designed for a left and right channel, 2 samples are selected.
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
volatile HAL_StatusTypeDef result = HAL_I2S_Receive(&hi2s1, (uint16_t *)&dataIn[0], 2, 100);
if(result != HAL_OK) {
printf("Error Code %08lX\n", HAL_I2S_GetError(&hi2s1));
}
}
/* USER CODE END 3 */
Below is a screen shot showing the Live Expressions window for the data buffer. Note that dataIn[0] is our left channel and dataIn[1] is our right channel and is always 0 since we don’t have a another sensor attached.
From the single blocking read, there isn’t much time to processed the received I2S data. With two channels at 16kHz there is only 15.625 microseconds (16kHz x 4 16-bit words = 64kHz) before the next 16-bit data word is ready at the input SPI/I2S register. That is just 1,000 CPU clock cycles at 64MHz maximum clock rate. Just trying to convert the read integer to a string caused data overflow errors (sprintf is a very, very slow function). With an overflow error you miss some real-time data and the data may shift within the data buffer (i.e., left channel moved to dataIn[1]).
A safer approach to processing incoming audio stream data is to use DMA where data is read from the microphone and placed directly into memory without the CPU. The STM32 programming environment provides support for a continuous circular buffer with interrupt callbacks for buffer half full and completely full. The image below shows the DMA data buffer. Note that all right channel data is zero.
For the I2S DMA test I counted each buffer related interrupt and performed a timing analysis to verify continuous data was being read from the MEMS microphone at the realized audio sampling rate (slightly different than the desired audio rate due to processor clock tree).
Overall the STMicroelectronics STM32CubeIDE tool make the developer’s job easier with the hardware configuration interface and auto hardware abstraction layer (HAL) code and data structures generation.
Micro Electro Mechanical Systems (MEMS) accelerometers have been available since the 1990’s. MEMS creates a microscopic mechanical sensing structures that is coupled with microelectronic circuits to measure physical parameters such as acceleration. One of the first applications of the silicon based MEMS accelerometer was to protect hard drives (HDD) media when being dropped while rotating. When free fall was detected the HDD head would be moved to a safe zone to protect the media.
When a MEMS accelerometer is in free fall all acceleration values move towards zero. The figures below help to understand why this is true (Figures from Physical StackExchange). When in free fall the frame and mass are both affected by the same acceleration so the force acting on the spring nears zero. For a MEMS accelerometer the measured acceleration nears zero.
An inexpensive MEMS accelerometer is the LIS3DH. This unit is a 3-axis accelerometer with scalable ranges (±2g/±4g/±8g/±16g), supports multiple data rates, is low power, has three 10-bit ADCs, and interfaces over I2C or SPI. This accelerometer can also generate interrupts for tap, double-tap, orientation changes, and freefall detection. These accelerometers are available on breakout boards from multiple vendor such as Adafruit and Sparkfun.
To configure the LIS3DH for free fall detection a threshold level in g’s and duration are programmed in device registers. The design tip DT0100 shows an example of setting the level to ~350mg with a duration of 30ms. For the interrupt to occur a level of 350mg or less must be detected on all three axis accelerometers for a minimum of 30ms before the interrupt occurs as shown in the figure below from the ST design note.
For this example I used an Adafruit LIS3DH breakout board. Adafruit does a nice job of providing libraries for their products. The Adafruit LIS3DH library unfortunately does not provide a free fall interrupt method. Normally I would inherit the library object and create my own methods but the library made key communication variables private, so this wasn’t an option without modifying the library. My client’s application did not required any other processing so I created code to replicate the free fall interrupt function in the Arduino loop().
The code uses the Adafruit sensors_event_t type, which returns the accelerometer values in m/s2. To match the design tip the free fall threshold would be set to 3.432 m/s2 (1g = 9.08665 m/s2). With a free fall threshold of 350mg, I found it too easy to enter free fall so I reduced the value to about 50mg, which worked well. When all three axis meet the free fall detection threshold, the free fall duration is checked. If the amount of time exceeds the free fall duration then a LED is turned on (the client turned a servo motor) indicating the unit is in free fall. If the free fall threshold isn’t met, then the duration time is updated to the current time using millis().
Below is the sample code emulating the LIS3DH free fall detection.
// Free Fall Detection
// Adafruit LIS3DH Accelerometer with SPI
// Adapted from Adafruit library acceldemo.ino
#include <SPI.h>
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>
// Hardware Pins
#define LIS3DH_CS 10 // SPI device select
#define LED_PIN 4 // LED output pin to indicate freefall active high
// Operating Parameters
#define FREEFALL_ACCEL_THRESHOLD 0.5 // freefall threshold in m/s^2, 1g = 9.80665 m/s^2
#define FREEFALL_TIME_THRESHOLD 30 // freefall time threshold in ms
// hardware SPI for accelerometer
Adafruit_LIS3DH lis = Adafruit_LIS3DH(LIS3DH_CS); // accel object
sensors_event_t event; // sensor data to evaluate for freefall
// timer for free fall
uint32_t freeFallTime; // timer for consecutive freefall detections
void setup(void) {
Serial.begin(115200);
while (!Serial) delay(10); // will pause Zero, Leonardo, etc until serial console opens
// setup output control pin for LED
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
if (! lis.begin()) {
Serial.println("Couldnt start");
while (1) yield();
}
lis.setRange(LIS3DH_RANGE_2_G); // set to 2G range
lis.setDataRate(LIS3DH_DATARATE_400_HZ); // sample at fastest rate (2.5ms)
Serial.println("Free Fall Detection with LIS3DH");
freeFallTime = millis();
}
void loop() {
lis.getEvent(&event); // get latest data
// detect free fall
if(abs(event.acceleration.x) <= FREEFALL_ACCEL_THRESHOLD &&
abs(event.acceleration.y) <= FREEFALL_ACCEL_THRESHOLD &&
abs(event.acceleration.z) <= FREEFALL_ACCEL_THRESHOLD) {
if((millis() - freeFallTime) >= FREEFALL_TIME_THRESHOLD) {
digitalWrite(LED_PIN, HIGH);
}
}
else { // not in freefall reset timer
freeFallTime = millis();
}
}
Update
The freefall detection code and hardware was used successfully as part of the Rogers Park Space Program high altitude balloon project when the “HELEN II” paper plane was released at 34,800′ above sea level. You can watch a cool video on YouTube of the entire flight that reached over 112,000′ on 5/28/2023.
Previously I have written about selecting a file from a Microsoft VBA using a file dialog window on a Mac. This approach used an Applescript and selected a single file. This approach was limited to selecting a single file located on the local hard drive. Recently I had the need to updated this approach to allow selecting multiple files that are located on any drive/cloud.
The ability to select multiple files in the dialog window required a small change to the Applescript. The text “multiple selections allowed false” changed “false” to “true.” This allows selecting multiple files that the Applescript returns.
mypath = MacScript("return (path to documents folder) as String")
sMacScript = "set applescript's text item delimiters to "","" " & vbNewLine & _
"try " & vbNewLine & _
"set theFiles to (choose file " & _
"with prompt ""Please select a file or files"" default location alias """ & _
mypath & """ multiple selections allowed true) as string" & vbNewLine & _
"set applescript's text item delimiters to """" " & vbNewLine & _
"on error errStr number errorNumber" & vbNewLine & _
"return errorNumber " & vbNewLine & _
"end try " & vbNewLine & _
"return theFiles"
inFiles = MacScript(sMacScript) ' get filenames
When the MacScript is run it returns a string of full path filenames separated by “,” unless no files are selected then “-128” is returned. The string of filenames are easily split into a array file filenames for VBA use. For the VBA to access each file two changes are required to each filename. First the Mac directory separator “:” is replaced with “/” symbol. The second change is to add a prefix “/Volumes/” to a full path filename. This allows the use of different drives/cloud files. In my previous post I removed “Macintosh HD” for the path name.
filenameSplit = Split(inFiles, ",")
For N = LBound(filenameSplit) To UBound(filenameSplit)
selectedFile = "/Volumes/" & Replace(filenameSplit(N), ":", "/")
<... DO WORK ...>
Next
This updated Applescript and code was used in a Word VBA but should work well with Excel on the Mac.