{"id":704,"date":"2022-01-02T19:21:56","date_gmt":"2022-01-02T19:21:56","guid":{"rendered":"https:\/\/samndave.org.uk\/ourdoc\/?p=704"},"modified":"2025-07-10T16:11:33","modified_gmt":"2025-07-10T16:11:33","slug":"pi-rover-robot-4-raspberry-pi-pico-as-a-slave","status":"publish","type":"post","link":"https:\/\/samndave.org.uk\/index.php\/2022\/01\/02\/pi-rover-robot-4-raspberry-pi-pico-as-a-slave\/","title":{"rendered":"Pi Rover Robot #4: Raspberry Pi Pico as a slave"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">All code in this example is included in the&nbsp;<a href=\"https:\/\/github.com\/DaveHartburn\/Pi-rover-robot\">GitHub repository<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When looking at adding a pan\/tilt camera mount, I ran into a number of problems with the Raspberry Pi and serving PWM (see <a href=\"https:\/\/samndave.org.uk\/2021\/12\/26\/9g-micro-server-sg9-performance\/\" data-type=\"post\" data-id=\"603\">9g Micro Servo performance<\/a>). All series of Raspberry Pi (excluding the Pico) run PWM in software. While there are two hardware channels (<a href=\"https:\/\/pypi.org\/project\/rpi-hardware-pwm\/\">pypi.org<\/a>), I was going to look to these to hardware drive the main motors. This only leaves software PWM available for any servos or other hardware added later. While giving poor performance for servo motors, any software PWM is taking away CPU from any more advanced functions, especially as I look at AI in the future.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A Raspberry Pi Pico is different to a traditional Pi and does not run an operating system. You write and upload a single program, which it directly executes, very similar to an Arduino. It has 16 PWM channels and my tests found it was very good at driving even very cheap servos. Many people have used an Arduino as a slave device in robotic projects, but I have decided to use a Pico. First it is very cheap, at under \u00a35. Secondly, the RP2040 chip it is based on has two cores. This should allow multi-threading, with one thread continually polling sensors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As I add more sensors (especially ultrasonic distance sensors), any operations performed directly via the main Pi, will add delay while everything is polled. In theory the Pico should be able to continually poll sensors and present results to the main Pi (referred to as just &#8216;the Pi&#8217; or &#8216;controller&#8217; from now on) on request.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Communication between devices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There are three ways a Pi can connect to and communicate with a Pico, I2C, SPI or UART (serial). Each protocol has it&#8217;s advantages and there are many articles available on the matter. One thing all tend to agree on is that UART is easier and quick to get up and running. I have chosen to use this but may look to one of the other protocols if I get performance issues. It is not rated as the fastest or most efficient of the three protocols.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Similarly, I need to decide on a language. The Pico can be programmed in C\/C++ or MicroPython. Compiled C is more efficient, however a number of tests have shown performance under MicroPython is very good. I originally decided to use MicroPython, as so far the rest of the code has been in Python (except the shell scripts and JavaScript in the web interface). There did not seem to be a need to add another language at this point. However (edit since I originally published this post), at the time of writing, multithreadding support for the Pico was considered buggy (version v1.17, published 2nd September 2021). This seems especially true when using the UART. As this is exactly what I wanted to do for the next stage, I have had to backtrack a little to investigate C++. I have used the Arduino IDE to develop the code. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">All test programs are in the GitHub repository in the <a href=\"https:\/\/github.com\/DaveHartburn\/Pi-rover-robot\/tree\/main\/pico\/testing\">testing directory<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">UART\/Serial on the Pico<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Raspberry Pi Pico has two pins for UART channel 0, GPIO 0 (Tx, pyhsical pin 1) and GPIO 1 (Rx, pin 2). When connecting to another serial device, Tx goes to Rx on the other device and Rx to Tx. They must also share a common ground. To test communications, I needed a USB to serial adaptor. I had a Particle Debugger device that I had not used for anything, which does provide serial. However a USB FTDI adaptor such as FT232R (also pictured) will also work.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"590\" height=\"395\" src=\"http:\/\/samndave.org.uk\/wp-content\/uploads\/2022\/01\/pico-serial.png\" alt=\"\" class=\"wp-image-708\" srcset=\"https:\/\/samndave.org.uk\/wp-content\/uploads\/2022\/01\/pico-serial.png 590w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2022\/01\/pico-serial-300x201.png 300w\" sizes=\"auto, (max-width: 590px) 100vw, 590px\" \/><\/figure><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">When plugging in the USB to Serial adaptor, it should register as a serial port (dmesg on Linux (\/dev\/tty???) or Device Manager on Windows (COM?)). There are a number of serial terminal applications that should talk to the device, screen on Linux, PuTTY on Windows or I used the Arduino IDE (both Windows and Linux). This has the advantage of being able to send complete strings.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Python<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The following program will initiate the UART service on GPIO0 and GPIO1, print the current status and then go into a loop toggling the onboard LED, printing the status to the Thonny shell while also sending the status out to the serial console. Any input from the console will show in the shell as &#8216;Data Received&#8217;.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Basic Pi -&gt; Pico communication test\n# This part to be run on the pico\n\nfrom machine import Pin\nimport machine\nimport time\n\nled=Pin(25, Pin.OUT)\nuart = machine.UART(0, 115200)\nprint(uart)\n\nuart.write(\"Hello from pico\\n\")\ntime.sleep(0.2)\n\nwhile True:\n    if uart.any():\n        print(\"Data received\")\n        rawIn = uart.readline()\n        #print(rawIn)\n        # Raw data is as a byte stream. Convert\n        # Need to use a try\/except as control characters may cause an issue\n        try:\n            dataIn = rawIn.decode('utf-8').strip()\n            # Remove new lines\n            #dataIn.strip()\n            print(\"Incoming :\", dataIn)\n        except:\n            pass\n    led.toggle()\n    print(\"LED status = \", led.value())\n    x = led.value()\n    uart.write(f\"LED status {x}\\n\")\n    time.sleep(0.5)\n<\/code><\/pre>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"692\" src=\"http:\/\/samndave.org.uk\/wp-content\/uploads\/2022\/01\/pico-seral-ss-1024x692.png\" alt=\"\" class=\"wp-image-710\" srcset=\"https:\/\/samndave.org.uk\/wp-content\/uploads\/2022\/01\/pico-seral-ss-1024x692.png 1024w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2022\/01\/pico-seral-ss-300x203.png 300w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2022\/01\/pico-seral-ss-768x519.png 768w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2022\/01\/pico-seral-ss.png 1249w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Screenshot of Thonny running the UART test code, having received the string &#8216;hello there&#8217; from the Arduino IDE<\/figcaption><\/figure><\/div>\n\n\n\n<h4 class=\"wp-block-heading\">C++<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A great place to look for code guidance in C is <a href=\"https:\/\/github.com\/raspberrypi\/pico-examples\">https:\/\/github.com\/raspberrypi\/pico-examples<\/a>. The UART code is based on the example from there.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The C version of the above code is very similar, making use of the C uart libraries. It reads the UART a character at a time with <code>uart_getc<\/code> rather than the whole buffer with <code>uart_read_blocking<\/code>. On initialisation, there is always one byte of data it appears to think it has received. Trying to read a full string caused a block, so instead I have a loop which reads one character at a time and puts this into a buffer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Note: In the Pico SDK, the standard is to use a &#8216;int main()&#8217; function where I&#8217;m using the traditional Arduino method of setup() and loop(). <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Basic Pi -&gt; Pico communication test in C++\n\/\/ This part to be run on the pico\n\/\/ UART reference at https:\/\/raspberrypi.github.io\/pico-sdk-doxygen\/group__hardware__uart.html\n\n#include &lt;stdio.h&gt;\n#include \"pico\/stdlib.h\"\n#include \"hardware\/uart.h\"\n\n\/\/ Define the UART and the standard UART pins\n#define UART uart0\n#define BAUD_RATE 115200\n#define UART_TX_PIN 0\n#define UART_RX_PIN 1\n\n#define LED LED_BUILTIN\n\nvoid setup() {\n  Serial.begin(115200);\n  Serial.println(\"Pico UART test\");\n\n  \/\/ Initialise the UART\n  uart_init(UART, BAUD_RATE);\n  \/\/ Convert line feeds to carriage returns to avoid\n  \/\/ hello\n  \/\/      hello\n  \/\/           hello\n  uart_set_translate_crlf(UART, true);\n  \/\/ The first few characters are often corrupt. Send two lines to indicate start\n  uart_puts(UART, \"INIT\\n\\n\");\n  uart_puts(UART, \"Hello from Pico\\n\");\n  \n  \/\/ Set the TX and RX pins by using the function select on the GPIO\n  \/\/ Set datasheet for more information on function select\n  gpio_set_function(UART_TX_PIN, GPIO_FUNC_UART);\n  gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART);\n\n  \/\/ Init the onboard LED\n  gpio_init(LED);\n  gpio_set_dir(LED, GPIO_OUT);\n}\n\nbool l=0;\nchar msgOut&#91;255];\nchar msgIn&#91;255];\n\nvoid loop() {\n  \/\/ Check for input\n  if(uart_is_readable(UART)) {\n    Serial.println(\"Data received\");\n    uart_puts(UART, \"Data received\\n\");\n    int i=0;\n    while (uart_is_readable(UART) &amp;&amp; i&lt;255) {\n      char ch = uart_getc(UART);\n      msgIn&#91;i++]=ch;\n      Serial.print('.');\n    }\n    Serial.print(\"\\n\");\n    Serial.print(\"Message in:\");\n    Serial.print(msgIn);\n    uart_puts(UART,\"Message in:\");\n    uart_puts(UART,msgIn);\n  }\n  \/\/ Toggle LED value\n  l=!l;\n  gpio_put(LED, l);\n\n  \/\/ Prepare outgoing message\n  sprintf(msgOut, \"LED status = %d\\n\", l);\n\n  \/\/ To standard serial console (string has new line)\n  Serial.print(msgOut);\n  \/\/ Send a UART string\n  uart_puts(UART, msgOut);\n  delay(500);\n\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It is also possible to interrupt on receiving UART data, though I have chosen not to use this at the moment.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">UART\/Serial on the Pi<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To use UART\/Serial on a Pi, the serial interface must be enabled in raspi-config as below. Note, this uses the miniUART rather than the PL011 UART. While PL011 is considered faster and more reliable, using this disables Bluetooth functions which I am going to need later.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>sudo raspi-config<\/code><\/li><li>3 &#8211; Interface Options<\/li><li>P6 Serial Port<\/li><li>&#8216;Would you like a login shell to be accessible over serial?&#8217;<ul><li>Answer &#8216;No&#8217;<\/li><\/ul><\/li><li>&#8216;Would you like the serial port hardware to be enabled?&#8217;<ul><li>Answer &#8216;Yes&#8217;<\/li><\/ul><\/li><li>Reboot<\/li><li>On restart, &#8216;ls -l \/dev\/ttyS0&#8217;, should show the serial device is now present.<\/li><li><code>echo test &gt; \/dev\/ttyS0<\/code><ul><li>The serial console software must be set to 9600 baud to receive this text<\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Now the following program can be run to test serial input and output. An increasing value of x is sent to the serial port, but each time around the loop, it checks for an incoming message and will display it. The dot as it receives each chunk of incoming data shows read_until is pulling the data as one chunk. Changing this to &#8216;.read(1)&#8217; will show each byte arriving. Note the baud rate changed back to 115200 from the test at 9600 above.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/python\n\n# Com test - Pi end\n# Run this bit on the Pi for basic UART\/Serial communication\n\nimport serial\nimport time\n\n# Init serial port and print details\nsport = serial.Serial(\"\/dev\/ttyS0\", 115200)\nprint(sport)\n\nprint(\"Serial test 1 - Run on the Pi not the Pico\")\ndata=\"Hello from Pi\\n\".encode('UTF-8')\nsport.write(data)\n\nx = 0\nwhile True:\n\t# Check for incoming data\n\tif(sport.in_waiting &gt; 0):\n\t\trawIn = bytearray()\n\t\twhile (sport.in_waiting &gt; 0):\n\t\t\t# Read until will read until we get a line ending\n\t\t\trawIn += sport.read_until()\n\t\t\tprint('.',end='')\n\t\tprint(\"\")\n\t\tprint(\"Data Received\")\n\t\t#print(rawIn)\n\t\t\n\t\t# Raw data is a byte stream, convert\n\t\t# Need to use a try\/except as control characters may cause an issue\n\t\ttry:\n\t\t\tdataIn = rawIn.decode('utf-8').strip()\n\t\t\tprint(\"  Incoming :\", dataIn)\n\t\texcept:\n\t\t\tprint(\"Unable to decode\")\n\t\t\n\t# Output an incremental counter\n\tmsg = \"x = {}\\n\".format(x)\n\tprint(\"Sending:\",msg,end='')\n\tdata=msg.encode('UTF-8')\n\tsport.write(data)\n\tx+=1\n\ttime.sleep(1)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Two way communication<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now we have established both devices can communicate over GPIO pins, we can test the following workflow:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The Pico will run with two threads:<ul><li>One thread will loop generating an array of 6 random values to simulate sensor readings<\/li><li>The other thread will watch for incoming serial communications, three commands may be sent<ul><li>&#8216;dataRequest&#8217; will request all sensor data to be returned as a JSON string<\/li><li>&#8216;toggleLED&#8217; will toggle the onboard LED<\/li><li>&#8216;quit&#8217; will terminate the Pico processes (reset then required)<\/li><\/ul><\/li><\/ul><\/li><li>The Pi will sit in a loop periodically issuing &#8216;dataRequest&#8217; and &#8216;toggleLED&#8217; commands at different intervals.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Before starting the Pi and Pico must be connected together as follows:<\/p>\n\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\" style=\"flex-basis:100%\">\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Pi GPIO<\/th><th>Pico<\/th><\/tr><\/thead><tbody><tr><td>GPIO14 (Tx) &#8211; Pin 8<\/td><td>GP1 (Rx) &#8211; Pin 2<\/td><\/tr><tr><td>GPIO15 (Rx) &#8211; Pin 10<\/td><td>GP0 (Tx) &#8211; Pin 1<\/td><\/tr><tr><td>GND &#8211; Any pin<\/td><td>GND &#8211; Any pin<\/td><\/tr><\/tbody><\/table><\/figure>\n<\/div>\n<\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Multithreadding the Pico<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Tip: When working with multiple threads the Pico can fail to terminate or act on a stop press on Thonny, if the second thread is running. Connecting any GND pin to pin 30 (RUN) will cause a reset. Add a button between these pins as a reset button.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Having two cores, the pico can run multithreadded. A function called sensorThread will sit in a loop until the global variable checkSensors is set to False. At which point the function terminates and the thread ends. This gives us a clean way of exiting the thread.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">On execution, the UART is initialised, an array (sensorData) is initialised with zero values and the sensor checking thread is started. The main loop starts where it permanently checks for incoming serial data and processes the request. It will either send the sensorData array as JSON, toggle the LED or quit. When quit is sent, the checkSensors variable is set to False. This will cause both the sensor thread and the main loop to terminate.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This will not run again until either the Pico is reset or the program is started again, e.g. Run on Thonny if running Python.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Python Code for the Pico:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code># Multithredded comms test\n\nfrom machine import Pin\nimport machine\nimport time\nimport _thread\nimport random\nimport json\n\nnumSensors = 6\nsensorData = &#91;]\nsensorInterval = 500      # Update simulated sensors every half second\ncheckSensors = True       # Flag - setting to false will terminate second thread\n\nled=Pin(25, Pin.OUT)\nuart = machine.UART(0, 115200)\nprint(uart)\n\n# Sensor thread - this will simulate the sensors by filling\n# the array with random values\ndef sensorThread():\n    nextCheck=0    # When to next check the sensors\n    while True:\n        if(checkSensors==False):\n            break\n        if(time.ticks_ms()&gt;nextCheck):\n            # Update the simulated sensors\n            for s in range(numSensors):\n                sensorData&#91;s]=random.randint(0,255)\n            nextCheck=time.ticks_ms()+sensorInterval\n    # End of 'infinite while loop\n    # Thread complete, checkSensors set to false\n# End of sensorThread\n\ndef sendData(str):\n    # Sends data over the serial UART\n    # Add new line to terminate string\n    #print(\"Sending: \", str)\n    uart.write(str+'\\n')\n    \ndef receiveData():\n    dataIn = \"\"\n    \n    while uart.any():\n        # In a fast enough loop, this may be called before the string\n        # has completed sending. This loop will continue until the incoming\n        # data has completed. On exception it will send what string it has\n        # so far\n        rawIn = uart.readline()\n        #print(rawIn)\n        # Raw data is as a byte stream. Convert\n        # Need to use a try\/except as control characters may cause an issue\n        try:\n            dataIn += str(rawIn.decode('utf-8').strip())\n            #print(\"Incoming :\", dataIn)\n        except:\n            pass\n    return dataIn\n\n# ******** Main code *************\n\n# Init the sensor array with zero values\nfor s in range(numSensors):\n    sensorData.append(0)\n    \n# Start sensor checker in new thread\n_thread.start_new_thread(sensorThread, ())\n# sensorThread()   # Uncomment for single thread\/testing\n\n# Main loop\nwhile checkSensors:\n    if uart.any():\n        msg=receiveData()\n        #print(f\"Message received: \\\"{msg}\\\"\")\n        if(msg==\"quit\"):\n            checkSensors=False\n        elif(msg==\"toggleLED\"):\n            led.toggle()\n            sendData(\"ack\")\n        elif(msg==\"dataRequest\"):\n            dataOut=json.dumps(sensorData)\n            sendData(dataOut)\nuart.write(\"Terminating....\")\nprint(\"Completed\")<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">C++<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The C++ version is very similar in function, though as the main loop never quits, you can send a start command to restart the sensor checking thread. It does not use any form of blocking so it could cause issues if the main thread tries to change checkSensors at the same time the sensor thread is reading from it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Multithredded comms test\n#include &lt;stdio.h>\n#include \"pico\/stdlib.h\"\n#include \"pico\/multicore.h\"\n#include \"hardware\/uart.h\"\n\n\/\/ Define the UART and the standard UART pins\n#define UART uart0\n#define BAUD_RATE 115200\n#define UART_TX_PIN 0\n#define UART_RX_PIN 1\n#define BUFSIZE 255\n#define R_TIMEOUT 1500\n\n#define LED LED_BUILTIN\nint l=0;        \/\/ Tracks LED status\n#define numSensors 6\nint sensorData&#91;numSensors];\nint sensorInterval = 500;\nbool checkSensors=true;\n\nvoid sensorThread() {\n  \/\/ Sensor thread, this will simulate the sensors by filling the array with\n  \/\/ random values\n\n  int nextCheck=0;\n  while(checkSensors) {\n    if(millis()>nextCheck) {\n      \/\/toggleLED();        \/\/ Uncomment for activity debugging\n      for(int i=0; i&lt;numSensors; i++) {\n        sensorData&#91;i]=random(255);\n      }\n      nextCheck=millis()+sensorInterval;\n    }\n  }\n}\n\nvoid toggleLED() {\n  gpio_put(LED, l);\n  l=!l;\n}\n\nvoid receiveUart( char *inarr, int maxIn) {\n  \/\/ Receive data from UART. Data should terminate with end of line\n  \/\/ or a timeout or a full buffer\n  int i=0;\n  bool terminateR=false;\n  int long timeout=millis()+R_TIMEOUT;\n  while(!terminateR) {\n    if(uart_is_readable(UART)) {\n      char ch = uart_getc(UART);\n      \/\/ Strip newline\n      if(ch!='\\n' &amp;&amp; ch!='\\r') {\n        inarr&#91;i++]=ch;\n      } else {\n        \/\/ Also terminate receive on new line\n        terminateR=true;\n      }\n    }\n    \/\/ Terminate receive conditions\n    if(millis()>timeout) {\n      terminateR=true;\n    }\n    if(i==maxIn) {\n      terminateR;\n    }\n  }\n  \/\/ Null terminate string\n  inarr&#91;i]=0;\n}\n\nvoid setup() {\n  Serial.begin(115200);\n  Serial.println(\"Pico UART test\");\n\n  \/\/ Initialise the UART\n  uart_init(UART, BAUD_RATE);\n  \/\/ Convert line feeds to carriage returns to avoid\n  \/\/ hello\n  \/\/      hello\n  \/\/           hello\n  uart_set_translate_crlf(UART, true);\n  \/\/ The first few characters are often corrupt. Send two lines to indicate start\n  uart_puts(UART, \"INIT\\n\\n\");\n  uart_puts(UART, \"Hello from Pico\\n\");\n  \n  \/\/ Set the TX and RX pins by using the function select on the GPIO\n  \/\/ Set datasheet for more information on function select\n  gpio_set_function(UART_TX_PIN, GPIO_FUNC_UART);\n  gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART);\n\n  \/\/ Init the onboard LED\n  gpio_init(LED);\n  gpio_set_dir(LED, GPIO_OUT);\n\n  \/\/ Turn on LED and wait 5 seconds for us to open the serial monitor\n  gpio_put(LED, 1);\n  delay(5000);\n  Serial.println(\"Pico multithredding test\");\n  Serial.println(\"Starting sensorThread\");\n  multicore_launch_core1(sensorThread);\n  Serial.println(\"Started\");\n  toggleLED();\n}\n\nchar msgIn&#91;BUFSIZE];\nchar msgOut&#91;BUFSIZE];\n\nvoid loop() {\n  if(uart_is_readable(UART)) {\n    receiveUart(msgIn, BUFSIZE);\n    Serial.print(\"Incoming message: \");\n    Serial.println(msgIn);\n    if(!strcmp(msgIn, \"dataRequest\")) {\n      \/\/ Compose JSON string manually (libraries exist for more complicated)\n      strcpy(msgOut,\"'&#91;\");\n      char tmpStr&#91;10];\n      for(int i=0;i&lt;numSensors;i++) {\n        sprintf(tmpStr, \"%d\", sensorData&#91;i]);\n        strcat(msgOut,tmpStr);\n        if(i!=numSensors-1) {\n          strcat(msgOut, \", \");\n        }\n      }\n      strcat(msgOut, \"]'\\n\");\n      \/\/ Send data\n      Serial.print(\"Sending data: \");\n      Serial.print(msgOut);\n      uart_puts(UART,msgOut);\n      \/\/ End of if dataRequest\n    } else if (!strcmp(msgIn, \"toggleLED\")) {\n      toggleLED();\n    } else if (!strcmp(msgIn, \"quit\")) {\n      checkSensors=false;\n      uart_puts(UART, \"Quitting thread\\n\");\n    } else if (!strcmp(msgIn, \"start\")) {\n      \/\/ Start the other thread\n      if(checkSensors==true) {\n        uart_puts(UART, \"Sensor thread already running\\n\");\n      } else {\n        \/\/ Start sensor stread\n        checkSensors=true;\n        Serial.println(\"Starting sensor thread\");\n        multicore_reset_core1();\n        multicore_launch_core1(sensorThread);\n        Serial.println(\"Started sensor thread\");\n        uart_puts(UART, \"Launched sensor thread\\n\");\n      }\n    }\n    \/\/ Do nothing with other messages\n\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Creating a master program on the Pi<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The master program on the Pi is very similar to the communications test program above. It will run for 30 seconds, toggling the LED every second and requesting the data every 1.5 seconds. After this it sends a quit to stop the Pico running.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/python\n\n# Multithredded test - the Pi end\n# Run this bit on the Pi for basic UART\/Serial communication\n\nimport serial\nimport time\n\nrunTime=30\t\t\t# Run for 30 seconds\ntoggleInt=1  \t\t# Toggle every second\ndataInt=1.5 \t\t# Get data every 1.5 seconds\n\ndataTimeOut=5\t\t# Time out after 5 seconds\n\n# Init serial port and print details\nsport = serial.Serial(\"\/dev\/ttyS0\", 115200)\nprint(sport)\n\nprint(\"Multithreadded test - Run on the Pi not the Pico\")\n\ndef sendData(msg):\n\t# Send data\n\t\n\tprint(\"Sending:\",msg)\n\tdata=msg.encode('UTF-8')\n\tsport.write(data)\n\ndef receiveData():\n\t# Wait for data or time out\n\ttimeOut=time.time()+dataTimeOut\n\tdataIn=\"Error_timeout\"\n\t\n\twhile (time.time()&lt;timeOut):\n\t\tif(sport.in_waiting&gt;0):\n\t\t\t# There is data\n\t\t\t#print(\"There is data waiting\")\n\t\t\trawIn = bytearray()\n\t\t\twhile (sport.in_waiting &gt; 0):\n\t\t\t\t# Read until line ending\n\t\t\t\trawIn += sport.read_until()\n\t\t\t\t#print('.',end='')\n\t\t\t\t\n\t\t\t# Raw data is a byte stream, convert\n\t\t\t# Need to use a try\/except as control characters may cause an issue\n\t\t\ttry:\n\t\t\t\tdataIn = rawIn.decode('utf-8').strip()\n\t\t\t\t#print(\"  Incoming :\", dataIn)\n\t\t\texcept:\n\t\t\t\tdataIn = \"Error_decode\"\n\t\t\t# We got something, drop out of loop\n\t\t\t#print(\"Data received\")\n\t\t\tbreak\n\t# End of while loop, if a timeout then dataIn will be unchanged\n\t\n\treturn dataIn\n# End of receiveData\n\t\t\t\ndef send_receiveData(msg):\n\t# Sends data and waits for a response\n\tsendData(msg)\n\treturn receiveData()\n\t\n\t\nendTime=time.time()+runTime\nnextToggle=0\nnextData=0\n\nwhile time.time()&lt;endTime:\n\tif(time.time()&gt;nextToggle):\n\t\trtn=send_receiveData(\"toggleLED\")\n\t\tprint(rtn)\n\t\tnextToggle=time.time()+toggleInt\n\tif(time.time()&gt;nextData):\n\t\trtn=send_receiveData(\"dataRequest\")\n\t\tprint(rtn)\n\t\tnextData=time.time()+dataInt\n# Loop completed, tell the Pico to stop\nsendData(\"quit\")\nprint(\"Finished\")<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A Pi Pico can run as a slave device to a Raspberry Pi, with two threads handling communications and actions while the other continually polls sensors which require regular updates, such as an array of ultrasonic sensors. This will give improved PWM support while freeing the Pi for other functions. However enhanced testing beyond the simplicity of the above tests have shown the MicroPython thread implementation is buggy. C++ is very stable and reliable but working with C does add complication when handling strings, dictionary structures and JSON.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The next developments are to add two servos for a pan\/tilt mount, add ultrasonic sensors to make a start on automated driving, then look at moving the motor functions onto the Pico.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next &#8211; Pan\/Tilt Mount *link pending*<\/p>\n","protected":false},"excerpt":{"rendered":"<p>All code in this example is included in the&nbsp;GitHub repository. When looking at adding a [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[35,37],"tags":[36],"class_list":["post-704","post","type-post","status-publish","format-standard","hentry","category-raspberry-pi","category-robotics","tag-pirover"],"_links":{"self":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/704","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/comments?post=704"}],"version-history":[{"count":1,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/704\/revisions"}],"predecessor-version":[{"id":1148,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/704\/revisions\/1148"}],"wp:attachment":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/media?parent=704"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/categories?post=704"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/tags?post=704"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}