{"id":334,"date":"2020-12-26T17:37:02","date_gmt":"2020-12-26T17:37:02","guid":{"rendered":"https:\/\/samndave.org.uk\/ourdoc\/?p=334"},"modified":"2025-07-10T16:11:34","modified_gmt":"2025-07-10T16:11:34","slug":"microbit-serial-communications","status":"publish","type":"post","link":"https:\/\/samndave.org.uk\/index.php\/2020\/12\/26\/microbit-serial-communications\/","title":{"rendered":"Micro:bit Serial Communications"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">By using the serial connections on a Micro:bit, it is possible to interact with it by sending messages in text, rather than just reading the input from a sensor. You can even use serial connections to allow the Micro:bit to talk to other Micro:bits, or different types of microcontrollers, such as an Arduino.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Basic serial output<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You can write from the serial line to a computer connected by USB, by using the &#8216;print&#8217; statement.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from microbit import *\n\nprint(\"Serial test starting\")\n\nc = 0\nwhile True:\n    if (button_a.is_pressed()):\n        print(\"Button A pressed \"+str(c))\n        c = c + 1\n        sleep(50)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The above will print to the serial line when button A is pressed. If you are using MU editor, flash the code, click REPL, hit the reset button on the back of the Micro:bit then press A a few times.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Micro:bit to micro:bit serial communication<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To allow two Micro:bits to communicate over a serial connection, we must make use of the &#8216;uart&#8217; library. For a serial connection, two wires are needed, rx is used to receive and tx is used to transmit. When communicating between two devices, rx must attach to tx on the other device, and vice versa. It is also good practice to connect the gnd pins to ensure a common potential difference.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If we use pins 0 and 1 for our communication. we can connect two Micro:bits with a common ground, and wire each pin 0 to pin 1 on the other device.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/mb2mb_serial_bb-1-1024x610.png\" alt=\"\" class=\"wp-image-337\" width=\"512\" height=\"305\" srcset=\"https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/mb2mb_serial_bb-1-1024x610.png 1024w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/mb2mb_serial_bb-1-300x179.png 300w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/mb2mb_serial_bb-1-768x458.png 768w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/mb2mb_serial_bb-1.png 1173w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><figcaption>Serial connection between two Micro:bits<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Set one Micro:bit and the sender with the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from microbit import *\n\n# Micro:bit serial to serial - sender\n\n# Initalise the UART\nuart.init(baudrate=9600, tx=pin0, rx=pin1)\n\nwhile True:\n    if(button_a.is_pressed()):\n        uart.write(\"A\")\n        sleep(1000)\n    if(button_b.is_pressed()):\n        uart.write(\"B\")\n        sleep(1000)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use below on the receiver:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from microbit import *\n\n# Micro:bit serial to serial - sender\n\n# Initalise the UART\nuart.init(baudrate=9600, tx=pin0, rx=pin1)\n\nwhile True:\n    msg = uart.readline()\n    if(msg is not None):\n        display.scroll(msg)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When a button is pressed on the sender, a message is sent over the serial line to the receiver which displays it on the LED matrix. While the message is short, e.g. &#8220;A&#8221;, this could be something larger. A more advanced system could parse messages to pull out commands or data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Arduino to Micro:bit communications<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">While the Micro:bit is a very versitile device, the low amount of memory, available IO pins or readily available hardware libraries, can cause it to struggle. One option is to use an arduino to drive a single piece of hardware and pass messages back to the Micro:bit using the serial line. An example is an RFID reader.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are two options for serial communications to an arduino, hardware serial or software serial. On most types of arduino, pin D0 doubles as serial rx and D1 as serial tx. In our receiver code above on the Micro:bit, we have our pin0 configured as tx and pin1 as rx. Connecting the ground of an arduino to the ground on the Micro:bit, then arduino D0 and D1 through to Micro:bit pin0 and pin1.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following sketch on the aduino will say &#8216;Hi&#8217; then increase numbers (a sketch is arduino for a program). Though, due to line ending differences it will print &#8216;??&#8217; on the scrolling display of the receiver. We will deal with that in the more advanced example below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void setup()\n{\n  \/\/ Open serial communications and wait for port to open:\n  Serial.begin(9600);\n  while (!Serial) {\n    ; \/\/ wait for serial port to connect. Needed for Native USB only\n  }\n  Serial.println(\"Hi\");\n  delay(2000);\n}\n\nvoid loop() \/\/ run over and over\n{\n  int i=0;\n  char msg&#91;5];\n  while (true) {\n      sprintf(msg, \"%d\", i);\n      Serial.println(msg);\n      delay(5000);\n      i++;\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">There is another problem. As we now have hardware connected to the serial line, we will have problems programming our arduino. We have to remove the connections to D0 and D1 each time we want to flash a new sketch. Another option is to use the software serial library and use other pins.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Connect the aruino to the Micro:bit, mapping D2 to pin0 and D3 to pin1 as shown.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"620\" src=\"http:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/arduino2mb_serial_bb-1024x620.png\" alt=\"\" class=\"wp-image-342\" srcset=\"https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/arduino2mb_serial_bb-1024x620.png 1024w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/arduino2mb_serial_bb-300x182.png 300w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/arduino2mb_serial_bb-768x465.png 768w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/12\/arduino2mb_serial_bb.png 1428w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The following code now makes use of the arduino software serial library and writes over pins D2 and D3. The code on the Micro:bit does not need to change.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/* Based on example at https:\/\/www.arduino.cc\/en\/Tutorial\/LibraryExamples\/SoftwareSerialExample *\/\n#include &lt;SoftwareSerial.h&gt;\n\nSoftwareSerial mySerial(2, 3); \/\/ RX, TX\n\nvoid setup()\n{\n  \/\/ Open serial communications and wait for port to open:\n  Serial.begin(9600);\n  while (!Serial) {\n    ; \/\/ wait for serial port to connect. Needed for Native USB only\n  }\n  Serial.println(\"Hi\");\n\n  \/\/ set the data rate for the SoftwareSerial port\n  mySerial.begin(9600);\n  mySerial.println(\"Lo\");\n}\n\nvoid loop() \/\/ run over and over\n{\n  int i=0;\n  char msg&#91;5];\n  while (true) {\n      sprintf(msg, \"%d\", i);\n      mySerial.println(msg);\n      Serial.println(msg);\n      delay(5000);\n      i++;\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You could create more &#8216;mySerial&#8217; objects to communicate to multiple Micro:bits or connect one to the serial. Using the software serial is useful while you are still doing code development on the arduino. You could then switch to hardware serial later.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Arduino serial to Micro:bit &#8211; advanced<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now lets look at doing something more useful. The Micro:bit LED display is not the best thing to read longer messages with, so lets connect a small OLED display. We need the arduino doing something useful. This example adds an Adafruit PN532 RFID\/NFC shield to the arduino and sends the serial number of cards and tags swiped over software serial to a Micro:bit.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Arduino code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/* rfid_to_serial - Dave Hartburn December 2020\n *  Dumps the UID of a card to the serial console. Designed to be the RDIF workhorse for\n *  another microcontroller, such as a micro:bit.\n *  \n *  Using Arduino UNO and Adafruit PN532 RFID\/NFC Shield\n *  Based on the readMifare Demo program\n *\/\n\n#include &lt;Wire.h&gt;\n#include &lt;SPI.h&gt;\n#include &lt;Adafruit_PN532.h&gt;\n#include &lt;SoftwareSerial.h&gt;   \/\/ Use the software serial library\n\nSoftwareSerial mySerial(2, 3);  \/\/ RX, TX\n\n#define PN532_IRQ   (2)\n#define PN532_RESET (3)  \/\/ Not connected by default on the NFC Shield\n\/\/ Define the board\nAdafruit_PN532 nfc(PN532_IRQ, PN532_RESET);\n\nvoid setup() {\n  Serial.begin(9600);\n  mySerial.begin(9600);\n  \n  \/\/ Init RFID board\n  nfc.begin();\n\n  uint32_t versiondata = nfc.getFirmwareVersion();\n  if (! versiondata) {\n    Serial.print(\"Didn't find PN53x board\");\n    while (1); \/\/ halt\n  }\n  \/\/ Got ok data, print it out!\n  Serial.print(\"Found chip PN5\"); Serial.println((versiondata&gt;&gt;24) &amp; 0xFF, HEX); \n  Serial.print(\"Firmware ver. \"); Serial.print((versiondata&gt;&gt;16) &amp; 0xFF, DEC); \n  Serial.print('.'); Serial.println((versiondata&gt;&gt;8) &amp; 0xFF, DEC);\n  \n  \/\/ configure board to read RFID tags\n  nfc.SAMConfig();\n  \n  \/\/Serial.println(\"Waiting for an ISO14443A Card ...\");  \n}\n\nvoid loop() {\n  uint8_t success;\n  uint8_t uid&#91;] = { 0, 0, 0, 0, 0, 0, 0 };  \/\/ Buffer to store the returned UID\n  uint8_t uidLength;                        \/\/ Length of the UID (4 or 7 bytes depending on ISO14443A card type)\n  int i,len;\n  unsigned long uidl;\n  char msg&#91;50];\n  \n  \/\/ Wait for an ISO14443A type cards (Mifare, etc.).  When one is found\n  \/\/ 'uid' will be populated with the UID, and uidLength will indicate\n  \/\/ if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)\n  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &amp;uidLength);\n  \n  if (success) {\n    \/\/ Display some basic information about the card\n    \/\/Serial.println(\"Found an ISO14443A card\");\n    \/\/Serial.print(\"  UID Value: \");\n    \/\/nfc.PrintHex(uid, uidLength);\n\n    \/\/ Convert array into single UID integer\n    uidl=uid&#91;0];\n    for(i=1;i&lt;uidLength;i++) {\n      uidl = (uidl &lt;&lt; 8) | uid&#91;i];\n    }\n    \/\/mySerial.print(\"CARD\");\n    sprintf(msg,\"c=%lX\",uidl);\n    mySerial.print(msg);\n    Serial.println(msg);\n\n    \/\/ Wait 3 seconds\n    delay(3000);\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Micro:bit code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Micro:bit card reader with arduino acting as\n# RFID\/NFC slave\n\nfrom microbit import *\nfrom ssd1306 import initialize, clear_oled\nfrom ssd1306_text import add_text\n\n# Init a SDD1306 screen\ninitialize()\nclear_oled()\n\n# Initalise the UART\nuart.init(baudrate=9600, tx=pin0, rx=pin1)\n\nwhile True:\n    msg = uart.readline()\n    if(msg is not None):\n        clear_oled()\n        add_text(0, 0, str(msg))\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">While this only reads the card serial number and displays it, you could do something more advanced such as a tick for known good cards and a cross for unknown cards.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>By using the serial connections on a Micro:bit, it is possible to interact with it [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[],"class_list":["post-334","post","type-post","status-publish","format-standard","hentry","category-microbit","category-hardware"],"_links":{"self":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/334","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=334"}],"version-history":[{"count":1,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/334\/revisions"}],"predecessor-version":[{"id":1163,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/334\/revisions\/1163"}],"wp:attachment":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/media?parent=334"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/categories?post=334"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/tags?post=334"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}