Why are GPIOs used? - embedded

I have been searching around [in vain] for some good links/sources to help understand GPIOs and why they are used in embedded systems. Can anyone please point me to some ?

In any useful system, the CPU has to have some way to interact with the outside world - be it lights or sounds presented to the user or electrical signals used to communicate with other parts of the system. A GPIO (general purpose input/output) pin lets you either get input for your program from outside the CPU or to provide output to the user.
Some uses for GPIOs as inputs:
detect button presses
receive interrupt requests from external devices
Some uses for GPIOs as outputs:
blink an LED
sound a buzzer
control power for external devices
A good case for a bidirectional GPIO or a set of GPIOs can be to "bit-bang" a protocol that your SoC doesn't provide natively. You could roll your own SPI or I2C interface, for example.

The reason you cannot find an answer is probably because if you know what an embedded system is and does, or indeed anything about digital electronic systems, then the answer is rather too obvious to write down! That is to say that if you get as far a s actually implementing a working embedded system, you should already know what they are.
GPIO pins are as a minimum, two state digital logic I/O. In most cases some or all of them may also be interrupt sources. These interrupts may have options for be rising, falling, dual edge, or level triggering.
On some targets GPIO pins may have configurable output circuitry to allow, for example, external pull-ups to be omitted, or to allow connection to devices that require open-collector outputs, and in some cases even to provide filtering of high frequency noise and glitches.

In most embedded systems, a processor will be ultimately responsible for sensing the state of various devices which translate external stimuli to digital-level logic voltages (e.g. when a button is pushed, a pin will go low; otherwise it will sit high), and controlling devices which translate logic-level voltages directly into action (e.g. when a pin is high, a light will go on; when low, it will go off). It used to be that processors did not have general-purpose I/O, but would instead have to use a shared bus communicate with devices that could process I/O requests and set or report the state of the external circuits. Although this approach was not entirely without advantages (one processor could monitor or control thousands of circuits on a shared bus) it was inconvenient in many real-world applications.
While it is possible for a processor to control any number of inputs and outputs using a four-wire SPI bus or even a two-wire I2C bus, in many cases the number of signals a processor will need to monitor or control is sufficiently small that it's easier to simply include the circuitry to monitor or control some signals directly on the chip itself. Although dedicated interfacing hardware will frequently have output-only or input-only pins (the person choosing the hardware interface chips will know how many signals need to be monitored, and how many need to be controlled), a particular family of processor may be used in some applications that require e.g. 4 inputs and 28 outputs, and other applications that require 28 inputs and 4 outputs. Instead of requiring that different parts be used in applications with different balances between inputs and outputs, it's simpler to just have one part with inputs that can be configured as inputs or outputs, as needed.

I think you have it backwards. GPIO is the default in electronics. It's a pin, a signal, that can be programmed. Everything is made up of these. For a processor, dedicated peripherals are a special case, they're extras for when you know you want a more limited function.
From a chip manufacturers perspective, you often don't know exactly what the user needs so you can't make the exact peripherals on your chip. You make generic ones instead. Many applications are so rare that there's no market for a specific chip. Only thing you can do is use GPIO or make specific hardware yourself. Also, all (unused or potentially unused) pins are worth turning into GPIO because that makes the part even more generic and reusable. Generic and reusable is very nearly the whole point of programmable chips, otherwise you would just make ASICs.
Some particularly suitable applications:
Reset parts (chips) in a system
Interface to switches, keypads, lights (all they have is one pin/signal!)
Controlling loads with relays or semicondctor switches (on-off)
Solenoid, motor, heater, valve...
Get interrupts from single signals
Thermostats, limit switches, level detectors, alarm devices...
BTW, the Parallax Propeller has practically nothing but GPIO pins. Peripherals are made in software. It works very well for many uses.

Related

Why can't the GPIO be accessed/changed from User space?

