Friday, October 07, 2016

USB storage with STM32F4-Discovery and CubeMX

I have been using the ARM microcontroller platform for many microcontroller projects in the past years, both the Silicon Labs/Energy Micro EFM32 Controller and the STMicroelectronics STM32. The complexity of setting up these controllers is much greater than previous microcontrollers I have used, Atmel AVR and PIC Micro.

The difficulty comes from all the register settings and combination of these to get the functionality you want in the end. I must say that Energy Micro has had the developer in mind when they made the simplicity studio, where updates and application notes are gathered in the same, easy to use interface. I am sorry to say STMicroelectronics, but your toolchain and documentation have not been anything to speak about. That is, until you made the CubeMX.

CubeMX makes it easy to set up the peripherals and the clock for the microcontroller and generate code for the toolchain of your choice. I have been switching between both ARM Keil, IAR Embedded Workbench and Atollic Truestudio, and I can use the same source code for all of them. Moving or porting code have been very difficult to do in the past as all of the settings would have to be changed, links to libraries would have to be set up again etc. Now a simple click of a button will set up the environment and always be working with the latest updates from ST. If additional peripherals are added to the project I can switch back from the code to CubeMX and add these to the project. Fantastic!

My only complaint is that there is very little documentation of how to set up the peripherals: There are now three documented examples, where of one is blinking a LED, one is to set up reading/writing to a SD card and one is power handling. I don't care about your HAL examples, ST - I want all of them transferred to CubeMX. For all periperhals and variants of setups.

I have now been using about three weeks just to set up my STM32F4-Discovery kit to read and write to a USB memorystick/thumbdrive connected to the USB-micro connector through an USB host adapter. This seems like a simple task, given that there is a HAL example in the repository (User\Repository\STM32Cube_FW_F4_V1.13.0\Projects\STM32F4-Discovery\Applications\FatFs\FatFs_USBDisk). I have been debugging the code and comparing the registers without getting good clues of why the CubeMX setup fail. In the end I found the problem being that the heap and stack size was too small. After doubling these from standard values I finally got the example working with CubeMX.

Here is how I did it:

Start by selecting the STM32F4-Discovery from the Board selection menu:


The next thing you should do is enable the "RCC-High Speed Clock (HSE)" with the STM32F4-Discovery Crystal, to be able to provide an accurate clock for the USB timing. You cannot continue with the setup for the USB without this enabled.


Next you want to enable "Host_Only" for "USB_OTG_FS". For the STM32F4-Disovery the "Activate_VBUS" should also be selected:

Now you want to Select" Mass Storage Host Class":

...and "USB Disk" from "FATFS" MiddleWares:

Now you want to set up the clock to have HSE and run at 168 MHz, as shown:

Before finishing the settings for the USB you want to set the "Drive_VBUS_FS" to "GPIO_Output" "PC0" under "USB_Host Configuration":

You are now ready to create the code with CubeMX. Select your toolchain (I am using Atollic Truestudio) and Select a proper location for the project and a project name. This is were it is crucial that you use a heap size of 0x400 and a stack size of 0x800. Without this the USB will not work!!


Now you press the icon "Generate Source code based on user settings" in CubeMX and confirm that you want to open the project.

To be able to copy the functionality of the example from the repository you need to put the code in "usb_host.c" instead of "main.c". This is because the USB settings and state machine is put here.

You want to add the private variables to the user code section 0 of usb_host.c. The #include for fatfs.h is also added to this section in order to prevent changes if future changes in CubeMX is expected:

/* USER CODE BEGIN 0 */
//Include the fatfs library here to be inside user code blocks
#include "fatfs.h"
FATFS USBDISKFatFs;           /* File system object for USB disk logical drive */
FIL MyFile;                   /* File object */
char USBDISKPath[4];          /* USB Host logical drive path */
USBH_HandleTypeDef hUSB_Host; /* USB Host handle */
/* USER CODE END 0 */

A custom error handler is added to section 1 where the red LED/LD5 is turned on if any errors occurs:


void USB_Error_Handler(void)
{
  /* USER CODE BEGIN USB_Error_Handler */
  /* User can add his own implementation to report the HAL error return state */
 HAL_GPIO_WritePin(LD5_GPIO_Port,LD5_Pin,GPIO_PIN_SET);
  while(1)
  {
  }
  /* USER CODE END USB_Error_Handler */
}

In the same user section the "MSC_Application" function is added. This is the function that is run after the USB memorystick is set up correctly:

