{"id":982,"date":"2016-07-05T15:33:06","date_gmt":"2016-07-05T23:33:06","guid":{"rendered":"http:\/\/www.beyond-circuits.com\/wordpress\/?page_id=982"},"modified":"2018-09-17T16:55:06","modified_gmt":"2018-09-18T00:55:06","slug":"tutorial24","status":"publish","type":"page","link":"https:\/\/www.beyond-circuits.com\/wordpress\/tutorial\/tutorial24\/","title":{"rendered":"Tutorial 24: Controlling a SPI device through embedded Linux"},"content":{"rendered":"<h1>Overview<\/h1>\n<p>In this <a href=\"https:\/\/www.beyond-circuits.com\/wordpress\/wp-content\/uploads\/2016\/06\/MAX5216PMB1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-medium wp-image-983 alignright\" src=\"https:\/\/www.beyond-circuits.com\/wordpress\/wp-content\/uploads\/2016\/06\/MAX5216PMB1-300x147.png\" alt=\"MAX5216PMB1\" width=\"300\" height=\"147\" srcset=\"https:\/\/www.beyond-circuits.com\/wordpress\/wp-content\/uploads\/2016\/06\/MAX5216PMB1-300x147.png 300w, https:\/\/www.beyond-circuits.com\/wordpress\/wp-content\/uploads\/2016\/06\/MAX5216PMB1-768x376.png 768w, https:\/\/www.beyond-circuits.com\/wordpress\/wp-content\/uploads\/2016\/06\/MAX5216PMB1-500x245.png 500w, https:\/\/www.beyond-circuits.com\/wordpress\/wp-content\/uploads\/2016\/06\/MAX5216PMB1.png 958w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a>tutorial, I will cover writing a Linux application to control a SPI device connected to the ZedBoard JA1 PMOD connector. In this example, I am using a <a href=\"https:\/\/www.maximintegrated.com\/en\/products\/analog\/data-converters\/analog-to-digital-converters\/MAX5216PMB1.html\">MAX5216PMB1<\/a>\u00a016-bit DAC module. Maxim makes an <a href=\"https:\/\/www.maximintegrated.com\/en\/app-notes\/index.mvp\/id\/5468\">Analog Essentials Collection<\/a> kit of PMOD boards that I highly recommend. You can buy the kit from Maxim or on DigiKey for about $100.<\/p>\n<p>The code that we will be using does a couple of things. First, it maps the four GPIO units into the address space of the application using the mmap function.<\/p>\n<p>It then has a couple of different modes that you can select using the buttons. One mode allows you to enter values on the keyboard, and then writes the value to the DAC. Another mode computes a sine wave and sends that out the DAC. There are also modes to read the buttons and switch settings, and to write the LEDs.<\/p>\n<h1>Accessing the GPIO Registers<\/h1>\n<p>The important part of our Linux program is accessing the registers for the GPIO blocks in the FPGA. These registers are memory mapped, so we access them by reading and writing memory. We use the <em>mmap<\/em> kernel function to map the physical addresses into our running program.<\/p>\n<p>First, we declare pointers to the base address of each GPIO unit and come constants that hold the base physical address of each unit:<\/p>\n<pre>static volatile uint32_t *buttons;\r\nstatic volatile uint32_t *switches;\r\nstatic volatile uint32_t *leds;\r\nstatic volatile uint32_t *pmod;\r\n\r\nstatic const uint32_t buttons_addr = 0x41200000;\r\nstatic const uint32_t leds_addr = 0x41210000;\r\nstatic const uint32_t switches_addr = 0x41220000;\r\nstatic const uint32_t pmod_addr = 0x41230000;\r\n\r\n<\/pre>\n<p>To use <em>mmap<\/em>, we first need to open the device file <em>\/dev\/mem<\/em>. We are going to map offsets in\u00a0this file into our address space. We wrap the <em>open<\/em> and <em>mmap<\/em> calls in a function called <em>map_gpios<\/em>.<\/p>\n<pre>void map_gpios(void)\r\n{\r\n int fd;\r\n\r\nif ((fd = open(\"\/dev\/mem\", O_RDWR|O_SYNC)) &lt; 0)\r\n\r\nif (fd &lt; 0) {\r\n perror(\"\/dev\/mem\");\r\n exit(-1);\r\n }\r\n\r\nif ((buttons = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, buttons_addr))\r\n == MAP_FAILED) {\r\n perror(\"buttons\");\r\n exit(-1);\r\n }\r\n\r\nif ((leds = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, leds_addr))\r\n == MAP_FAILED) {\r\n perror(\"leds\");\r\n exit(-1);\r\n }\r\n\r\nif ((switches = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, switches_addr))\r\n == MAP_FAILED) {\r\n perror(\"switches\");\r\n exit(-1);\r\n }\r\n\r\nif ((pmod = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, pmod_addr))\r\n == MAP_FAILED) {\r\n perror(\"pmod\");\r\n exit(-1);\r\n }\r\n}<\/pre>\n<h1>Writing to the SPI interface<\/h1>\n<p>We also need to create a function which will write to the MAX5216 ADC using its SPI interface. We will declare some constants which indicate the bit positions within the GPIO register that correspond to the three SPI pins that go to the MAX5216 device.<\/p>\n<pre>const int SPI_DATA_POS = 1;\r\nconst int SPI_CS_POS = 0;\r\nconst int SPI_CLOCK_POS = 3;\r\n<\/pre>\n<p>Unlike the GPIO units for the LEDs, buttons, and switches, the GPIO pins for the PMOD can function as either inputs or outputs. So this unit has a second register which controls the direction of the corresponding pin. For our purposes, we only need to drive the pins as outputs, but we need to initialize the unit by writing zero to this direction control register. Also, the SPI chip select is active low so we need to write that bit to a 1 so that we are not selecting the DAC by default.<\/p>\n<pre>void init_spi(volatile uint32_t *port)\r\n{\r\n  \/* Set all GPIO pins to output *\/\r\n  *(port+1) = 0;\r\n\r\n  \/* Set chip select high (inactive)*\/\r\n  *port = 1 &lt;&lt;SPI_CS_POS;\r\n}\r\n<\/pre>\n<p>Next, we need a function to write to the SPI interface. The interface takes a 24-bit value. There are two control bits in bits 22-23 of the SPI data word which need to be set to 01<sub>2<\/sub> to write to the DAC output register. These bits are then followed by 16 data bits and 6 zero bits. Data is captured on the falling edge of the SPI clock. Here is the function to write to the SPI interface:<\/p>\n<pre>void write_spi(volatile uint32_t *port, uint16_t value)\r\n{\r\n  int i;\r\n  uint32_t shift = (value &lt;&lt; 6)|(1&lt;&lt;22); *port = 0; \r\n  for (i=23; i&gt;= 0; i--) {\r\n    *port =\r\n      (((shift&gt;&gt;i)&amp;1)&lt;&lt;SPI_DATA_POS) | 1&lt;&lt;SPI_CLOCK_POS; \r\n    *port = \r\n      (((shift&gt;&gt;i)&amp;1)&lt;&lt;SPI_DATA_POS);\r\n  }\r\n  *port = 1&lt;&lt;SPI_CS_POS;\r\n}\r\n<\/pre>\n<h1>User inputs<\/h1>\n<p>There are five different demo modes for the program. One just lets you type a value to write to the DAC, while another generates a sine output out of the DAC. Other modes let you read button or switch values, or write to the LEDs. We use a function to print a menu of options and read the user selection.<\/p>\n<pre>const int value_mode = 1;\r\nconst int sine_mode = 2;\r\nconst int buttons_mode = 3;\r\nconst int switches_mode = 4;\r\nconst int leds_mode = 5;\r\nconst int exit_mode = 0;\r\n\r\nstatic int select_mode(void)\r\n{\r\n  int mode;\r\n  printf(\"Select one of the following modes:\\r\\n\");\r\n  printf(\"%0d) Enter a value to write to the DAC.\\r\\n\",value_mode);\r\n  printf(\"%0d) Output a sine wave.\\r\\n\",sine_mode);\r\n  printf(\"%0d) Read the buttons.\\r\\n\",buttons_mode);\r\n  printf(\"%0d) Read the switches.\\r\\n\",switches_mode);\r\n  printf(\"%0d) Enter a value to write to the LEDs.\\r\\n\",leds_mode);\r\n  printf(\"%0d) Exit the demo.\\r\\n\",exit_mode);\r\n  scanf(\"%d\",&amp;mode);\r\n  return mode;\r\n}\r\n<\/pre>\n<h1>Set the DAC output to a value<\/h1>\n<p>Here is the function which reads a numeric value and then sets the DAC output to that value:<\/p>\n<pre>static void run_value_mode(void)\r\n{\r\n  int value;\r\n  printf(\"Enter a negative value to exit DAC mode.\\r\\n\");\r\n  do {\r\n    printf(\"Enter a 16-bit number in decimal: \");\r\n    scanf(\"%d\",&amp;value);\r\n    write_spi(pmod,value);\r\n  } while (value &gt;= 0);\r\n}\r\n<\/pre>\n<h1>Sine output<\/h1>\n<p>This function writes a sine wave out the DAC. It runs until the user presses one of the buttons on the ZedBoard.<\/p>\n<pre>static void run_sine_mode(void)\r\n{\r\n  int value = 0;\r\n  float angle = 0.0;\r\n  float sine_value;\r\n  float phase_increment;\r\n  const float radians_per_degree = M_PI \/ 180.0;\r\n\r\n\r\n  printf(\"Enter a phase increment in degrees: \");\r\n  scanf(\"%f\",&amp;phase_increment);\r\n  printf(\"Generating a sine wave with phase increment %0f degrees.\\r\\n\");\r\n  printf(\"Press any button to end the demo.\\r\\n\");\r\n  \r\n  phase_increment = phase_increment * radians_per_degree;\r\n\r\n  do {\r\n    sine_value = sinf(angle);\r\n    angle += phase_increment;\r\n    value = (sine_value+1.0)*32767.0;\r\n    *leds = value &gt;&gt; 8;\r\n    write_spi(pmod,value);\r\n  } while (*buttons == 0);\r\n}\r\n<\/pre>\n<h1>LEDs, buttons, and switches<\/h1>\n<p>These functions set the LEDs, and read the button and switch values:<\/p>\n<pre>static void run_buttons_mode(void)\r\n{\r\n  printf(\"Buttons value is %0d\\r\\n\",*buttons);\r\n}\r\n\r\nstatic void run_switches_mode(void)\r\n{\r\n  printf(\"Switches value is %0d\\r\\n\",*switches);\r\n}\r\n\r\nstatic void run_leds_mode(void)\r\n{\r\n  int val;\r\n  printf(\"Enter a value to set the LEDs to: \");\r\n  scanf(\"%d\",&amp;val);\r\n  *leds = val;\r\n}\r\n<\/pre>\n<h1>Main program<\/h1>\n<p>And here is the main function to wrap it all together:<\/p>\n<pre>int main()\r\n{\r\n  int mode;\r\n\r\n  map_gpios();\r\n  init_spi(pmod);\r\n\r\n  do {\r\n    mode = select_mode();\r\n    if (mode == value_mode)\r\n      run_value_mode();\r\n    else if (mode == sine_mode)\r\n      run_sine_mode();\r\n    else if (mode == buttons_mode)\r\n      run_buttons_mode();\r\n    else if (mode == switches_mode)\r\n      run_switches_mode();\r\n    else if (mode == leds_mode)\r\n      run_leds_mode();\r\n  } while (mode != exit_mode);\r\n      \r\n  return 0;\r\n}\r\n<\/pre>\n<p>Of course you will need some includes at the top of the program. Here they are:<\/p>\n<pre>#include &lt;unistd.h&gt;\r\n#include &lt;stdio.h&gt;\r\n#include &lt;fcntl.h&gt;\r\n#include &lt;string.h&gt;\r\n#include &lt;math.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n#include &lt;stdint.h&gt;\r\n#include &lt;sys\/types.h&gt;\r\n#include &lt;sys\/mman.h&gt;\r\n<\/pre>\n<p>You can find a link to the file <a href=\"https:\/\/www.beyond-circuits.com\/repos\/tutorial\/trunk\/sw\/max5216pmb1.c\">here<\/a>.<\/p>\n<h1>Compiling and running the program<\/h1>\n<p>The simplest thing to do to compile the program is to use the command line GCC compiler. If you have set up Petalinux by sourcing the settings.sh script, then you can invoke the compiler and compile the program like this:<\/p>\n<pre>% arm-xilinx-linux-gnueabi-gcc max5216pmb1.c -lm -o max5216pmb1\r\n<\/pre>\n<p>This will build an ARM binary called max5216pmb1, which you can copy to the ZedBoard and run. I usually use the SSH copy command <em>scp<\/em> to copy the file to the board. You can find out the IP address of the ZedBoard by typing ifconfig in the serial console window once you have logged in.<\/p>\n<p>From the serial console on the ZedBoard\u00a0first login to the console. Use <strong>root<\/strong> as the username and password.<\/p>\n<pre>Avnet-Digilent-ZedBoard-2015_4 login: root\r\nPassword: \r\nlogin[918]: root login on 'ttyPS0'\r\nroot@Avnet-Digilent-ZedBoard-2015_4:~# \r\n<\/pre>\n<p>Then issue the command <em>ifconfig<\/em>.<\/p>\n<pre>root@Avnet-Digilent-ZedBoard-2015_4:~# ifconfig\r\neth0      Link encap:Ethernet  HWaddr 00:0A:35:00:1E:53  \r\n          inet addr:10.0.0.59  Bcast:10.0.0.255  Mask:255.255.255.0\r\n          inet6 addr: fe80::20a:35ff:fe00:1e53\/64 Scope:Link\r\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\r\n          RX packets:36 errors:0 dropped:0 overruns:0 frame:0\r\n          TX packets:19 errors:0 dropped:0 overruns:0 carrier:0\r\n          collisions:0 txqueuelen:1000 \r\n          RX bytes:3902 (3.8 KiB)  TX bytes:3175 (3.1 KiB)\r\n          Interrupt:145 Base address:0xb000 \r\n\r\nlo        Link encap:Local Loopback  \r\n          inet addr:127.0.0.1  Mask:255.0.0.0\r\n          inet6 addr: ::1\/128 Scope:Host\r\n          UP LOOPBACK RUNNING  MTU:65536  Metric:1\r\n          RX packets:0 errors:0 dropped:0 overruns:0 frame:0\r\n          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0\r\n          collisions:0 txqueuelen:0 \r\n          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)\r\n\r\nroot@Avnet-Digilent-ZedBoard-2015_4:~# \r\n<\/pre>\n<p>This shows that on my network the IP address of my board is 10.0.0.59.<\/p>\n<p>Copy the executable to the ZedBoard using the <em>scp<\/em> command. From your workstation type the following:<\/p>\n<pre>% scp max5216pmb1 root@10.0.0.59:\r\n<\/pre>\n<p>You will need to give the root password <strong>root<\/strong>.<\/p>\n<p>Then from the console window run the program like this:<\/p>\n<pre>root@Avnet-Digilent-ZedBoard-2015_4:~# .\/max5216pmb1\r\n<\/pre>\n<p>The program should then run.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Overview In this tutorial, I will cover writing a Linux application to control a SPI device connected to the ZedBoard JA1 PMOD connector. In this example, I am using a MAX5216PMB1\u00a016-bit DAC module. Maxim makes an Analog Essentials Collection kit &hellip; <a href=\"https:\/\/www.beyond-circuits.com\/wordpress\/tutorial\/tutorial24\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"parent":226,"menu_order":24,"comment_status":"open","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-982","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/pages\/982","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/comments?post=982"}],"version-history":[{"count":10,"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/pages\/982\/revisions"}],"predecessor-version":[{"id":1229,"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/pages\/982\/revisions\/1229"}],"up":[{"embeddable":true,"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/pages\/226"}],"wp:attachment":[{"href":"https:\/\/www.beyond-circuits.com\/wordpress\/wp-json\/wp\/v2\/media?parent=982"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}