This may be regarded as a naive question.
I'm used to bare-metal programming where I changed register values manually in order to write in the GPIO. Conversely, I read those same registers when needing information.
I've recently moved to embedded linux. I've remarked that now dealing with the GPIO cannot be done from code running in the user space.** I can imagine there it might be some security/sanity reason for this but I cannot see it. Why can't code from user space read/write in the GPIO? An example on a problem that could be caused by that would be great.
** I am aware of libraries/APIs that enable you to deal with the GPIO from user-space, and I am learning to use them. My question is pure out of curiosity.
On some platforms it can be, but it's usually avoided.
Typically Linux runs on hardware with an MMU providing both page-level memory protection, and remapping of a virtual address space to physical addresses.
To access a memory-mapped GPIO from userpace, you'd need to configure the MMU to map the register hardware address into the desired process's virtual address space, and you'd need to enable read and/or write access to that page.
The problem though is that the granularity is typically poor - a memory page may be something like 4 kilobytes, while a GPIO pin's behavior is governed by a few distinct bits in several different registers. So it's not possible to expose an individual pin to a given process.
Additionally, doing this from userspace would require knowing the precise hardware details of how GPIO works on a given platform, and that's information which usually better belongs in a driver.
There are a few cases where using the sysfs interface is too slow, for example trying to bit-bang some slower interfaces. But typically in those cases rather than trying to handle the GPIO directly from userspace, a kernel module is written which does the bit-banging from kernel space, and then userspace uses a syscall to pass entire mid- to high- level operation requests to the kernel.

Do every pin of a micro controller associated with a register?

I'm a beginner in the embedded system development world.
I would like some clarifications on the following questions.
Is every pin of a microcontroller (from here after referred to as mc) associated with a register?
Is it an one to one relationship?
How are ports (or groups of pins) assigned inside the mc?
Is it only possible to set a single pin low or high only?
No. Some pins are not associated with a register at all, e.g. Vcc and GND and if they do not have a dual use as a GPIO it also applies to clock/oscillator and reset pins.
If a pin is associated with registers, it is usually associated with several ones: one for determing the IO direction, one for reading the input, one or more for setting the output. For I2C, SPI, UART pins, the associated is indirect, i.e. the register mainly control the I2C/SPI/UART controller, which in turn is associated with the pin.
I don't understand the question
A GPIO pin can be set as input, as output in high state (delivering current or with a weak pull-up), as output in low state (sourcing current or with a weak pull-down) or in open-drain state (often similar to input mode). A pin can also be configured to be used by one fo the I2C/SPI/UART controllers or as DAC (outputting a variable voltage between GND and Vcc).
In addition to fundamental stuff like supply and clock pins, a MCU got numerous hardware peripherals internally. A hardware peripheral being something like a piece of GPIO (general-purpose input/output), ADC, UART, SPI etc. Each such hardware peripheral has a number of possible pins to which its functions can be routed.
Traditionally, these were pretty much fixed - if you wanted UART Tx then you would always get it on some fixed pin number, take it or leave it. Nowadays, most MCUs are quite flexible internally, allowing you to re-route hardware peripheral functionality to almost any pin you like, variably.
In either case, several hardware peripherals could share the same pin, and then it is MCU specific which one that takes precedence. For example GPIO could be present on the pin by default, but if you enable UART then maybe the MCU states that you get UART Tx on that pin instead.
As for the hardware peripheral called GPIO, they are almost always grouped in ports, where each port consists of a number of pins. Most often, port registers are either 8 bits or the size of the CPU's word length. Each bit in the various port registers corresponds to a pin.
You'll have a port data register, which is the actual read/write to the pin, a data direction register stating input or output, and then various other registers for interrupts, pull resistor enable etc etc.
Not all pins but all IOs (Input/Output) have a specific register.
Each IO has a specific group of registers. Bu also some registers may include specific bits which effects an IO or all IOs.
It depends of design of micro controller.
Yes it is.
I strongly recommend you to read some embedded hardware/software books(for example Newness Know It All books for embedded systems) and datasheets.

Does laptop Embedded Controller have limited writes?