static void MSC_Application(void)
{
  FRESULT res;                                          /* FatFs function common result code */
  uint32_t byteswritten, bytesread;                     /* File write/read counts */
  uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */
  uint8_t rtext[100];                                   /* File read buffer */

  /* Register the file system object to the FatFs module */
  if(f_mount(&USBDISKFatFs, (TCHAR const*)USBDISKPath, 0) != FR_OK)
  {
    /* FatFs Initialization Error */
    USB_Error_Handler();
  }
  else
  {
      /* Create and Open a new text file object with write access */
      if(f_open(&MyFile, "Even.TXT", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK)
      {
        /* 'STM32.TXT' file Open for write Error */
        USB_Error_Handler();
      }
      else
      {
        /* Write data to the text file */
        res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten);

        if((byteswritten == 0) || (res != FR_OK))
        {
          /* 'STM32.TXT' file Write or EOF Error */
          USB_Error_Handler();
        }
        else
        {
          /* Close the open text file */
          f_close(&MyFile);

        /* Open the text file object with read access */
        if(f_open(&MyFile, "Even.TXT", FA_READ) != FR_OK)
        {
          /* 'STM32.TXT' file Open for read Error */
          USB_Error_Handler();
        }
        else
        {
          /* Read data from the text file */
          res = f_read(&MyFile, rtext, sizeof(rtext), (void *)&bytesread);

          if((bytesread == 0) || (res != FR_OK))
          {
            /* 'STM32.TXT' file Read or EOF Error */
            USB_Error_Handler();
          }
          else
          {
            /* Close the open text file */
            f_close(&MyFile);

            /* Compare read data with the expected data */
            if((bytesread != byteswritten))
            {
              /* Read data is different from the expected data */
              USB_Error_Handler();
            }
            else
            {
          /* Success of the demo: no error occurrence */
              //BSP_LED_On(LED4);
              HAL_GPIO_WritePin(LD4_GPIO_Port,LD4_Pin,GPIO_PIN_SET);
            }
          }
        }
      }
    }
  }

  /* Unlink the USB disk I/O driver */
  FATFS_UnLinkDriver(USBDISKPath);
}

The last thing to add to the "usb_host.c" file is the startup of the "MSC_Application" function from the state machine when the USB stick is ready:


static void USBH_UserProcess  (USBH_HandleTypeDef *phost, uint8_t id)
{

  /* USER CODE BEGIN 2 */
  switch(id)
  { 
  case HOST_USER_SELECT_CONFIGURATION:
  break;
    
  case HOST_USER_DISCONNECTION:
  Appli_state = APPLICATION_DISCONNECT;
  break;
    
  case HOST_USER_CLASS_ACTIVE:
  Appli_state = APPLICATION_READY;
  MSC_Application();
  break;

  case HOST_USER_CONNECTION:
  Appli_state = APPLICATION_START;
  break;

  default:
  break; 
  }
  /* USER CODE END 2 */
}

One final thing that is essential to make everything work: There is a bug in the code for the setup of the VBUS for the Discovery board because it is using an external chip (as decribed here). You want to change the settings from SET to RESET in main.c:

  /*Configure GPIO pin Output Level */
  //Bug code: HAL_GPIO_WritePin(OTG_FS_PowerSwitchOn_GPIO_Port, OTG_FS_PowerSwitchOn_Pin, GPIO_PIN_SET);
  HAL_GPIO_WritePin(OTG_FS_PowerSwitchOn_GPIO_Port, OTG_FS_PowerSwitchOn_Pin, GPIO_PIN_RESET);


Now everything should be working. During debugging I noticed that USBDiskPath variable is not setup correctly if the heap and stack sizes are too small. The variable is not filled with content if the setup of the USB fails. The below picture shows a correct setup:


I hope this post is helping you.. I was struggling getting this to work and got no help from other users on the forums, but pushed through and finally got it running :-)

Friday, May 08, 2015

Fransk middag

Venter på Cajun-mat på Cane & Table i New Orleans.

Friday, February 06, 2015

Vellykket

Fra skeptisk til overbevist. Fritzing kretskortproduksjon var både enkelt, relativt billig og av god kvalitet.

Tuesday, July 02, 2013

RIP Google Reader

We will miss you!

Sunday, October 28, 2012

Wednesday, December 21, 2011

Lo tech decoding

Solution to optional exercise in Stanford's "Introduction to Artificial Intelligence". No need for computers...

Tuesday, November 01, 2011

Hot plate PI controller - Part 5: Boiling water and measuring with thermistor

