Search Microcontrollers

Saturday, June 13, 2015

Should rights be "forever" in a ever-changing world?

We fight for our rights, many, if not most, of our heroes are those who gave their lives to obtain and preserve some rights we now hold dear.
These include freedom, equality (Liberté, égalité, fraternité anyone?)  down to some more modern era/more detailed and specific rights such as (in some countries) refuse to join an army, work-life balance, health, even a minimum wage or a "citizenship income" in some places etc.
People should not work more than 8 hours a day (may vary slightly by country).
Took a while to achieve that and we consider it an important milestone in human rights.
I am all for it, don't get me wrong, in fact it might even be the case we should at this point (some did) reduce those 8 hours.
But, what IF it does not make anymore sense, meaning that in a given context, a given society, that does not work anymore, it is not sustainable.
Would it be still a right?

Now, the one I would like to discuss is even more radicated in our culture, in a way that every single politician in every single campaign would advertise he/she will do everything to boost it.
Politicians do their research (with our money) and even the dumbest of them are able to select their stands on these topics, so I know I will attract a lot of hatred reactions just for discussing the matter, but, hey, go ahead, hating is one of your rights after all (and I am not running for office anytime soon) :)

The right to have a family.
Ok, ok, I hear you booing already, once you are done, can we have a serious discussion about it?
The "light" version of it says that a men and a woman should be able to marry.
A slightly modernized version says that two humans, regardless of their sex and their sexual preferences, should be able to marry.
I am fine with both versions, no issues here.

Now, in most places this extends to "a family"  in the sense you have rights to have children.
Children are cool I guess, who could argue with that?

Before we go ahead, I know in these discussions we are all biased, so I will just declare my bias upfront, for the benefit of a rational and honest discussion :
I have no children, never married, never wanted to, never felt the urge to create a family, for a number of different reasons.
At this point I guess you MUST be hating me a little bit already, right?

Ok, now, back to the point.
Rights to have children in general means a lot of things which go beyond the actual fact of having one or more babies.
It ties into making it easier to families to support them, in other words it is like the society is promoting families.
In most countries the society recognizes that raising children is an expensive task, so you get a little bit of tax reductions, some maternity leave rights (for both parents) etc.
These "allowances" are granted  using the society resources (mainly collected taxes) as in general such resources should go to support the citizen's rights and well being.
If something is a citizen's right, then I totally agree that the society should do whatever possible to favour its implementation and even promote it.
But is it?
Is transmitting your DNA really a right and, in a more general sense, can we say that a right is still a right regardless of the context, forever?
Or can we say that rights are a mere product of our culture, which, in turn, generates from our history?

Let me introduce another bias I have : I am an atheist (which I find a funny definition, but most of you would call me that way) and have no holy book telling me what's good or wrong. I do need to find it out myself and for this reason I ask myself several questions and sometimes discuss them with others.

So, it is clear that the urge of transmitting our DNA is present in all animal species, but normally they (slowly) evolve, both genetically and "culturally" in a  way that affects their reproduction rate according to the needs.
A wonderful explanation of this concept (although with the opposite problem) can be found in the speech that Douglas Adams gave for TED, about 1 third in the speech, when he tells the story of the Kakapo.

I strongly encourage you to watch the full speech as D.A. was a phenomenal speaker on top of being a witty and creative writer.

(Douglas Adams : "Parrots, the universe and everything")

The "problem" with humans is that we became remarkably efficient in modifying the environment around us to suit our needs, so, when the environment was supposed to counter our expansion, we fought back and somehow "won".

Going from the Kakapo to another animal that might be more familiar to all of us, let's consider the cat.
I love cats, in fact I live with two 10 yr old females since quite some time.
Most of the people who love cats agrees -like I do- that it is a good thing to spay or neuter them.
In the wilderness, the chances of survival of a cat in his/her first years are pretty slim, plus when the populatuion grows in a given area, it is regulated by competition for food or territory.
So they needed to procreate very quickly, the fittest would generally survive and maintain the specie alive.
Since most of the cats now live with humans, they share the "benefits" of the modified environment, i.e. we provide medical care and food for them which extends greatly their life expectaion and dramatically reduces chances of deaths for lack of food etc.
Is the cat risking extinction because we neuter and spay most of them?
Not that I am aware of, in fact it seems to me that population control, given the actual context, is being a benefit for the cat specie.

Now, why would it be different for humans?
Take a look at this chart :

Does anybody see any alarming trend there?
Humans in 1960 : 3.000 Millions
Humans in 2050 (projection) : 9.000 Millions
( 3x in 90 years)

Cat's chart would have been similar (worse actually, because of their high reproduction rate) if we did not take actions. We realized that having an average of 3 cats per square meter aound us would have been quite an issue for everybody, including them.
Cats have no right to procreate in fact, it did not take long to us to negate that one to them, few complained.

Now, back to humans, I believe it is culturally difficult to "cap" the number of children a family should have (it is somehow happening in some places), mainly because we feel that having them is a right.
For the same reason we still try, as a society, to encourage families to have children.
But, does it make sense?

