RSS

Archive for May, 2013

C# SerialPort on the Raspberry Pi

Sunday, May 19th, 2013

Sometimes you have to do something just because you can. Today was no exception. Take one Raspberry Pi board (Linux) and give it a dose of .NET loving…

I can hear people screaming NO! but it’s too late, I’ve done it.

To be honest, I’m not the first person to use .NET on the Raspberry Pi. In fact I used this installation guide to install Mono on the Raspberry Pi.

So what interested me? Simply put, hardware interfacing. Could the .NET hardware classes (i.e. SerialPort) be used on the Raspberry Pi? There was only one way to find out.

Raspberry Pi Setup

The first thing to do was to set up the Raspberry Pi using the instructions in the blog mentioned above. This was not difficult although it was time consuming as it took a while to compile.

When this is complete a simple program should demonstrate if the serial ports are available to us. The following code should show this:

namespace ConsoleApplication1
{
	class Program
	{
		public static void Main(string[] args)
		{
			SerialPort sp = new SerialPort("/dev/ttyAMA0", 115200, Parity.None, 8, StopBits.One);
			sp.Open();
			for (int index = 0; index < 10; index++)
			{
				string result = string.Format("{0} Testing", index);
				sp.Write(result);
			}
			sp.Close();
		}
	}
}

As you can see, this code is not too complex. It merely opens a serial port and then starts to output data to the port. The only tricky part of the job was to locate the name to be used for the serial port. It’s been too long since I used Unix in anger.

Testing the Application

Testing is not too complex as the test application is simply outputting a text message. We can see the output by hooking up PuTTY to a serial port on a computer.

The hardware is also simple to hook up. The FTDI cable I have allows me to connect a 3.3V TTL serial device to my PC over USB. This USB device then appears as a standard serial device on the PC. Three connections are required:

Raspberry PiFTDI Cable
GroundGround
RxTx
TxRx

Strictly speaking, we do not have to connect the Tx on the FTDI cable to the Rx on the Raspberry Pi as we will not be transmitting anything from the PC to the Raspberry Pi in this example.

Once the hardware is connected you will need to fire up PuTTY and connect it to the serial port on your PC. Ensure that the settings used match those in the application code above.

Assuming that you now have Mono installed and the application typed in ready to go, type the following commands into a shell on the Raspberry Pi:

mcs serial.cs
mono serial.exe

The first command invokes the Mono C# compiler. The second tells mono to execute the application which has been compiled.

If all has gone well then you will see something like this in the PuTTY window running on the PC:

Serial Output in Putty

Serial Output in Putty

Conclusion

I was rather interested to see that the C# skills acquired on the PC could also be used on the Raspberry Pi. The only thing missing on the Pi was a good development environment.

Making a Netduino GO! Module – Conclusion

Tuesday, May 7th, 2013

Making the OutputExpander module has been an interesting journey. The original drawings started in August 2012 and then sat on the hard drive for about eight months. Much of the time following the original drawings were spent working out how the STM8S worked. You can find out more in The Way of the Register series (something I will pick up again soon, to my mind there are a few missing topics).

For those who do not know, I’m a software engineer and electronics is a hobby. The prospect of designing a board and using SMD components would have been unthinkable to me two years ago. Today I sit here with my first prototype PCB connected to a commercial board and the output looks reasonably professional – well I’ll let you decide.

Completed Board

Completed Board


Not looking too bad if I say so myself.

So let’s look at what I have learned and also how long the project took.

Lessons Learned

With all projects we should look back and learn from the experience, both good and bad. So here are a few things I have learned over the past few months.

Designing the Board

The original design started life in August 2012. I probably should have taken the plunge and developed the board a little quicker than I did although in truth, I did not get the major requirement of the board, namely GoBus 1.0 really sorted out until late November 2012.

Prototyping

This was probably the simplest bit of the project. I have all of the standard components in my toolbox already and I also have the tools required. This was really a case of getting the system working. The hardest part was getting to grips with the STM8S, a story I have documented in The Way of The Register series of posts.

Schematic