I made a new mistake in my attempt to make a hot plate PI controller: The thermistor I selected from eBay was an unbranded China thermistor marked with "10k ohm 103 NTC Thermistor"with no datasheet. I thought it would be easy to obtain the datas for the thermistor, but so far I have not been able to find any other info than what the seller is saying:

Model: CP_RM_103 NTC Thermistor
Resistance: 10KΩ
Resistance tolerance: +/- 10%
Temperature: 30°C to +125°C

I have sent an email to the seller as a last effort to get a datasheet for the thermistor, but I have doubts that I will get it.

I wanted to set up a test to check the accuracy of the thermistor in combination with the pre set parameters in the arduino library for thermistors. I soldered a wire to the thermistor, filled a pot with 1 liter of spring water, submerged the thermistor and boiled the water. When boiling temperature 100°C is reached the chart for temperature with stabilize at 100 degrees as water is vaporized.

First some theory:
Thermodynamics has equations describing how a volume will be heated. When there is no flow in or out of the volume the heating equation reduce to:

Cp*ρ*V*dT/dt=P+h(T0-T)

Where
Cp is specific heat capacity. For water Cp=4181.3 J/(kg*K)
ρ is the density. For water ρ=1000 kg/m^3
V is the volume. For my experiment I use 1 liter=1e-3 m^3
T is the temperature in the volume.
T0 is the temperature of the neighboring. The air temperature is about 22°C
P is the power of the heating source. I use two different boiling plates with 1.4 and 1.5 kW
h is the heat conduction number

If no energy is transferred to the environment with no other losses whatsoever I get:
Δt=Cp*ρ*V*ΔT/P

I am using two different hot plates:
1. A 1.5 kW standard hot plate. Ideal time for boiling 1l water should be 262 seconds, about 4 minutes.
2. A 1.4 kW induction hot plate. Ideal time for boiling 1l water should be 281 seconds, about 4,5 minutes.

The ideal heating time is based on the tap water being 6°C.

After modifying the LabVIEW VIs used with the thermistor and servo to also save raw voltage data to disk and importing to excel I get these curves:





A couple of things can be observed from the charts:
  1. The heating curve for the induction hot plate is very erratic. This is likely because induction is basically fast alternating current through a coil. This creates a magnetic field that again induces current in the sensor wire. If better results are to be obtained with an induction cooker I need a shielded thermistor.
  2. Both measured heating curves for the induction and standard hot plate has a measured boiling temperature of about 110°C. This is probably due to wrong values for this sensor set for the Steinhart-Hart equation.
  3. The zero crossing with the y-axis is above the temperature of the tap water temperature. This is again probably due to wrong values in the Steinhart-Hart equation.
  4. Some drops are observed for the standard hot plate. This is due to different temperatures when the thermistor touched the pot and when it was only in contact with water.
  5. The slope for the induction cooker is very close to the ideal curve, thus the induction cooker is very efficient at transfering energy into cooking water.
  6. The induction hot plate and pot can be modeled as an integrator without time delay. The standard hot plate can probably be modeled as an integrator with a time delay included. When heating a larger amount of water I am expecting more energy to be transfered to the environment, and  the curves will probably take the shape of a "time-constant with time-delay" process.
Now I need to search a little more to try finding some information about the sensor specs. This in combination with the measured curves will probably give me everything I need to know to calibrate the thermistor.

Hot plate PI controller - Part 4: Playing with thermistor, RC servo and LabVIEW with arduino library


In my previous post I wrote that I wanted to use LabVIEW in combination with an additional Arduino library and the Arduino device to work as a controller. LabVIEW has library for both fuzzy and PID controllers.

I have been testing the LabVIEW PID library in combination with the Arduino library while waiting for my thermistors to arrive. My first test was to use a potmeter as an input for a PID controller setpoint and use a simulated plant to test the PID functionality. I tested the PID relay autotuner, which is a tuner that uses on/off signals to test the plant response. I have previously used relay autotuners successfully to set PID controllers with microcontrollers. The autotuner function in the LabVIEW PID library seems to be more sensitive to having a working PID controller before trying to excite the plant with on/off signals. My experience with the library is that this results in a poorly tuned controller. My plan is to use the step response for the plant to set the controller or make a relay based controller from scratch from my previous knowledge of the problem.

A few days back I finally got my 10k thermistors from eBay. The 10kohm value seems to be rather flexible with the LabVIEW Arduino library, and I cannot really understand why. I thought that the equation used, the Steinhart-Hart thermistor equation, needs three parameters A, B and C set that is allready fixed in the Arduino thermistor read function.