I am wondering if I should be worried about excessive writes to the embedded controller registers on my laptop. I am guessing that if they are true registers, they probably act more like RAM rather than flash memory so this isn't a problem.
However, I have a script to modify the registers in my laptop's EC to better control the fan speed curve. It has to be re-applied after each power change event such as sleep/wake as well as power cable events, so it happens fairly often. I just want to make sure I am not burning out my chips in the process.
The script I am using to write to the EC is located here:
https://github.com/RayfenWindspear/perl-acpi-fanspeed
Well, it seems you're writing to ACPI registers. Registers here do not refer to any specific hardware; it just means its a specific address that you can reach using a specific bus. It's however highly unlikely that something that you have to re-write after every power cycle is overwriting permanent storage, so for all practical aspects I'd assume that you can rely on this for as long as your laptop lives.
Hardware peripherals are almost universally implemented as SRAM cells. They will not wear out first. The fan you are controlling will have a limited number of start/stop cycles. So it is much more likely that the act of toggling these registers will wear something else out prematurely (than the SRAM type memory cell itself).
To your particular case, correctly driving a fan/motor can significantly improve it's life time. Over driving a fan/motor does not always make it go faster, but instead creates heat. The heat weakens the wiring and eventually the coils will short reducing drive and eventually wearing out. That said, the element being cooled can be damaged by excess heat so tuning things just to reduce sound may not make sense.
Background details
Generally, the element is called a Flip-Flop with various forms. SystemRDL is an example as well as SystemC and others where digital engineers will model these. In digital hardware, the flip-flops have default or reset values. This is fixed like ROM on each chip and is not normally re-programmable, uses EEPROM technologyNote1 or is often configured via input lines which the hardware designer can pull them high/low with a resistor or connect them to another elements 'GPIO'.
It is analogous to 'initdata'. Program values that aren't zero get copied from flash, disk, etc to memory at program startup. So the flip-flops normally do not hold state over a power cycle; something else does this.
The 'Flash' technology is based off of a floating gate and uses 'quantum tunnelling' to program the floating gates. This process is slightly destructive. It was invented by Fowler and Nordheim in 1967, but wide spread electronics industry did not start to produce them until the early 90s with NOR flash followed by NAND flash and many variants. But the underlying physics is the same; just the digital connections are different. So as well as this defect you are concerned about, the flash technology actually followed many hardware chips such as 68k, i386, etc. So 'flip-flops' were well established and typically the 'register' part of the logic is not that great of a typical chip and a flip-flop uses the same logic (gates) as the rest of the chip logic. Meaning that using flash would be an extra overhead with little benefit.
Some additional take-away is that the startup up and shutdown of chips is usually the most destructive time. Often poor hardware designers do not put proper voltage supervision and some lines maybe floating with the expectation that system programs will set them immediately. Reset events, ESD, over heating, etc will all be more harmful than just the act of writing a peripheral register.
Note 1: EEPROM typically has 100,000+ cycles. These features are typically only used once at manufacture time to set a chip configuration for the system. These are actually quite rare, but possible.
The MLC (multi-level) NAND flash in SSD has pathetically low cycles like 8,000 in some cases. The SLC (single level) old school flash have 10,000+ cycles, but people demand large data formats.

Is it possible to have CAN on Arduino without extra hardware?