Shouldn't a behavior that actually damages the society, the human kind and the whole world alltogether be considered more like a crime, rather than a right?
I know this is a strong statement, but it is really a question.
I am not immune to cultural biases either, so that question scares me as well.
But I do know that sometimes truth can be scary, because it shakes our belief system, but I grew accustomed to this, I know that scary or not does not change the fact that it is the truth.

I also imagine many of you will say things like : "If your parents thought the same thing, you would not be here blogging" and yes, I can see that, but, so what?
Isn't this an incredibly egoistic thing to say?
Each one of us feels special, but from the community point of view we are just another human contributing both with good and bad interactions.
I try my best, most of the time, to ensure that my contribution to the society is worth the air I breathe and the food I eat, sometimes I question it (and I believe that's a good exercise).

Can our society still consider that having babies is a human right?
Should rights be demoted to "cultural habits" and eventually to "bad habits coming from a past, different, context" when they damage the society?

Pick your answer and try to be consistent with facts.

Thursday, May 21, 2015

Cortex M3 - SPI / 1

I have been playing with SPI a few times, but never on a Cortex M3 using CMSIS.

That, by itself, it should be a good reason to dig into this topic, however I have a nice project in mind and it will require SPI communicatin, so... let's  get to it!

Some basic stuff first :
SPI uses four pins: MOSI (Master Out Slave In), MISO (you guess it), CLK (clock) , SSEL and as Chip enable/select to activate the slave, normally a simple GPIO pin on the master.

NXP Cortex M3s implement a variation of SPI called SSP (Synchronous Serial Port) which supports the "old" SPI.
In the LPC1768 there are two SSP peripherals called SSP0 and SSP1.

The LPC17xx manual says:

"The two SSP interfaces, SSP0 and SSP1 are configured using the following registers:

  1. Power: In the PCONP register, set bit PCSSP0 to enable SSP0 and bit PCSSP1 to enable SSP1.
    Remark: On reset, both SSP interfaces are enabled (PCSSP0/1 = 1).
  2. Clock: In PCLKSEL0 select PCLK_SSP1; in PCLKSEL1 select PCLK_SSP0. In master mode, the clock must be scaled down.
  3. Pins: Select the SSP pins through the PINSEL registers and pin modes through the PINMODE registers.
  4. Interrupts: Interrupts are enabled in the SSP0IMSC register for SSP0 and SSP1IMSC register for SSP1. Interrupts are enabled in the NVIC using the appropriate Interrupt Set Enable register.
  5. Initialization: There are two control registers for each of the SSP ports to be configured: SSP0CR0 and SSP0CR1 for SSP0, SSP1CR0 and SSP1CR1 for SSP1.
  6. DMA: The Rx and Tx FIFOs of the SSP interfaces can be connected to the GPDMA controller
Remark: SSP0 is intended to be used as an alternative for the SPI interface, which is included as a legacy peripheral. Only one of these peripherals can be used at the any one time" 
(@NXP LPC17xx user manual)

It seems to me this is a pretty good checklist.

1) Power ON

Power CONtrol for Peripherals (PCONP) is the register we use to turn the SSP (or any other) interfaces on:

  LPC_SC->PCONP |= (1 << 21); /* Enable power to SSPI0 block */
  LPC_SC->PCONP |= (1 << 10); /* Enable power to SSPI1 block */

Normally we just need one, I reported the lines for both so you can decide which one to use.

2) Clock in

The Peripheral clock selection is done via the PCLKSEL0 and 1.
Each peripheral uses 2 bits

00 : PCLK_peripheral = CCLK/4 00
01 : PCLK_peripheral = CCLK
10 : PCLK_peripheral = CCLK/2
11 : PCLK_peripheral = CCLK/8

SSP0 uses bits 11:10 of PCLKSEL1 and SSP1 uses bits 21:20 of PCLKSEL0

LPC_SC->PCLKSEL1 &= ~(3<<10);  /* PCLKSP0 = CCLK/4 */
LPC_SC->PCLKSEL1 |=  (1<<10);  /* PCLKSP0 = CCLK */

LPC_SC->PCLKSEL0 &= ~(3<<20);  /* PCLKSP1 = CCLK/4*/
LPC_SC->PCLKSEL0 |=  (1<<20);  /* PCLKSP1 = CCLK */

3) Pins

Here we will set MISO, MOSI and CLK pins, plus you need to remember to set 1 GPIO as output to enable the slave, in this example we will assume you are using GPIO P1.21 as SSEL (Slave Selection / Enable).
Normally SPI slaves are selected active when SSEL is LOW.

A summary of the available configurations for SSP pins :

 /* ----> SSEL : output set to high. */
LPC_PINCON->PINSEL3 &= ~(0<<10);   /* P1.21 SSEL (used as GPIO)   */
LPC_GPIO1->FIODIR   |=  (1<<21);   /* P1.21 is output */
LPC_GPIO1->FIOPIN   |=  (1<<21);   /* set P1.21 high*/
 /* ----> SSP0 : SCK, MISO, MOSI  */
