Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Tuesday, September 24, 2019

Programming the ATmega328P ADC Registers

Programming the ATmega328P Registers


This is the second article that I have written regarding programming the ATmega328P registers. In the first article we looked at how we could blink an LED using the hardware registers and interrupts. Now we will examine the ADC and how we can use it to measure voltage on one of the Analogue Inputs (AI's) of the Arduino UNO. 

The Arduino IDE libraries make it trivial to read the voltage on an AI: 

int value = analogRead(A0); 

Using default settings, a return value of 0 would represent 0V, and a return value of 1023 (the maximum) would represent approximately 5V. By understanding what is going on behind the scenes you can go beyond this basic implementation and do things like:
  • Change the conversion speed via the pre-scaler;
  • Use different reference voltages;
  • Make ADC reading non-blocking;
  • Use an interrupt which returns when the value is read;
  • Read other things such as the internal chip temperature, GND and VCC;


ATmega328P Analogue to Digital Converter (ADC)


Figure 1. ATmega328P ADC Simplified Block Diagram.

The Arduino ATmega328P has a 10-bit ADC which means it can return 2^10 (i.e. 0 – 1023) values. This is where the 1024 comes from in the equation from the data sheet:

ADC =  (Vin*1024)/Vref

If you want to convert the ADC value to a voltage use the following formula (as the hardware rounds down):

float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

Select the ADC Voltage Range


In order to convert an analog voltage to a digital value on any ADC, the converter has to be provided with the range of voltages. The lower limit is always GND on the Arduino (i.e. 0V) but you can select one of three sources to serve as the high reference:
  • AREF - This is a separate pin on the microcontroller that can be used to provide any high reference voltage you wish to use as long as it’s in the range of 1.0V to VCC. On the Uno it’s wired to one of the black headers. 
  • AVCC - This pin on the microcontroller provides power to the ADC circuitry on the chip. On the Uno it is connected to VCC. This is the simplest option to use provided AVCC is connected to VCC. 
  • 1.1V - The microcontroller has an internal 1.1V reference voltage that can be used
Regardless of the source selected, the data sheet advises putting a capacitor between AREF and ground to smooth out the voltage on that pin. Table 24-3 (data sheet) is used to select which voltage reference you want to use. Note that if you use either of the internal voltages references (AVCC or 1.1V) then that voltage is connected to the AREF pin internally. In this situation, do not connect any other voltage sources to that pin or it will be shorted to the internal reference (and probably let out the magic smoke).


I would default to AVCC unless you had a reason to do otherwise. This will give you a nominal 0 - 5V range.

Note that all 8 AI’s on the UNO are connected to the same ADC (see Figure 1). So you can only sample one input at a time. That’s what table 24-4 (data sheet) and the ADMUX register is used for.


ADC Control Registers (ADCSRA and ADCSRB)


The ADC module of the ATmega328P has two control and status registers, ADCSRA and ADCSRB. For basic ADC operations only the bits in the ADMUX and ADCSRA register have to be modified.

Figure 2. ADMUX Register

Assuming we are using AVCC, from Table 24-3 we need REFS1 = 0 and REFS0 = 1. To get a 10 bit result, ADLAR = 1, and if we are using A0 as our input then from Table 24-4, MUX3-0 = 0000. Thus

ADMUX = 0b01000000

Figure 3. ADCSRA Register

The things we need to worry about for ADCSRA are:

Bit 7 - The ADEN bit enables the ADC module. Must be set to 1 to do any ADC operations.

Bit 6 - Setting the ADSC bit to a 1 initiates a single conversion. This bit will remain a 1 until the conversion is complete. If your program using the polling method to determine when the conversion is compete, it can test the state of this bit to determine when it can read the result of the conversion from the data registers. As long as this bit is a one, the data registers do not yet contain a valid result.

Bit 5 - ADATE: ADC Auto Trigger Enable. When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in ADCSRB. We don't want auto triggering so select 0 for this bit.

Bit 4 - ADIF: ADC Interrupt Flag. This bit is set when an ADC conversion completes and the Data Registers are updated. The ADC Conversion Complete Interrupt is executed if the ADIE bit and the I-bit in SREG are set. ADIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, ADIF is cleared by writing a logical one to the flag. Beware that if doing a Read-Modify-Write on ADCSRA, a pending interrupt can be disabled. This also
applies if the SBI and CBI instructions are used. Set ADIF to 0.

Bit 3 - Setting the ADIE bit to a 1 enables interrupts. An interrupt will be generated on the completion of a conversion. The interrupt vector name is “ADC_vect”.

Bits 2:0 - The ADPS2, ADPS1 and ADPS0 bits selects the pre-scaler divisor value. Those available are:

Figure 4. ADC Pre-Scaler Table

The ADC circuitry needs to have a clock signal provided to it in the range of 50kHz to 200kHz. The ATmega328P clock is too fast (16MHz on the Uno) so the chip includes an adjustable pre-scaler to divide the processor clock down to something usable. The processor clock speed is divided by the pre-scaler value to give an ADC clock speed. Using a lower pre-scaler will make the conversion faster but at the cost of accuracy.

The lowest usable value is a pre-scaler of 16 for the UNO. The analogRead library uses a pre-scaler of 128 in order to get maximum resolution. Unless you understand the consequences, stick with 128.

The value for ADCSRA is going to depend on what conversion approach you use (see below).

 ADC Data Register (ADCH and ADCL - high and low bytes)


The results of the conversion are stored in the two bytes of the Data Register. The most significant bits of the result are stored in ADCH and the least significant bits are in ADCL. For 10-bit conversion, the ADLAR bit in the ADMUX register should be zero.

Figure 5. ADC Data Registers

When using the 10-bit results (ADLAR=0), the results can be read into your program with:

int value = ADC; 

The ADC measures voltage by charging an internal 14 pF capacitor and then measures that voltage with successive approximations. The ADC takes 13 ADC clock cycles to perform a conversion, except the first time the ADC is enabled, at which point it takes 25 ADC cycles, due to the initialisation overhead. The ADC Sample and Hold takes approximately 12μs and the entire conversion process can take up to 260 μs (depending on the pre-scaler selected). So there are at least 3 ways you can approach this:
  1. Put a long enough delay in your while loop so you know the conversion is done. This is the least elegant method!
  2. Set the ADSC bit in ADCSRA to a one. This starts the first conversion. Then poll the ADSC bit in ADCSRA until it becomes zero and read the ADC value.
  3. Use the ADC interrupt and handle the reading in the associated ISR - ADC_vect()
I suggest using approaches 2 or 3.

Don’t forget that you need to set the ADSC bit in ADCSRA to one, every time you want to do a conversion.

Sample ADC Register Polling Code


To cement the information above, I will provide some sample code to read the ADC using registers. The first example uses the polling technique (approach 2 above).


A few notes about this code:
  • We need to use the standard Arduino loop() to allow serial events to be handled (i.e. the printing out of the result to the serial monitor).
  • C5:: The delay(500) is just there to enable us to see the printed result. It is not functionally required, it is the job of the polling (i.e. checking the ADSC bit) to ensure the result is ready.
  • With nothing connected to A0, the pin is floating and I was reading values of around 650 (but this could be anything due to electrical noise from the environment, or capacitively coupling with a nearby pin.). Connect A0 to GND and you should see 0, while connecting it to 5V should show 1023.


Sample ADC Register Interrupt Code


For our final example we will measure the ADC using interrupts.


Regarding the interrupt version of the code:
  • We have to enable interrupts by setting the ADIE bit of the ADCSRA register.
  • The sei() command is optional, setting ADIE is sufficient to enable this interrupt.
  • Note we try to do as little as possible in the ISR.
  • It is a little bit more complicated than the polling version, but not much.
  • As with the polling example if nothing is connected to A0, then the pin is floating and you will get a random result. Connect A0 to GND and you should see 0, while connecting it to 5V should show 1023.

Saturday, September 21, 2019

Programming the ATmega328P Registers and Interrupts

Why Use Register Programming?


Figure 1. The registers of interest

Normally you wouldn't bother to use register programming for the Arduino family. The libraries provided with the Arduino IDE do all the heavy lifting and make it easy to program the microprocessor without knowing exactly how it works. This convenience and readability is not without a cost though and sometimes for reasons of speed, code size or power consumption you will need to get closer to the metal. An example of this is writing a flight controller for a drone. For a realtime application like this (depending on the Arduino model) you are probably going to need to directly access the I/O registers and interrupts.

I’m afraid this is a fairly tedious way to code! I will try to explain why we are selecting the values in the code, otherwise it looks like gibberish! The comment numbers (e.g. C1) are referenced in the explanation below.

Hello World AKA Blink


The hardware equivalent of Hello World is to blink a LED. To demonstrate what you can do with registers and interrupts we will start with that example. There are many different ways to write this code. The complete listing is shown below.


C1:: We are using Timer 0 which is an 8 bit timer with two independent Output Compare Units, and PWM support (see Figure 1). The PWM outputs are mapped to D5 and D6 but we don’t need these here. We want to detect when the counter reaches the value stored in the OCR0A Register. The Output Compare Registers (OCR0A and OCR0B) are compared with the Timer/Counter value and can be used to generate an Output Compare interrupt request. We can use this to toggle our LED.

Figure 2. TCCR0A & TCCR0B Registers 

The meaning of the TCCR0A & TCCR0B register bits are shown in Figure 2. You turn on the bits required in these registers to get a certain behaviour. To work out what does what, have a look at Figure 3.

Figure 3. Explanation of Register Bits

We want CTC mode 2. So the Waveform Generator Mode (WGM01) bit needs to be 1. That is:

TCCR0A = 0b00000010;

another way to write this is:

TCCR0A = (1 << WGM01);

C2:: The Timer/Counter can be clocked internally, via the pre-scaler, or by an external clock source on the T0 pin. We will use the pre-scaler set to 256. The clock source is selected by the Clock Select logic which is controlled by the Clock Select (CS) bits located in the Timer/Counter Control Register (TCCR0B). For TCCR0B to get a pre-scaler of 256, CS02 needs to be 1 (see Figure 3).

TCCR0B = 0b00000100;

or

TCCR0B = (1 << CS02);

C3:: Next we set the Output Compare Register. The number of ticks for a delay of 4ms is 250, so let's run with that.

OCR0A = 250;

C4:: When the timer/counter reaches the OCR0A number, an interrupt will be triggered by setting the OCIE1A flag in TIMSK1. We can do that by:

TIMSK0 = 0b00000010;

or

TIMSK1 = (1 << OCIE1A);

The specific interrupt vector that will be called for this CTC event is:

ISR(TIMER0_COMPA_vect)

As an aside, a list of the available AVR interrupt vectors can be found at: http://ee-classes.usc.edu/ee459/library/documents/avr_intr_vectors/

Figure 4. Port B Registers

C5:: I used digital output D13 since it is attached to the onboard LED and saves me wiring one up, but obviously you can use any output pin. Here we are using the Data Direction Register (DDR) to set D13 as an output (see Figure 4).

DDRB = 0b00100000;

C6:: We need to set the global interrupt flag to enable interrupts:

sei();

C7:: Finally, we need the Interrupt Service Routine which is called when an interrupt occurs. All we do here is toggle D13 which turns the LED on and off (very quickly)! With a LED toggling every 4ms, it just looks on all the time albeit a bit dimmer. We are effectively using PWM to dim the LED, but we want to be able to see the blinks so we use the extraTime variable to slow things down.

Saturday, June 8, 2019

Programming the Tello Drone using Swift (Part 1)

The Tello Drone




In this article we will explore how to write a simple iOS app in Swift to allow control of the Tello.

Tello is a mini drone equipped with a HD camera that is manufactured by Ryze Robotics and includes a flight controller with DJI smarts. It is a great drone to learn to fly on as you can use it indoors and because it is so light (80 grams), crashing is fairly painless if you have the prop guards on. I have crashed mine (a lot) and the worst that has happened is that a propeller came off, which is easy to replace. It is also relatively inexpensive. You can manually control it using either an app (iOS or Android) on your phone, or a combination of the app and a dedicated Bluetooth remote. Either works fine. If you do get the Bluetooth remote be careful of not moving out of Bluetooth range of your phone while you are flying the drone.

Tello Specifications


Tello is Powered by a DJIGlobal flight control system and an Intel processor (Movidius MA2x chipset). The MA2x is based on a SARC LEON processor which has two RISC CPUs to run the RTOS, firmware, and runtime scheduler (Ref: RyzeTelloFirmware). The other specifications are:

  • Weight: Approximately 80 g (Propellers and Battery Included)
  • Dimensions: 98×92.5×41 mm
  • Propeller: 3 inches
  • Built-in Functions: Range Finder, Barometer, LED, Vision System, 2.4 GHz 802.11n Wi-Fi, 720p Live View
  • Port: Micro USB Charging Port
  • Max Flight Distance: 100m
  • Max Speed: 8m/s
  • Max Flight Time: 13min
  • Max Flight Height: 30m

Programming - Firmware Versions


Apart from being a good platform to earn your flying chops, the best thing about the Tello from my perspective is that you can write a script or a program to control the drone remotely. This opens up a lot of possibilities.

Note that there are three different Tello's that you can buy (the Tello, the newer Tello EDU and the Ironman Edition), and they use slightly different API's. So make sure that you use the appropriate version for your drone.

You can work out which firmware you have by connecting your mobile to the Tello WiFi, opening the Tello app, tapping on settings (the gear icon), then tap on the More button, and finally tap on the "..." button to the left of the screen. This should bring up the screen shown below which includes the firmware and app version numbers. My Tello is running firmware version 1.03.33.01. You can download the relevant SDK document for this version.



The Tello EDU uses version 2.0 of the SDK. You can download a PDF of the V2 SDK from here.

Commands that are available in SDK v1.3 but not v2.0 are:

  • height?
  • temp?
  • attitude?
  • baro?
  • acceleration?
  • tof?

Conversely, commands that are available in SDK v2.0 but not v1.3 are:

  • stop (hover)
  • go x y z speed mid (same as go x y z speed but uses the mission pad)
  • curve x1 y1 z1 x2 y2 z2 speed mid (same as curve x1 y1 z1 x2 y2 z2 speed but uses the mission pad)
  • jump x y z speed yaw mid1 mid2 (Fly to coordinates x, y and z of mission pad 1 and recognize coordinates 0, 0 and z of mission pad 2 and rotate to the yaw value)
  • mon
  • moff
  • mdirection
  • ap ssid pass
  • sdk?
  • sn?

The Tello EDU also has a swarm mode if you want to control a bunch of drones.

Programming - Python


There are plenty of examples on how to use Python to control your Tello. For drones running v1.3 have a look at the DroneBlocks code. For the Tello EDU (i.e. v2.0 SDK), Ryze Robotics provide some sample code for you to download and try out.

I uploaded the DroneBlocks code using my Raspberry Pi connected to the Tello WiFi and it worked a treat. Given that there are lots of Python examples, I thought I would put together something in Swift and work up to an app which provides additional functionality not found in the official Tello app.

Programming - Swift (iOS)


We access the Tello API by connecting to the airframe via a WiFi UDP port. Once a connection is in place, the drone is controlled using simple text commands.



The first thing we want to determine is whether our device is connected to the Tello WiFi. There are a couple of Swift functions which can assist with establishing this. The Tello SSID name contains the string "TELLO" (see image above), so this is what we will use to determine wether we are connected to the correct WiFi network.


We can use the code above in our ViewController to ensure that we are hooked up to the Tello, and if not provide an alert. The screenshot below shows this implemented in my proof of concept app.


The code for the ViewController is shown next. It should be fairly self explanatory.



UDP


UDP (User Datagram Protocol) is a communications protocol, similar to Transmission Control Protocol (TCP), but used primarily for establishing low-latency, low-bandwidth and loss-tolerating connections. UDP sends messages, called datagrams, and is considered a best-effort mode of communications. With UDP there is no checking and resending of lost messages (unlike TCP).

Both UDP and TCP run on top of the Internet Protocol (IP) and are sometimes referred to as UDP/IP or TCP/IP.

UDP provides two services not provided by the IP layer. It provides port numbers to help distinguish different user requests and, optionally, a checksum capability to verify that the data arrived intact.

The Tello IP address is 192.168.10.1. The UDP Services available are:

UDP PORT: 8889 - Send command and receive a response.
UDP SERVER: 0.0.0.0 UDP PORT: 8890 - Receive Tello state.
UDP SERVER: 0.0.0.0 UDP PORT: 11111 - Receive Tello video stream.

If you want to send and receive via UDP on iOS then the two main libraries in use appear to be SwiftSocket and GCDAsyncUDPSocket.

Swift Socket looks to be the simpler of the two libraries, so I used that for my initial attempt. I put together a Tello Swift class to do the heavy lifting. It is reproduced below and works as advertised. You will need to put together your own UI but if you hook up the relevant buttons in the View Controller then you shouldn't have any problem reproducing what I have done.

I will add a bit more functionality to the app (e.g. video) and then stick it up on the app store for download.



Thursday, July 12, 2018

Espressif ESP32 Tutorial - Programming (Arduino IDE)

Introduction


As promised in the previous post, let's have a look at the different ways we can program our ESP32. I will start with the Arduino IDE, because I think that will be the most common option. In this post I will only be looking to get the "hello world" of IoT going, that is blinking a LED.



Once I've selected an IDE, we will do something useful with the ESP32 (stay tuned).

Arduino IDE




Installing support for the ESP32 IC is not yet available through the Boards Manager, so the
instructions on the GitHub page should be used. For the Mac OS, it is pretty straight forward.

1. Install the latest version of the Arduino IDE.
2. Open Terminal and execute the following command (copy->paste and hit enter):

mkdir -p ~/Documents/Arduino/hardware/espressif && \
cd ~/Documents/Arduino/hardware/espressif && \
git clone https://github.com/espressif/arduino-esp32.git esp32 && \
cd esp32 && \
git submodule update --init --recursive && \
cd tools && \
python get.py

3. Restart the Arduino IDE.

Support for the ESP32 for Arduino is under constant development, but once everything is installed,
the sketch writing and upload process is similar to other boards. If you are using the Jaycar board, select ESP32 Dev Module as the board type, and ensure that the correct serial port is selected.



Connect your ESP32 Dev Board to your PC via a USB cable and you should be ready to compile and upload your first program. First check that you can see the port which is connected to the ESP32.

On my MacBook Pro (early 2015) running High Sierra, the port on the Duinotech ESP32 Dev Board was not recognized. If this happens, you may need to install the drivers for the USB-serial converter for this board. It uses a CP2102 IC, and the drivers are found on the Silicon Labs CP2102 website:
https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers.

After you download the correct driver version for your OS. You will need to install it. On the Mac this involves, unzipping the archive, mounting the DMG disk image and then running the Silicon Labs VCP Driver.pkg. You will need to give permission to run this driver in the Security and Privacy preference (this will pop up). You should now be able to see the port in the Arduino IDE (no need to reboot or restart the IDE).

Open up the Blink Sketch (File -> Examples -> 01. Basics -> Blink), compile and download to your ESP32.

You will probably get this error:

'LED_BUILTIN' was not declared in this scope

There are a couple of traps for new players here,

The standard Arduino boards define the LED_BUILTIN macro in the variant file but apparently the ESP32 Dev Board doesn't. For the Arduino, the built in LED is usually connected to pin 13, on the ESP32 it can be anything. The usual suspects are pins 2, 5 or 16. You can fix this error by adding the following line to the top of the sketch, above the setup() function. For example, if your LED is connected to pin 2:

int LED_BUILTIN = 2;

Unfortunately, the Duinotech ESP32 Dev Board doesn't seem to have a LED connected to a user controllable pin. It does have a blue LED which flashes when communicating via the serial port. It is difficult to be 100% sure that this LED is not controllable since I can't find a schematic for this board. Most development boards have a red power LED and a blue in built LED for user control. Anyway, I resorted to connecting an external LED with a current limiting resistor to GPIO 2.



Note that when the EP32 Dev Board is placed on a standard sized bread board, there will only be one spare row of pins, make sure that this is on the side you want to connect to.

Calculation of the current limiting resistor is done using this formula:

Resistor Value = (Vs – VF)/ IF = 160 ohms (I used 150 ohms since that is what I had)

Where:

Vs = Input Supply DC voltage = 3.3V
VF = LED Forward Voltage = 1.7V
IF = LED current = 10 mA



I measured the LED forward voltage drop (VF) using my LCR meter but you could just get it of the data sheet.

I didn't need to do this, but if you are having trouble uploading, try holding the ‘BOOT’ button while pressing and releasing the ‘RST’ button. This should put the board into boot-loader mode to allow uploads.

While you are here you may want to try some of the other ESP32 example sketches provided. For example ChipID (File -> Examples -> ESP32 -> ChipID) will display your chips MAC address in the serial monitor.



All up that wasn't too painful. I think the Arduino IDE would be a good option if you are already familiar with it and as long as the functionality that you need is available. Not all of the libraries are ESP32 compatible yet (e.g. analogWrite is not available yet although there are work arounds).

Wednesday, December 23, 2015

Moving to embedXcode...

The Problem


We have been using the Arduino IDE to develop on. Which is fine (and free) but it does have some limitations. In particular, we ran into the problem of having too many tabs (files) in our main controller sketch. This came about as a result of another issue, which is not unrelated.

As with most people we started developing our robot code organically using mostly straight c with c++ functionality reserved for included libraries. By the time you add 13 sensors, speech synthesis, speech recognition, 2 motor controllers, serial comms for the Bluetooth remote (which will be described in a subsequent post) and an I2C bus connecting the real time clock, pressure / altitude module and 2 auxiliary Arduino's used for display and logging, the code gets messy and hard to maintain. A simplified schematic of the robot so far is shown below. The schematic was produced using Fritzing which I have mentioned previously and strongly recommend.



As an aside, we are using SPI for the logging Arduino to communicate with its OLED shield, so we have all the available communication options covered (with the possible exceptions of WiFi and RF - stay tuned)!

To fix the messy, unmaintainable code issue, we started to translate our c code into c++ classes where it made sense. This made the code much more modular but each class requires a new tab which brings us back to the first issue mentioned above. Once the number of tabs fill up the top row of the IDE, it becomes a bit of a pain to move to the tabs not displayed. There is a keyboard shortcut to go to the next and previous tab, but that is a bit clunky and was the straw that sent me on a search for a better IDE to develop Arduino code on.


The other short comings of the Arduino IDE are:
  1. No code completion; and
  2. The syntax highlighting is a bit hit and miss. You could fix a particular issue by editing the keywords.txt file in the appropriate library but that is pretty fragile.

The Solution


A quick google search will turn up LOTS of different options for programming the Arduino. Our preferred solution would incorporate the following:
  1. Minimal learning curve;
  2. Preferably free;
  3. Works on a Mac;
  4. Can upload a sketch from within the IDE;
  5. Includes a serial terminal similar to the serial monitor provided by the Arduino IDE; 
  6. Has code completion and syntax highlighting; and
  7. Handles multiple files well; and
  8. Doesn't create any new issues.
With this shopping list in mind, the field quickly narrows to a plug in for Xcode called embedXcode. This ticks all our requirements and has (almost) no learning curve since we use Xcode for our App Development work.



The other IDE we considered was Eclipse which is the basis of Android Studio that we use for Android Development. What swayed or decision was that the setup looked a lot easier for Xcode and we were more familiar with this IDE as well. Have a look at this blog by a chap in the US, he had the same issues but decided on Eclipse. Going with what you are already familiar with makes a lot of sense.

Setting up embedXcode


This is straight forward and described in detail in the (large) user manual. In summary:
  1. Install Xcode if you don't have it already.
  2. Download embedXcode. We went for the free version to evaluate how good the plug in is. Should it work out we will either upgrade to embedXcode+ or pay a donation. We want to encourage ongoing development of the plugin. We know that Xcode changes frequently and with each new release normally breaks legacy code.
  3. Install the plug in and open up Xcode. That's it! You should now have the option to open a new embedXcode AVR project (see below).

Importing Sketches


Unfortunately you can't just import sketches that you have done with the Arduino IDE. There is a process that you need to follow:
  1. Open a new project in Xcode. You can call it the same name as your sketch. Make sure you select the correct board type (e.g. Uno) in the new project options. The scope options are sketch or library and this also sets the extension of the main file (.ino for sketches and .cpp for libraries).
  2. Open your sketch in the Arduino IDE and copy the contents into the ino file in your Xcode project. There is some pre-processor definitions used for code sensing at the top of the ino template file in Xcode. Don't overwrite these unless you know what you are doing (e.g. if you are using a recent Arduino you can replace the lot with #include "Arduino.h".
  3. The next step is to find your Arduino libraries folder in Finder and drag it across to the Sketchbook group. When the choose options for adding these files dialog comes up, don't select "copy items if needed" (unless you want multiple copies of your library files), select index in "add to targets" (see below). You also need to change the type from plain text to "c++ source". This option is found in the right hand pane of Xcode after selecting the main sketch (shown in the second screenshot below).
  4. The thing I stuffed up initially was not also listing the libraries used in the makefile. If you get an error saying a library can't be found, this may be the answer To fix it, select the makefile in the left hand pane and add the names of the libraries used.  There are two types of libraries you will use most often, application libraries and user defined libraries. Generally, the application libraries are the ones defined using <> (e.g.  #define <SoftwareSerial>) and the user libraries are defined using"" (e.g. #define "blunoAccessory"). However the <TimerOne> library was an exception to this rule and needed to be defined as a user library (e.g. "APP_LIBS_LIST = SoftwareSerial" and "USER_LIBS_LIST = U8glib blunoAccessory TimerOne". Different libraries are separated by a space and don't show the file extension. Read the user manual if you are still confused, it covers this topic in some detail.



Once you have completed the four steps above, you should be able to build (compile) your project, but only if your board is connected.

New Issues?


The only issues which have arisen so far are fairly minor apart from the speed of compilation and uploading. This is significantly slower than the Arduino IDE. If you purchased  embedXcode+ then you have two options:

  1. Build -> All targets which builds and links everything, and is slow.
  2. Make -> Fast -> additional targets only, which builds the main sketch and the libraries in the local folder, so it is much faster (up to 10x according to the developer).

If you only downloaded the free version then you are stuck with option 1. Other areas to be aware of are:
  1. You can't Build (compile) a project unless you are connected to your board via USB. This is a bit of a pain as you could just compile using the Arduino IDE without being connected to the board. Solved this. From the Product menu item select Scheme -> Build.
  2. Instead of Serial Monitor in the Arduino IDE you use Terminal on the Mac. The default baud rate for terminal is 9600. Which is ok if that is the baud rate you want to use on the serial port but I have a sketch which communicates with a BlueTooth LE shield on the same comm port that needs 115200 baud. Theoretically you can change the baud rate in Terminal using stty (e.g. stty 115200), but this doesn't seem to work. I have also tried "screen /dev/tty.usbmodemfd121 115200", but no cigar. I will keep working on this but the work around for now is to use 9600 baud if you can or use the old Arduino Serial Monitor if all else fails. Other solutions are welcome, so feel free to comment below. I have found the answer to this as well. There is an option in the makefile that you can use to set the baud rate, namely:  "SERIAL_BAUDRATE = 115200".
  3. Getting code sense to work for me took a bit of tweaking. First make sure that the sketch (ino file) has index selected for Target Membership (click on this file to check). Save the file and close the project. A small update is required to the user manual instructions. In the current version of Xcode (v7.2), projects is now a separate dialogue to Organiser but it is still found under the Windows menu in Xcode. Delete your derived data for your project and then reopen your project. After indexing, code sense for the Arduino specific definitions should work. You can change the syntax colouring in preferences, fonts and color.

If anything else comes up, I will add it here. All in all I am pretty happy with this solution. We will still use the Arduino IDE for simple sketches but for something as complicated as a robot, an IDE like Xcode is essential. Well done embedXcode!

Update 27th December 2015


I was so impressed with embedXcode that I upgraded to embedXcode+. This is worth doing if you use the plugin regularly. It also encourages the developer to keep supporting the product which is important given the frequent updates to Xcode.

Error: Serial port not available (Step2.mk)




If you come across this error (I did), there is a simple fix. First open up terminal and find out the name of your serial port. Type the following command: ls /dev/tty.usb*


This will provide the name of your serial port. Copy this and then open the main Makefile in Xcode uncomment the line:

#BOARD_PORT = /dev/tty.usbmodem*

and specify either a more general name:  e.g. BOARD_PORT = /dev/tty.usbmodem*

or the specific USB port name of the board that you got from Terminal e.g. in my case:

BOARD_PORT = /dev/tty.usbmodemfd121