I hooked up the thermistor as shown in the library included thermistor example and one servo as shown in the servo example. Pretty simple:




Next I mixed the two examples together so that the temperature from the thermistor would set the output for the servo. I multiply the temperature with 1.8 so that when I have 100 degrees C input I get a 180 degrees rotation of the servo. I also tested with different delays in the loop to remove some of the "spastic" behaviour you can get when the realtime signal is used.


I experienced a bit with moving the thermistor over a candle to check the system. Below is a video of the system in action:

Here is the output in LabVIEW with and without delay:

I am quite happy with setting this system up so quickly and with both input and output working as planned on the first run.

One thing I experience is that when I stop the LabVIEW program and restart it i get erratic behaviour of the servo. Perhaps because of the PWM output from the Arduino being out of sync with the servo. I need to pull out the USB plug from the computer a couple of times in order to make it work again. This all might have to do with me having an old Arduino or that I got black smoke coming out of it the last time I used it.

Coming up I will be soldering a wire to the thermistor, put it in boiling water and see if I get a reading of 100 degrees celcius. Otherwise I need to get better parameters for the thermistor function.

Hot plate PI controller - Part 3: Arduino and LabVIEW


It's been about three years since I last used the Arduino in any project. The reason for this is that I usually find it equally easy to implement simple things in the AVR microcontroller, rather than spending more money on the arduino. The second reason is that I have usually been working on projects requiring faster throughput time for realtime control of fast acting systems (sound/vibration).

When I now came back to look at the arduino I see that a lot has changed since the last time I used it. The obvious thing being that more modern arduinos and shields for all different kinds of purposes have come to life. The community for Arduino has grown exponentially fast and Arduino is now probably the number one gadget for electronic hobbyists. Software for Arduino has become even more easy to use and make it possible to test arduino code without a physical arduino attached with VirtualBreadboard. National Instruments has recently made it possible to include Arduino in LabVIEW with an additional library, which I will come back to later in the post.

The book "making things talk" learned me a lesson in how to work with microcontroller projects, or any other problem. Rather than trying to attack the complete problem in one chunk I now try to break down the problem in small problems that can be tested one at a time. Some things that you take for granted are usually missed if you try to include the complete set of functionality at once, and even the best debugger/emulator cannot test for every kind of outcome. This is why it is critical to test each problem one at a time.

To test the reading of a sensor, in this project a thermistor, you need a system able to show the input from the sensor to the user. With early versions of the arduino this was best done by using the programming language processing and displaying the input to the computer screen. The only difficulty with this solution was that a fraction of the code you wrote was reusable and you thus needed to write routines each time you had a new kind of problem.

Now LabVIEW, the measurement system that I as a programmer loved to hate, has come up with a complete range of pre built modules to comunicate with the arduino. So you can put all the logics in labVIEW and the input/output can be handled by arduino. This makes everything even more simple. The only problem I see with this solution is that you need a computer with LabVIEW or the labview built application to run the algorithms. I will start working with the labview modules, and later see if I want to move the whole controller and logics to the arduino.

Setting up Arduino with LabVIEW was done in a breeze. The examples and ready made functions for sensors are absolutely amazing.

Full instructions for installing Arduino with LabVIEW can be found here.
National Instruments web page for LabVIEW with Arduino

Here is even a geeky video of what the combo can be used for:

Monday, October 10, 2011

Hot plate PI controller - Part 2: The temperature sensor

The thermometer I am using is the typical stove thermometer that you can buy from any kitchenware store. Mine came with our IKEA / Whirlpool kitchen stove.



I have no idea of the resistance of the thermistor probe that came with the thermometer so I had to set up a little experiment to find the resistance range.

I put 1 litres of water in a pot on an induction plate, turn on the heat for a while, turn it off to let the temperature settle and then measure temperature with the thermometer. Next I measure the resistance with a multimeter.

With four measurements I got this curve:


Excel shows the fitted linear curve and the nice little formula:

Rt=0.2*T-2.7

Where Rt is the termistor resistance and T is the temperature measured in centigrades.

I want to use the thermistor with a resistor and measure the temperature by setting them up as a voltage divider. Input voltage will be 5V:


By setting the second resistor to the value of 5 ohm I get the greatest difference between the lowest and highest measured voltage (2,85V) and thus the best resolution. The curve for voltage measured over the thermistor for the optimal resistor is shown below: 


Defining:
F=Vout/Vin=Rt/(Rt+R)

Calculating for Rt:
1) Rt=R*F/(1-F)

From previous excel linear fitting for measured temperature:
2) T=(Rt+2.7)/0.2