LPC_PINCON->PINSEL3 &= ~(3UL<<8);       /* P1.20 cleared  */
LPC_PINCON->PINSEL3 |=  (3UL<<8);       /* P1.20 SCK0  */
   /* P1.23, P1.24 cleared        */ 
LPC_PINCON->PINSEL3 &= ~((3<<14) | (3<<16)); 
   /* P1.23 MISO0, P1.24 MOSI0    */ 
LPC_PINCON->PINSEL3 |=  ((3<<14) | (3<<16)); 

 /* ----> SSP1 : SCK, MISO, MOSI  */
LPC_PINCON->PINSEL0 &= ~(0x3F<<14);  /* P0.7,8,9 cleared  */
    /* ... an then set to function 2 */
LPC_PINCON->PINSEL0 |=  (2UL<<14) | (2UL<<16) | (2UL<<18);

4) Interrupts

As suggested by the checklist, we will use the SSP Interrupt Mask Registers SSPxIMSC.

As you can see, these interrupts are used to identify error conditions or FIFO status to ease buffered communication.
Since SSP is a synchronous communication (unlike the UART), there is no point in having a RX data ready interrupt.
In fact, each time you want a slave device to send you some data, using SPI / SPSS you explicitly have to ask for it (polling), meaning you should also be already listening for it to arrive, no need for an interrupt.

Should you need to implement some more advanced control, feel free to enable those interrupts, in that case you should check the SSPxRIS (Raw Interrupt Status), SSPxMIS (Masked Interrupt Status) and SSPxICR (Interrupt Clear) registers.

5) Initialisation

Ok, we definitely need this one.
What we need here is to accurately set the bit frequency, so that it will match the frequency supported by the slave device we are interfacing.
This is done via the Prescaler Register (CPSR) that divides the peripheral clock (pclk) we initially configured in step 2 (PCLKSEL0 and 1).

So, let's assume our processor is running at 100MHz, we fed the peripheral with the same clock speed (by providing a divider = 1) and now we want to obtain a 400KBit/s rate.
How do we do that?

#define sspKBps 400000
int prescaler = SystemCoreClock / sspKBps; 
/* 100.000.000/400.000 = 250 */

LPC_SSP0->CPSR = prescaler; /* for SSP0 */
LPC_SSP1->CPSR = prescaler; /* for SSP1 */

Now we need to use the SSP Control registers to specify how many bits should be transferred and which protocol -Frame Format- to use (remember, the SSP can do more than SPI, in fact it supprots TI and Microwire formats too). 
Also, we can further reduce the bit rate here by dividing the value of the prescaler, plus we can set clock phase and polarity.

/* SSP0 : 8Bit, SPI, CPOL=0, CPHA=0 */                                  
LPC_SSP0->CR0  = 0x0007;   
/* SSP1 : 8Bit, SPI, CPOL=0, CPHA=0 */                                  
LPC_SSP1->CR0  = 0x0007;   

The Control Register 1 (CR1) allows to enable the SSP port and to configure it as master or slave.

LPC_SSP0->CR1  = 0x0002;       /* SSP0 enable, master  */
LPC_SSP1->CR1  = 0x0002;       /* SSP1 enable, master  */

6) DMA

I am sure some day I will feel particularly brave and will have a go at it, for now, let's just say that we can enable DMA transfers for SSP ports using the SSPxDMACR registers.

Ok, with all this our SSP port should be ready for communication, at least on the Master side.

So, where do we put output data and from where do we get input?
There is a Data Register SSPxDR (we can use the low 16 bits) that is used both for RX and TX.
Why is this possible?
SSP (or SPI) is synchronous communication, meaning you cannot write and read at the same time on the line, or better, for every byte you send out, you will get a byte back.

The LPC17xx manual says :

"Write: software can write data to be sent in a future frame to this register whenever the TNF bit in the Status register is 1, indicating that the Tx FIFO is not full. If the Tx FIFO was previously empty and the SSP controller is not busy on the bus, transmission of the data will begin immediately. Otherwise the data written to this register will be sent as soon as all previous data has been sent (and received). If the data length is less than 16 bits, software must right-justify the data written to this register.

Read: software can read data from this register whenever the RNE bit in the Status register is 1, indicating that the Rx FIFO is not empty.
When software reads this register, the SSP controller returns data from the least recent frame in the Rx FIFO. If the data length is less than 16 bits, the data is right-justified in this field with higher order bits filled with 0s"

Looks like we need to check the Status Register (SSPxSR)

So, putting it all together, to exchange 1 byte we need to :

int SSP1_sendbyte(int out)
// enable your GPIO used as SSEL
 LPC_GPIO1->FIOCLR = 1<<21; // enable slave
 // while(!(LPC_SSP1->SR & 1)) ; // Wait until TX Empty
 // might need a grace period here, depending on the slave
 LPC_SSP1->DR = out; // output data
 // while(LPC_SSP1->SR & (1 << 4)); // Wait until SSP is busy
  while(LPC_SSP1->SR & (1 << 2)); // Wait until we have data in RX
 LPC_GPIO1->FIOSET = 1<<21; // disable slave
 return LPC_SSP1->DR;

In a future post we will test this with some SPI device.