1

I'm doing a project where I want to record IMU (Inertial Measurement Unit) readings. I want to use pretty high sampling frequency and I'm using Raspberry Pi Zero W to send PWM signal of 800Hz to control the sampling frequency. The Raspberry is connected to the sensor via SPI and logs data to SD card. First I thought that the data logging works just fine but I noticed that something doesn't add up. For example, I know that an event that I'm recording lasts quite accurately 4.5 seconds. However, the IMU readings suggest that the event lasts only 4.2 seconds. Thus, I'm missing some data. I added a time stamp every time when I collect data using Raspberry's clock_gettime -function. The time stamp revealed that about every second there is something happening, which messes up the data logging (figures below). I tried with different sampling frequencies (200-800Hz) but the same thing happened. I connected the Raspberry's PWM pin straight to a pin, which detects when the data is ready to be transferred (so I removed the sensor out of the circuit). Still about every second I miss some PWM signals. Then I generated a square signal from signal generator to ensure that the problem is not in the PWM signal that the Raspberry is generating. It is not.

So I'm asking if there is some background program running in Raspberry Pi that causes the delay or if somebody know why this is happening?

I attached a code and some plots about the time differences between samples with couple different sampling frequencies.

#include <bcm2835.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>

#define DR              24  //DR pin number

#define STALL           50  //delay microseconds to make sure that the code runs without problems

#define SYNC            13  //SYNC pin number(PWM)
#define PWM_CHANNEL     1   //Controlled by PWM channel 1
#define RANGE           6 //Max range of the PWM signal
#define CLOCK_DIVIDER   4000 //clock divider for PWM


int initialize(void){
    if (!bcm2835_init()){
        printf("bcm2835_init failed. Are you running as root??\n");
        return -1;
    }

bcm2835_gpio_fsel(DR, BCM2835_GPIO_FSEL_INPT); //setting DR as an input pin

bcm2835_gpio_fsel(13,BCM2835_GPIO_FSEL_ALT0 ); //Set the output pin to Alt Fun 0, to allow PWM channel 1 to be output there    
bcm2835_pwm_set_clock(CLOCK_DIVIDER); // Set PWM clock divider 19.2 MHz / 4000 = 4800 Hz
bcm2835_pwm_set_mode(PWM_CHANNEL, 1, 1); // PWM channel, MARKSPACE mode, true
bcm2835_pwm_set_range(PWM_CHANNEL, RANGE); // 4800 Hz / RANGE (6) = 800 Hz
bcm2835_pwm_set_data(PWM_CHANNEL, RANGE/2); // Set pulse ratio to 50/50

return 0;
}

int main(int argc, char **argv){
   int suc = initialize();
   FILE *filePointer; // create pointer to a file

   struct timespec ts; // time stamp for data


   if (suc!=0){ //checking to see if the settings were successfully applied
     printf("Reboot");
     return -1;
   }
   else{
     char fileName[64]; //filename space
     printf("Please enter filename where you want to store the data\n"); // ask for the file name
     scanf("%s",&fileName); // copy the text to filename
     filePointer = fopen(("%s",fileName), "w"); // open the file
   }

if (filePointer != NULL){
    int i = 1;
    while (i <= 8000){ // gather data for 10 seconds
      if (bcm2835_gpio_lev(DR) == 1){ // detects if DR pin is high
        clock_gettime(CLOCK_MONOTONIC_RAW, &ts); // storing time stamp
        fprintf(filePointer, "%ld\t %ld\n", ts.tv_sec, ts.tv_nsec); // write the data to the file 
        i++;
        while (bcm2835_gpio_lev(DR) == 1){
          bcm2835_delayMicroseconds(1); // wait till DR pin is low
        }
      }
    }
    printf("\n");
    fclose(filePointer); //close the file
    bcm2835_spi_end();  //end spi mode on rpi
}
else{
    printf("Error, file was not created correctly.");
}

return 0;
}

Times between samples with 200Hz

Times between samples with 800Hz

  • 1
    I don't see how that code could work reliably. What happens when your process is rescheduled because another task needs to run? Neither do I understand what you are doing. What are the Pi input signals? What are the outputs? – joan Jun 6 at 7:47
  • Regarding the question of "background programs running" - the answer is "yes!" All of Linux, its demons, the packages that were installed by default.... If you need to control every clock cycle, use Arduino or some microcontroller that doesn't run a general purpose OS. – Brick Jun 6 at 14:17
0

Question

  1. RpiZW send PWM signal of 800Hz to control sampling frequency.

  2. About every second something happening, messes up data logging.

  3. With different sampling frequencies (200-800Hz) same thing happened.

  4. Remove sensor out of the circuit, Rpi PWM pin straight to a pin, detects data ready

  5. Still about every second I miss some PWM signals.

  6. Why?

Answer

Well, Rpi is not a MCU like Arduino which you can program it to do one and only one thing, say, in your case, generating PWM signals, and almost nothing else.

On the other hand, Rpi linux is kind of UNIX operating system, which is a multitasking/multiprocessing operating system, doing many jobs/processes/tasks in the foreground and background, like entertaining peripherals (input/out things for keyboard and mouse etc), memory (RAM/Flash) management process/task/job scheduling.