1) and 2) put together:
T=25*F/(1-F)+13.5, where F=Vout/Vin

Finishing with an example:
What is the temperature when you are suppling the voltage divider with 5V and you get an ADC reading is 511?

A reading of 511 in the ADC is a measured voltage of 5V*511/1023=2.5V with a supplied voltage of 5V.

F=2.5V/5V=0.5

T=25*F/(1-F)+13.5=25*0.5/(1-0.5)+13.5=38.5 degrees celcius, which corresponds very well with the curve above.


The real excitement begins when I get a 5 ohm resistor, set up a measurement system and start measuring realtime temperature data. Is boiling temperature still measured to 100 degrees celcius?

_____________________________

Update:

Yesterday I tried setting up the voltage divider with the arduino. I found a 4.7 ohm resistor to use with the thermistor and was ready for measuring temperature with the arduino. 

I had thought very little about the consequences of using such small resistors: When I hook up a 4.7 ohm resistor with a thermistor that has close to zero ohm resistance at room temperature I get a current of 5V/5ohm=1A!! So when I set up the bridge and inserted the USB I got smoke coming out of the arduino or resistor. The arduino seems to be working fine afterwords, though, so I learned my lesson.

So I should rather find a resistor that has as low as possible reistance, without destroying the arduino. How low can it be?

Here are some of the limits:
- The USB 2.0 standard has a maximum current limit of 500 mA. 
- In the summary for the arduino UNO the I/O ports are rated for 40 mA. 
- In the data sheet for the Voltage regulator (LM340) I see a maximum current of 1 A at 5 V.
- I think the resistors I am using is 0,25 W type based on the thickness => Maximum current 50 mA.

I think the input impedance of the ADC pins are quite high, so there will not be much current going through to the ADC. That makes the resistors I am using the weakest link with maximum current 50 mA.

My new resistor will have to be at least 5 V / 0.05 A=100 ohm.

The new temperature chart will be like this:

The voltage range is too low, which means I get bad resolution (about 0.7 deg C) . I either need a different thermistor or a resistor with higher power rating.

In summary: Don't try to reuse the measurement probe from a thermometer. It's cheaper and easier to buy a thermistor with an available datasheet.

Hot plate PI controller - Part 1: The start

I want to make a hot plate controlled by a PI controller. The reasons are primarily to master the PI controller practically with the bonus of being able to control the boiling process when making home made beer.

Yesterday I boiled my first batch of wort and got the feeling of what it takes to control the temperature with several liters of wort (about 30 litres) on a small 1,5 kW old fashioned hot plate. The process was pretty slow, so it is absolutely possible to control it manually, but I want to set it at a specific temperature and let a home made controller do the rest of the job.

The parts I want to use for the project is:

  1. Controller: An old Arduino NT that I got lying around. This will be permanently used for brewing purposes in the future.
  2. Actuating element: A 1,5 kW hot plate of the old kind with built in on/off controller and stepless adjustment of power.
  3. Actuator: A 180 degrees adjustable Hitec HS-325HB RC servo for attaching to the power knob.
  4. Temperature sensor: A termistor type termometer that I want to reverse engineer and use the probe from.

Wednesday, January 05, 2011

How to set up VirtualBox shared folders with Windows 7

Start by adding shared folders in settings before starting the VM:

Next install guest additions after windows 7 VM has started:

If you are using autoruns you will be asked to install guest addition. Otherwise open the cd rom drive and run installation. You will be asked to restart the VM when finished.

After restarting you should now find your shared folders under Network\VBOXSVR within the Explorer (windows key+E).

Tuesday, April 13, 2010

How to change payment information in itunes when caught in an endless loop

I have been sufferig the latest couple of week by not being able to change my billing information in either iTunes or directly on my iPhone. I kept trying to change my old credit card info to a different card or setting the payment method to none, but every time I returned to my payment information nothing had changed. A message allways appeared in iTunes stating that "there were errors or omissions". I was unable to buy anything from iTunes or update apps on my Iphone.

The solution: I am currently an iphone developer and opened my web browser to developer.apple.com/iphone. I then resent my programmer status and contact information and accepted the latest agreement from apple. I suddenly was able to change my billing information to whatever I wanted.

Monday, January 11, 2010

Valg av varmeløsning

Jeg har i den siste tiden hatt mye å tenke på angående hvordan vi skal varme opp det nye huset vi skal bygge. I den siste tiden har det dessuten vært en glohet diskusjon angående varmekilder, noe takket være den kalde perioden vi har vært gjennom nylig.