I would like to have Arduino operating in a CAN network. Does the software that provides OSI model network layer exist for Arduino? I would imagine detecting the HI/LOW levels with GPIO/ADC and sending the signal to the network with DAC. It would be nice to have that without any extra hardware attached. I don't mind to have a terminating resistor required by the CAN network though.
By Arduino I mean any of them. My intention is to keep the development environmen.
If such a software does not exist, is there any technical obstacle for that, like limited flash size (again, I don't mean particular board with certain Atmega chip).
You can write a bit banging CAN driver, but it has many limitations.
First it's the timeing, it's hard to achieve the bit timing and also the arbitration.
You will be able to get 10kb or perhaps even 50kb but that consumes a huge amount of your cpu time.
And the code itself is a pain.
You have to calculate the CRC on the fly (easy) but to implement the collision detection and all the timing parameters is not easy.
Once, I done this for a company, but it was a realy bad idea.
Better buy a chip for 1 Euro and be happy.
There are several CAN Bus Shield boards available (e.g: this, and this), and that would be a far better solution. It is not just a matter of the controller chip, the bus interface, line drivers, and power all need to be considered. If you have the resources and skills you can of course create your own board or bread-board for less.
Even if you bit-bang it via GPIO you would need some hardware mods I believe to handle bus contention detection, and it would be very slow and may not interoperate well with "real" CAN controllers on the bus.
If your aim is to communicate between devices of your own design rather than off-the shelf CAN devices, then you don't need CAN for that, and something proprietary will suffice, and a UART will perform faster that a bit-banged CAN implementation.
I don't think, that such software exists. CAN bus is more complex, than for example I2C. Basically you would have to implement functionality of both CAN controller and CAN transceiver. See this thread for more details (in German).
Alternatively you could use one of the CAN shields. Another option were to use BeagleBone with suitable CAN cape.
Also take a look at AVR-CAN.

UART vs I2C vs SPI for inter-processor communication between microcontrollers

I am examining a way to connect two microcontrollers. On the level of serialization I am thinking of using Nano protobuffers (http://code.google.com/p/nanopb/). This way I can encode/decode messages and send them between two processors.
Basically, one small processor would be the RPC server, capable of doing several functions. Bigger processor will call there RPCs via messages sent, and then when data is ready, it will read it from smaller processor.
What would be the pros/cons of using UART, I2C or SPI?
Messages will be put in the mailbox que prior to sending.
It depends on your total requirements and how expensive are pins.
I2C only needs two pins, but it's slow and to handle it with or without interrupts is a pain, even with the build in peripheral modules.
It's a master/slave system, it's good for controlling many slow devices like temp sensors.
Only two lines for all bus devices, the selection is done via an I2C-Address in the protocol.
Uart needs two pins, it's normally faster, easier to handle, but requires (nearly) the same clocks at both sides.
One to one asynchronous system, can be good if both systems needs to be send sometimes data without waiting for a master poll request.
Can also be used as a bus system, but then you need a master/slave structure or more complex protocols.
SPI needs 3 (or 4 with CS) pins, it's the fastest, simple to implement even with DMA, low cpu time overhead, often buffered.
When you have enough free pins I would prefer it.
All of these interfaces have pros/cons.
UART connection in it's basic functionality requires 2 pins: RX and TX. The SW implementation of how to message over that UART is quite a bit more complicated...you'll have to develop your own messenging protocol between the devices and decide what is a good message and what is a bad message. It could get quite complicated because you pretty much have to define how to "communicate" over the physical link, what is an error, retries, etc. Unless you are implementing a serial port connection to a PC or some other external device, I think a UART is highly overkill for a IC to IC communication path. Master and slave are not specifically defined.
SPI is a master-slave relationship and can be a faster interface (I've seen up to 60MHz clock rates, not common) but it also requires more pins, 3 at a minimum for a point-to-point communication scheme but the number of pins increases to 3+n as the number of "slaves" increases above 1. There are no error indications via SPI. SPI is a "de-facto" standard...meaning it can vary in implementation...your mileage may vary depending on how a IC supplier defined "their" SPI implementation. I generally consider the lack of a true standard for SPI to be a "con".
I2C is also a two pin interface and is an actual "standard" developed by Phillips (now NXP.) As a standard, it is well-defined in how it operates, how errors are raised, and is simple to implement. It has an addressing scheme, can send commands, and can support 0 or more data frames in a transaction. CRC (optional) and higher data rates can be supported (up to 5Mbits.) It does have cons, namely bus capacitance can limit actual data rates (rise/fall time) but generally you can design around this "problem".
In their most basic forms, all of these busses are "ground referenced"...and can suffer from system induced noise. Obviously, lower rail voltages can make this even more of issue. Again careful design practice can mitigate many of the problems some people report to be the bain of their existence.
For the point-to-point system initially asked by the poster, if a master-slave arrangement is required, a SPI or I2C interface may be appropriate (data rate dependent.) If a master-master relationship is required, I2C or UART may be required.
For ease of implementation from a software point of view, I'd rank these communication methods in the following order:
I2C, if you need faster data rates than I2C can handle, then SPI
SPI, if you need multi-master, then I2C or UART
UART as a last resort...has a lot more software overhead to manage the communications channel
I would use UART or CAN or ETH or any protocol that is asynchronous.
If you use a synchronous protocol, the master must always "ask" the slave if it has data and generate unwanted traffic.