In other words, your PWM program get interrupted from time to time (in your case, about once per second) when the linux guy diverts to do its more important jobs, and pauses (preempts) the your less important PWM job.

The trouble/problem is that the little user application program guy almost cannot do any thing to pause the big housekeeping linux guy.

A get around is instead of RpiZ raspbian, use MCU like arduino/ESP8266/CircuitPython, which serves only one master, your PWM program, and almost nothing else.

I am not surprised that you find my explanation confusing. You might like to read the following Wikipedia article abstract to see why I am confusing you.

References

Multiprocessing [Operationg System] - Wikipedia

Multiprocessing is the use of two or more central processing units (CPUs) within a single computer system. The term also refers to the ability of a system to support more than one processor or the ability to allocate tasks between them. There are many variations on this basic theme, and the definition of multiprocessing can vary with context, mostly as a function of how CPUs are defined ...

A multiprocessor is a computer system having two or more processing units (multiple processors) each sharing main memory and peripherals, in order to simultaneously process programs. A 2009 textbook defined multiprocessor system similarly, but noting that the processors may share "some or all of the system’s memory and I/O facilities"; it also gave tightly coupled system as a synonymous term.

At the operating system level, multiprocessing is sometimes used to refer to the execution of multiple concurrent processes in a system, with each process running on a separate CPU or core, as opposed to a single process at any one instant.

When used with this definition, multiprocessing is sometimes contrasted with multitasking, which may use just a single processor but switch it in time slices between tasks (ie a time-sharing system).

Multiprocessing however means true parallel execution of multiple processes using more than one processor. Multiprocessing doesn't necessarily mean that a single process or task uses more than one processor simultaneously; the term parallel processing is generally used to denote that scenario. Other authors prefer to refer to the operating system techniques as multiprogramming and reserve the term multiprocessing for the hardware aspect of having more than one processor.

*Micro Controller and Micro Controller Unit (MCU) - The Computer Language Company*

Microcontroller is a single chip that contains the processor (CPU), non-volatile memory (flash memory or ROM) for the program, volatile memory (RAM) for processing the data, a clock and an I/O control unit. Microcontroller units (MCUs) are available in numerous sizes and architectures.

They Don't Get the Publicity

Because MCUs contain only 8-, 16- or 32-bit CPUs and cost just a few dollars or even less than one dollar, they do not get the mainstream attention as do the latest 64-bit chips in a PC or graphics card, which cost several hundred dollars. MCUs also do not require the state-of-the-art chip technology.

However, MCUs are everywhere, and billions of these "computers on a chip" are embedded in products from toys to appliances to just about anything. New cars can employ a couple hundred of them. For example, an entire MCU might be dedicated to a simple task such as waiting for the driver to close the car door or press a particular button on the dashboard. See embedded system and automotive systems.

Motorola 6801 - One of the First

Introduced in 1978, the 6801 was one of the first semiconductor products to claim the "computer on a chip" moniker. These magnified images show the entire chip (top), about three quarters of the 256 bytes of RAM (left) and only a few bytes at 400x.

They Don't Get Much Smaller

These 8-bit PIC brand microcontrollers from Microchip are used in myriad applications, cost less than 50 cents each and are much more powerful than the 6801. We're not great technology predictors. In 1949, Popular Mechanics speculated that future computers would only weigh "one and a half tons!"

A Microcontroller Behind Everything

Today's cars can have more than a hundred MCUs, each one controlling the simplest function from pressing a button to more complicated systems like the ones in the Honda above.

mcu picture

MCU ESP32/ESP8266 - Sara Santos 2019may01

SBC (Single Board Computer) - Wikipedia

A single-board computer (SBC) is a complete computer built on a single circuit board, with microprocessor(s), memory, input/output (I/O) and other features required of a functional computer. Single-board computers were made as demonstration or development systems, for educational systems, or for use as embedded computer controllers. Many types of home computers or portable computers integrate all their functions onto a single printed circuit board.

Unlike a desktop personal computer, single board computers often do not rely on expansion slots for peripheral functions or expansion. Single board computers have been built using a wide range of microprocessors. Simple designs, such as those built by computer hobbyists, often use static RAM and low-cost 8- or 16-bit processors. Other types, such as blade servers, would perform similar to a server computer, only in a more compact format.

Single board computers were made possible by increasing density of integrated circuits. A single-board configuration reduces a system's overall cost, by reducing the number of circuit boards required, and by eliminating connectors and bus driver circuits that would otherwise be used. By putting all the functions on one board, a smaller overall system can be obtained, for example, as in notebook computers. Connectors are a frequent source of reliability problems, so a single-board system eliminates these problems.

Single board computers are most commonly used in industrial situations where they are used in rackmount format for process control or embedded within other devices to provide control and interfacing. Because of the very high levels of integration, reduced component counts and reduced connector counts, SBCs are often smaller, lighter, more power efficient and more reliable than comparable multi-board computers.

SBC 2019 Global Update - MedicalMarketReport 2019jun06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.