Til å begynne med ble jeg svært fristet av å installere en vannbåren varmeløsning, med varme i alle golv i begge etasjene, totalt 190 m^2. Jeg har blant annet hørt om denne fantastiske lunheten man får med bruk av rørlagt vann i gulvene.

Vi ba utbygger om å komme med pris på luft-vann varmepumpe og vi fikk prisantydning på ca 170000, noe jeg personlig synes var styggdyrt. Etter å ha sett på NRK og FBI fikk jeg høre at prisen på strøm antagelig ville øke med 25% de neste ti årene. Jeg antok at merkostnaden for ei bergvarmepumpe kommer på prisen for borring, kanskje 50000. Jeg ønsket dessuten å sammenlikne med ei habil luft-luft varmepumpe på 25000. Pellets eller sentral vedfyring ble først vurdert, men disse falt bort da vi ikke har kjeller eller plass til silo for disse løsningene.

Etter å ha gjennomgått energikalkylen for vårt planlagte hus (205 m^2 BRA) hos energimyndigheten.se fikk jeg mengen energi som kunne spares for hvert år. Med beregnet prisøkning for strøm fikk jeg følgende kurver:



På kurven ser vi at det tar ca 4 år å spare inn en luft-luft varmepumpe, 12 år for luft-vann og 14 år for vann-vann. Det tar dessuten ca 20 år før alle løsningene er like lønnsomme. Dette forutsetter selvsagt at anlegget holder i hele perioden. De beste garantiene for varmepumper gjelder for 10 år, så du skal være heldig dersom pumpen varer en hel investeringsperiode.

Etter en prat med utbygger i dag ble jeg til slutt overbevist: På grunn av den nye byggenormen av 2010 vil huset være svært godt isolert og ventilert. Gulvene vil også være lune. Med elektriske panelovner på alle rom og varme i golv på bad og vaskerom burde vi ha et hus som er lett å holde passe varmt. Vi vil dessuten installere en god ovn med gratis fyring og evt en luft-luft varmepumpe dersom vi ser at strømforbruket blir høyt allikevel.

Friday, January 01, 2010

Mini review of "The Power of LESS" by Leo Babauta


Personal productivitiy systems have been very popular the latest years, kickstarted by David Allen's massive success "Getting Things Done". The book probably made Allen a very rich man and started a cult of GTD followers. Every follower had their own little twist of change to what Allen wrote in his book and websites and blogs like 43 folders and lifehacker introduced readers to new systems on how to adapt to GTD. Leo Babauta also started his own site Zen Habbits where he wrote about his own experiences with GTD.

I first found Zen Habbits about a year ago, when I was looking for other GTDers stories about how they made GTD work for them. I had been an avid user of the system about two years then, and was looking for a new GTD software system to change to.

Leo Babauta identified some flaws with Allen's orignal system. The most important ones being the lack of priorities amongst different projects and thus the lack of focus on each individual task. Even though Allen have suggestions for selecting projects based on long term goals and a "someday maybe list" for those projects you cannot work with right now, he never seem to mention anything about minimizing the amount of simultaneous projects and reducing the number of tasks you are saying yes to. I think Leo Babauta is into something when he asks you to limit yourself to the essentials in order to get the maximum out of everything you do.

Ok, so I was about to tell you about feelings about the book "The Power of Less". It would be impossible to write something about it without the former introduction. If you allready are a user of GTD today I would say that you can find everything extra you need to know from reading the most important articles at Zen Habits. I have a slight feeling that some of the articles might be word by word the same as on the web site. If you are new to GTD or don't know about Zen Habits on the other hand, I would highly recommend you pick up the book and start reading. It is a quick read (about a day for me) and adds good wisdom in today's fast lane society.

Tuesday, December 29, 2009

Mini review of "Brain Rules" by John Medina



I am not sure how I came across the book "Brain Rules" by John Medina, but I had put it on my Christmas wish list and got it as a gift. My hopes before starting reading it was that I was going to pick up a few tips and be inspired to change my ways of doing things in a more brain friendly way.

The book chapters are sectioned in what Medina calles "brain rules" or principles of how the brain is working. The chapter titles are exercise, survival, wiring, attention, short-term memory, long-term memory, sleep, stress, sensory integration, vision, gender and exploration. The actual brain rules for each topic can be found on medinas site: http://www.brainrules.net/. The videos on the site are quite good for catching the essence of each rule too and for repetition as well.

Each chapter usually uses plenty of examples of how the brain is working, usually experienced by the author himself. The examples are coupled to brain research and brain anathomy in a humorous way. At the end of each chapter Medina has a few ideas on how the brain rules can be put to practical use.