During this part of the design phase I tried several different packages. All of them had strengths and weaknesses. I finally settled on DesignSpark. For me this package had three major strengths:

  • It’s free
  • You can use it for commercial projects
  • It feels like a Windows application
  • In fairness it does have a few weaknesses. The most obvious for me was the lack of the ability to add images of any kind to the design. Come on, at version 5 you should have this one!

    Nets – I discovered these when producing the final draft of the schematic. These allowed the separation of the nets into logical groups/functions/areas. It made the schematic a lot cleaner.

    Schematic to Manufacture

    For me this was the where I learned the most. The first thing I learned was that auto-routers are dreadful. They are slow and produce some interesting board layouts. This board is a simple board and yet the auto-router still took a long time to make a half-hearted attempt at routing the board. In the end I did this manually. This was not too much of a problem as the board was simple.

    Next, you have to learn to think in three dimensions. You have two layers so use them.

    The Netduino modules produced by Secret Labs have nice rounded corners – these are a devil to produce in DesignSpark. I think that the module I produced has one corner which is slightly different from the others.

    The cost of prototyping is a lot lower than I thought. Ten boards including shipping costs about £18 and only took 10 days.

    I now know what 0403 means. The ‘0’ stands for Ohhh my goodness that’s small. Seriously, the four digits should be split into two and thy give the dimensions of the component. So for a metric component an 0403 part is 0.4 x 0.3 mm – that’s small.

    The STM8S part selected has a 0.65mm pitch for the pins. I originally found this a little worrying. Don’t be afraid – they are not that bad.

    Get a USB microscope when soldering SMD components. This tools is cheap and allows the examination of joints for shorts. The quality will never be great, mine only runs at 640×480, but a 400x zoom means you can be sure that you have no problems.

    Add test points. There came a point when I was making the board and I needed to see the data going through to the 74HC595’s. I did not have a suitable connection and so I had to solder a piece of wire to the board:

    Improvised Test Point

    Improvised Test Point

    A good test point would have made this easier.

    How Long Did it Take

    The original drawing started in August 2012 and the final board was put together and tested only yesterday. So in elapsed time that’s about nine months. In real working time this broke down as follows:

    Activity Duration (Hours)
    Building Prototype circuit 2
    Prototype software 3
    Schematic 6
    PCB layout 20
    Assembly and testing 5
    Enhanced software 4
    Total 40

    Something to bear in mind is that no production evaluation or component selection has been conducted as part of this project. It was supposed to be the final item on the list. I am still not sure if this should be taken through to manufacture – time will tell.

    Another item to be considered is to achieve the Netduino GO! logo approval. At the time of writing this required the approval of the board by Secret Labs – this activity has not been completed.

    Conclusion

    Well, that was a hectic few weeks.

    Did I enjoy it – YES!

    Would I recommend that you try it – YES!

    As for me, I’ll be taking a few days off of hardware development and blogging. Love doing it but it can take it’s toll.

    I suppose you may be interested in some downloads…

    If you use any of the code or techniques discussed in this series of posts then please let me know as I’m interested in what other people are doing with this work.

    Making a Netduino GO! Module – Stage 6 – Assembling the Prototype

    Monday, May 6th, 2013

    A few days ago I received a package from China, namely my Output Expander prototype boards:

    Bubble Wrapped Boards From China

    Bubble Wrapped Boards From China

    Could not wait to unwrap them:

    OutputExpander Bare Boards

    OutputExpander Bare Boards

    Only one thing left to do, start assembling them. As with all projects this will be broken down into steps:

    • Add the STM8S microcontroller and test
    • Add one 74HC595 shift register and test
    • Complete the board and add connectors and of course, test
    • By using a modular approach it should be easy to detect a problem with the design or assembly.

      Component List

      The board requires the following components:

      ComponentValueQuantity
      STM8S103F3NA1
      IDC socket1.27″ pitch1
      Sr1, SR2, Sr3, SR4SOL / SOP164
      C21uF0403
      C1, C3, C4, C5, C6, C7100nF – 04036
      Connectors0.1″Misc

      When these arrive be prepared, they are small!

      Adding the Microcontroller

      The board will need a microcontroller and some way of programming it. The logical first task is to add the controller, socket and the supporting passive components. Doing this will allow us to programme the controller with the firmware. As a test we can connect the programmed board to the Netduino Go!. If the connections between the board and the Netduino GO! are correct then the blue LED on the socket on the Netduino Go! should light.

      If you are attempting to follow this series and you are making your own board then I recommend you browse the net and have a look for videos on soldering SMD components. I found the tutorials on drag soldering really useful.

      Out with the soldering iron, a magnifier (it was needed). One thing I noticed was the difference between the 74HC595 pads and the pads for the STM8S. The 74HC595 component used was a built in component whilst the STM8S was a component I had created. The most noticeable difference between the two parts was the size of the pads on the PCB compared to the size of the component. The 74HC595 pads were elongated. These make soldering easier.

      STM8SPadsShiftRegisterPads
      STM8S75HC595

      Although the pins on the STM8S are only 0.65mm pitch, soldering is not as difficult as it first appears. A quick first attempt gave the following:

      STM8S Mounted On Board

      STM8S Mounted On Board

      There is only one item of concern and that is the whisker of solder between the fourth and fifth pins down on the right hand side of the image. This was quickly tidied up by dragging the soldering iron between the two pins.

      Next task was to add the passives which supported the STM8S leaving the passives for the shift registers for later. This is where you get some idea of the difference between the size of the components vs the size of the tools you are using:

      Capacitor and Tools

      Capacitor and Tools

      At this point I realised that an 0403 (metric sizing) component is 0.4mm x 0.3mm and the smallest soldering iron bit I has was about 1.5mm. Not to worry, the pads on the board are a reasonable size, simply tin the pads and then slide the capacitor into the molten solder.

      The next job was to add the socket for the GoBus. The sockets are surface mounted 1.27″ pitch IDC sockets. I found the easiest way to add these was to tin one pad and then slide the socket into place. The remaining pads could be soldered by placing the solder at the end of the connector and then applying heat and letting the solder run under the socket. It’s not as difficult as it sounds.

      At this point, the microcontroller should be in place with enough supporting hardware to allow it to be programmed. This was achieved by connecting the ST-Link/V2 programmer to the prototype board using the Komodex Breakout Board. The firmware developed in the previous posts was loaded into the development environment and deployed top the microcontroller.

      Programming the STM8S

      Programming the STM8S

      No deployment errors!

      A good indication that the microcontroller and the supporting hardware are functioning correctly.

      Add a Shift Register

      Next step is to add a single shift register and see if we get some output. Soldering the shift registers was a lot simpler than the STM8S as the pin pitch was greater. These could be soldered more conventionally although the pitch was finer than you may be used to if you have only worked with PTH components.

      Connecting the module to the Netduino GO! acts as a quick check:

      Netduino Go! Connected to OutputExpander

      Netduino Go! Connected to OutputExpander

      The blue LED lights up – the Netduino GO! recognises the OutputExpander as a valid module.

      Adding the single register worked and so the next task is to add the remaining registers and connectors.

      But All Was Not Well…

      During the assembly and testing process I had managed to accidentally short a few pins on the shift registers. This resulted in no output from the OutputExpander module. Breaking out the scope and the logic analyser proved that something was very wrong. The following trace shows the problem:

      Original Output From the OutputExpander

      Original Output From the OutputExpander

      It appears that the latch and clear lines were being triggered at the same time. I was able to establish by disconnecting the module from the circuit that there was not short between the two lines. Something else must be going on. Some further digging into the output from the logic analyser showed that the clear signal was being triggered slightly before the latch signal and that the latch was being released slightly after the clear signal. As a result I would expect no output from the shift registers – this is what I was seeing.

      Not wanting to waste money on components I continued to check the circuit but could not find anything else obviously wrong with the soldering or the software.

      Only one remaining option. Try a putting together a new board. Back to step one.

      A New Board

      Building the new board was a lot quicker than the first. Following the same procedure (one step at a time and test all the way) produced a new board:

      Before testing the board there was a final modification to make. This time to the software. The board has the outputs labelled from left to right with the lower bits being to the right of the board. The prototype module had the shift registers ordered from right to left. A quick change to the C code on the STM8S soon resolved this problem:

      //--------------------------------------------------------------------------------
      //
      //  GO! function 2 - Output the specified bytes to the shift registers.
      //  Tx buffer.
      //
      void SetShiftRegisters()
      {
          for (int index = 0; index < _numberOfShiftRegisters; index++)
          {
              _registers[index] = _rxBuffer[5 - index];
          }
          OutputData();
          NotifyGOBoard();
      }
      

      A small bug had also been noticed in the clock configuration method. The code stated that CCO was turned off but the code actually turned it on. The code should read:

      //--------------------------------------------------------------------------------
      //
      //  Setup the system clock to run at 16MHz using the internal oscillator.
      //
      void InitialiseSystemClock()
      {
          CLK_ICKR = 0;                       //  Reset the Internal Clock Register.
          CLK_ICKR_HSIEN = 1;                 //  Enable the HSI.
          CLK_ECKR = 0;                       //  Disable the external clock.
          while (CLK_ICKR_HSIRDY == 0);       //  Wait for the HSI to be ready for use.
          CLK_CKDIVR = 0;                     //  Ensure the clocks are running at full speed.
          CLK_PCKENR1 = 0xff;                 //  Enable all peripheral clocks.
          CLK_PCKENR2 = 0xff;                 //  Ditto.
          CLK_CCOR = 0;                       //  Turn off CCO.
          CLK_HSITRIMR = 0;                   //  Turn off any HSIU trimming.
          CLK_SWIMCCR = 0;                    //  Set SWIM to run at clock / 2.
          CLK_SWR = 0xe1;                     //  Use HSI as the clock source.
          CLK_SWCR = 0;                       //  Reset the clock switch control register.
          CLK_SWCR_SWEN = 1;                  //  Enable switching.
          while (CLK_SWCR_SWBSY != 0);        //  Pause while the clock switch is busy.
      }
      

      Testing

      The step by step testing process had shown that a single shift register worked, now to prove that four worked. Now it was time to add some more and connect some LEDs:

      Netduino Go OutputExpander and Some LEDs

      Netduino Go OutputExpander and Some LEDs

      And here’s a video of it working:

      Conclusion

      Assembly was not as difficult as it first appears even considering the small size of the components. In fact the STM8S was programmed first time.

      One piece of equipment I did find invaluable was a cheap USB microscope. These don’t give a high resolution image but they do allow you to zoom in on the board and check for problems.

      One final post left – time to reflect on the process.