Many chapters are quite captivating and I found myself fascinated on how complex the brain actually is. The most important points I picked from the book are:

  • Learning is better done while exercising. Try to combine the two if possible.
  • Create strong pictures when you really want to remember things.
  • Teach and learn in periods of about 10 minutes at a time. The brain loses attention and gets bored after this time.
  • Recreate the environment of where you learned something when you want to recollect it.
  • Understand every word in a sentence that you want to understand.
  • In a presentation: Catch the audience's attention at an early moment.
  • Use plenty of examples when you want to explain something.
  • Multitasking is a waste of time.
  • Learn by doing. The brain is an expert at adapting to new tasks.
  • The best way of really learning something: Repeat every 10 minutes for three times and then repeat the most important things every 3-4 days.
  • Get sufficient sleep.
  • Avoid long term stress. Ask the question "am I in control?" if you are not sure if you are stressed.
  • Strengthen learning by using many senses at a time.
  • Your learn much by watching pictures in combination with relevant text, but more with narration and videos.
  • Reduce the amount of text in powerpoints - The brain is lazy and avoids reading text.
  • Vision is the most powerful sense and actually uses half of the brain's processing power.
  • Women capture the emotional details while men see the gist when experiencing acute stress.
So was the book worth reading? I think it was ok reading the book, but I think Medina got a little to detailed for my taste. I never wanted to be a brain scientist. I got what I wanted in the end: some great techniques for improving learning backed up with science. I will put it to practise - no doubt about it.

Thursday, October 15, 2009

How to locate, read and write property lists for iPhone

I had a real headache trying to figure out how to read and write property lists yesterday. It should have been an easy task, and I did everything according to the manual.

Here is what I wanted to do:
  1. Locate a property list created in xcode
  2. Read the XCode property list to a NSDictionary
  3. Append one or more extra items to the NSDictionary
  4. Save the updated NSDictionary to disc
The problem was that the iPhone has a sandboxed area called "Documents" where you can read and write property lists, but the property list you created in xcode is not located in this folder.

If you create a property list "MyPlist.plist" for an application called "MyApp" in XCode it will be located here:

appPath/MyApp.app/MyPlist.plist

Where "appPath" is a string that you can only get while running the app. You can get the whole path to the plist by using this code:

NSString *path = [[NSBundle mainBundle] pathForResource:@"MyPlist" ofType:@"plist"];

This file could be read from, but not written to due to the location on the iPhone.

But I wanted to save data to the iPhone. This could only be done in a property list located here:

appPath/Documents/MyPlist.plist

To locate the folder "Documents" where I have rights to both read and write I can get the path by using this code:

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory=[paths objectAtIndex:0];
NSString *path=[documentsDirectory stringByAppendingPathComponent:@"History.plist"];

Reading and writing to the property list from a NSDictionary could be done with the following code:

Reading: NSDictionary *dict=[[NSDictionary alloc] initWithContentsOfFile:path];
Writing: [dict writeToFile:path atomically:YES];

Here is the whole code put into action:

NSMutableDictionary *dict;

//Reading plist created in xcode
NSString *path = [[NSBundle mainBundle] pathForResource:@"MyPlist" ofType:@"plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

//Reading plist stored on device
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory=[paths objectAtIndex:0];
path=[documentsDirectory stringByAppendingPathComponent:@"MyPlist.plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
//Merging dictionary created in xcode with dictionary stored on the iPhone
[dict addEntriesFromDictionary:tempDict];
}

//Creating dictionary if it doesn't exist
if (dict==nil) dict=[[NSMutableDictionary alloc] init];

//creating and adding array to dictionary
NSArray *array=[NSArray arrayWithObjects: [NSDate date], [NSNumber numberWithDouble:double1], [NSNumber numberWithDouble:double2], [NSNumber numberWithDouble:double3], [NSNumber numberWithDouble:double4],nil];
[dict setObject:array forKey:@"First Array"];

//writing dictionary to plist on device
[dict writeToFile:path atomically:YES];
[dict release];

Wednesday, September 02, 2009

How to connect icd3 ac162049 with a PIC microcontroller.


I confess I'm a hopeless beginner when it comes to Microchip's PIC microcontrollers. After playing around several years with AVR microcontrollers I figured it was time to go for the hobbyists second choice - the PIC.

My first impression is that Atmel has outpriced themselves after earlier being able to deliver cheap developer boards like the STK500. I wanted a programming device that was able to program DIL devices for rapid prototyping and for hobby projects and ended up buying an Microchip ICD3. I also bought a AC162049 universal programming module to be able to program several different DILs without having to make circuit boards first.


I am familiar with some other chips from Microchip, and have always found the datasheets quite understandable. With the ICD3 it was a completely different story. I was not able to connect to the dsPIC33FJ128MC that I knew was compatible with the ICD3. After looking around a bit I found out how to communicate with the device:

  1. Connect a 4.7-10 kOhm pullup resistor from one of the two VDD wires to the _MCLR pin.
  2. Connect all other wires except VPP to the pins in the datasheet for the microcontroller. GND wires should be connected to Vss. PGC and PGD should be connected to any of the pins starting with PGC or PGD. I used PGC1 and PGD1.
  3. Open MPLAB IDE and choose "Configure-Select Device". Choose the device you are using.
  4. Open "Programmer-Select Programmer"and select "MPLAB ICD3".
  5. Open "Programmer-Settings-Power" and check "Power target circuit from MPLAB ICD3".
Now you should be able to connect to the microcontroller. For me it was the setting for the power that I missed. After using a voltmeter I found that the microcontroller didn't have any power.

Tuesday, March 24, 2009

Simple TWI / I2C communication with AVR ATMega8 and TC1321 DAC

I wanted to set up and test the D/A-converter TC1321 with a AVR, but had no previous knowledge of TWI. These are my experiences:

To make things easier I used a AVR with built in TWI function. I got a little confused on this subject when I read on AVR Freaks that for example the ATTiny26 had TWI function. Actually the microprosessors with a lowercase "y" in the comparison chart has USI which can be used for TWI. The uppercase "Y" for TWI indicates that the uC has built in TWI functionality. With such uCs you can include the to get some free predefined twi-codes.

To connect to a TWI device you need to connect the SCL and SDA lines to the uC. For ATMega8 it is PC4 (SDA) and PC5 (SCL). You then need to connect each of these via a pullup resistor to the source voltage (5V). For this connection I used two 220 ohm resistors.



So to sum up: I found it easier than I thought to interface the TC1321. Reading through descriptions that others have made describing both reading and writing to a slave (EEPROM etc) was not necessary when the only thing I wanted was to send data.

I found it easier than I had thought to communicate with the TC1321. First you need to set up the SCL-clock rate. You can calculate the TWBR with this formula:
TWBR=(fCPU/fSCL-16)/(2*4^TWPS)

So if you run your uC at fCPU=8MHz and you want fSCL=100kHz and try to use a prescaler TWPS=0 you get TWBR=(8e6/100e3-16)/(2*4^0)=32. So you start by setting:

TWPS=0;
TWBR=32;
To send data to the TC1321 you can use two protocols: 1-byte format (8-bits) and 2-byte format (10-bits). The progress of sending data is made in a sequence like this:

1-byte format:
START
SLA+W
COMMAND
DATA
STOP

2-byte format:
START
SLA+W
COMMAND
DATA
DATA
STOP

In between every sending you check the status codes by looking at TW_STATUS. The SLA+W is actually only the slave adress, 0x90.

Here are some functions that can be used to send data to the TC1321:


So to sum up: I found it easier than I thought to interface the TC1321. Reading through descriptions that others have made describing both reading and writing to a slave (EEPROM etc) was not necessary when the only thing I wanted was to send data.

Sunday, March 01, 2009

Mini review of "The 4-hour work week" by Timothy Ferris




I came across this book as I was looking for material before having a inspirational lecture about mathematics to new high school students. I ended up having a lecture of why you should embrace learning different things and the importance of knowing a little about most things in life. This is actually what Timothy Ferris was looking for when he decided to break out of his 9-5 traditional work as an employer ("slave" in his words) and start managing his own future. He wanted to work less, earn more and spend the extra time and money he had for traveling and enjoying life while he still was young and able to live it.

The book is a blue print on how to [D]efine your goals in life ("dreamlines"), [E]liminate time wasting and start focusing on realizing those goals (by using Pareto's principle and Parkinson's law), [A]utomate your business (by using outsourcing and the wonders of computers) and [L]iberating yourself from current work and the life you are living.

I really liked the book: It gave me a kick in the butt to start focusing on progressing towards my most important goals. Even though the internet business modell is perfect for people having a big home market, many of the tips are quite transferrable to everyone wanting to start up something new.

I am not dreaming about traveling the world throughout my life anymore, but I still would prefer having more time for hobbies and family. I think this book gave me gigant leaps towards achieving this.