An UART interpreter – sneak peek

mainbrdIn a hot summer of a couple of years ago, trying to not thinking about the stifling heat of the afternoon, I put some efforts in a system which should drive a set of motors and peripherals by means of a single serial line. The idea consists in creating a sort of instruction set, sent over the serial, to transmit and receive informations, but the main effort was to develop this under a robust software, to make the system rensonsive and interrupt driven, fully aknowledged to keep trace of errors also.

This project is born following these ideas, on order of development:

  • Driving a low level peripheral using a console, with an affordable and error tolerant firmware
  • HW separated by SW, being able to design them finely and independently
  • Being able to drive the HW on any type of PCs
  • Expliting any software that can handle strings, the only specification is to know the language of the console
  • As a natural consequence, a PC connected on the Internet can drive the HW remotely

The main idea

In order to do this, I thought to a concept made of a two stages of control: the microcontroller receive commands from the user and put them in action. But the user of the microcontroller could be another board or PC, not necessarily a human generated commands. This, as previoulsy said, can be made through a console.

In this way the microcontroller carries an “interpreter” which translate commands to the hardware. By this mechanism I split a single action in a confined memory and execution time, affordable and in a responsive way. Due to this software “modularity” it is possible to extend indefinitely the instructions that the micro can interpret and use all of its calculus power to control precisely the hardware desired or manage the instructions in a robust way. The MCU is then only a front-end of the system which receive and sent signals from/to external world. By using a coherent language, the device can communicate with other peripherals (like a PC) by using the serial, and being driven by them directly.

The abstraction layer

The user only see a console over the serial, which work so vaguely similar to the Python line interpreter. But commands are simple, being able to be generated by a software running on another machine which send them to the console. And are simple because this project is at a very early stage. 🙂

Here the user of the console can implement all the algorithms, writing them down to the MCU generated command prompt. With this machanism we already have an abstraction to blink an LED over the Internet, or driving a robotic arm, nothing change inside the MCU. The abstraction give the possibility to personalize the behavior of the device and save in a text file on the PC without the need of reprogramming the chip. Also, but this is not structured yet, can be possible to save this content on an EEPROM or whatever memory support can be reached by the microcontroller, when the console is not directly accessible.

So, anyone can control the device directly or through a PC algorithm. The power of the idea is that if I want to drive a robotic arm, I have sufficient abstraction to drive it directly from another location, making this MCU implementation very suitable for remote control and environment analisys.

At this stage of the project, the software running on an internet connected device is written in the multi-platform Python language, due to its versatility. It reads the console and write commands to it. But here the console is just an echo taken from the microcontroller, elaborated by the Python based SW and printed on the screen. What is important, the user can not know anything of the hardware of the MCU, being free to think to the optimum driving algorithm.

Are also implemented 2 buttons where each control a device bypassing the physical serial console. But due to the modularity of the firmware, when a button is pressed, it is not activated a signal inside the MCU, but there is an auto-generated internal command sent back to the console, by parameter passing without using the USART module. By means of this mechanism, all controls are the same, the code remains modular and there are no performance losses.

A pretty stupid image is shown here, just to make the idea. The light green is what is done inside the MCU, while the light orange shows the basic algorithm of the PC. Between these two colors, there is an USART wrapper, but can be implemented on other technologies, like SPI, I2C, whatever isola supported on the MCU side.

prj

I almost forget an analogy: we can think about a client-server structure. Here, the server is the MCU while the client the Phython based PC software. I like thinking to the old fashioned gerarchy of the computer terminals, a dumb terminal that send commands on a mainframe. But here the terminal is not so dumb compared to those in 1960.

Some specifications

I almost forget to talk about the core. Its based on a 8-bit PIC18F47J53 microcontroller, which can handle  very efficiently two levels of interrupts priority. Here I can give more priority to the USART commands instead of those on board, or viceversa, depending on what I desire. For example, when I press a button and I want to be interrupted by the serial, I can put the serial receiving interrupt up in priority. The project was previously born on an Atmega328P by using Avrdude and AVR Studio 6, but then ported on this PIC using XC8 and MPLAB-X, due to better hardware specifications.

Moreover, and I will talk about that on next article, on the MCU board there are two buttons and here are configured to work efficiently like a joystick. The ADC samples a value of voltage on a potentiometer and can set the intensity of the command.

The software on PC is Python based and uses the Pyserial library.

epic

And now?

Now as soon as I can find some time to put something on more than a breadboard and when the Python based terminal is presentable (keep in mind what “presentable” means for an electronic student…), I will put something more that a bare useless presentation. I will also put the sources and I will explain better what is going on, trying to be helpful to who want to play with this stuff.

On the next article, I’ll try to explain how to control a motor by using an opposite phase PWM modulation, allowing the analog control of a motor. This can be done also without an MCU, by using only one 555. I’ll see what implementation I will adopt.

Nevertheless, this opposite phase PWM method can be integrated very well with this UART intepreter project: one can drive the motor manually and then an algorithm can decide if that speed must be kept, and so take the control over the device. Yes, I will decisely talk about that in the first release of this project. I will play with the 555 another time…
But I’m afraid that I’ll not find so much time to setup a proper sensor and data acquisition. So, I need to organize myself on order to find time, and this is not a good news.

Il tempo si paga in energia

723px-Neutrino_bubble_chamber_decay_overlay

Una frase del genere odora di Einstein. Ma lui rapportava la massa all’energia… ah, no, c’era di mezzo anche il tempo, con qualche giro matematico.
Passeggiando in giro, andando in bicicletta, muovendosi in acqua. Ci rendiamo tutti conto che quando le cose vengon fatte con calma paiono meno faticose. Basti pensare alla stanchezza dopo una lunga scalinata, fatta di corsa. E sì, uno può essere stanco anche dopo averla fatta lentamente, ma di certo è un qualcosa di più sopportabile. Questo nonostante l’energia fornita totale per salire gli scalini sia esattamente la stessa. E accettando l’ovvietà di questa conclusione con un po’ di umiltà, la mente si sposta di un passo avanti.

Ecco infatti che, come qualsiasi esperto può affermare, il nostro corpo – ma probabilmente tutte le forme di vita – può dare una certa quantità di energia in un lasso di tempo definito che è sempre inferiore alla potenziale quantità di energia che realmente possiede (riserve di grasso, ATP e tutto quel che ora si conosce a riguardo). Ed ecco che alla corsa verso la cima della scalinata, salvo essere allenati, le forze “mancano”. L’allenamento altro non è infatti che aumentare l’eneriga utilizzabile nello stesso lasso di tempo, o trovare l’equilibrio tra l’energia che si consuma e quella che si può fornire per migliorare la resistenza, sia che si parli di allenamento in palestra o allenamento mentale, nello studio. E quindi mi dico: ma solo io essere vivente? O anche ciò che mi circonda funziona così?

Allora penso alle forme inorganiche, come una goccia d’acqua che corrode una pietra. Dopo molto tempo, si osserverà lo stesso danno che avrebbe fatto un proiettile sparato sulla pietra, ma sarebbe avvenuto in una frazione di secondo. Il meccanismo di scambio di energia è completamente diverso dal corpo umano, ma in qualche modo c’è una filosofia di base che unisce cose e animali.

Poi però mentre scrivo, mi viene in mente che qualcuno, da poco usciti dal Medioevo, agli albori della matematica, ha tradotto questa “filosofia di base”. Si è arrivati ad una forma di equazione differenziale, perfettamente nota a chi ha studiato un minimo di fisica, la Potenza:

bfbd26cca59bdfa4546d8359b12c9760

Dove L è il lavoro, ovvero la quantità di energia spostata e t è il tempo.

Una cosa interessante è come tutte queste formule fanno fede ad un metodo inventato dalle persone (la Matematica), capace di prendere un fenomento e quantificarlo permettendo di gestirlo, in un linguaggio che non conosce nazioni. Ma se si riesce a concepire come innovativa una cosa così vecchia, allora scatta l’ultimo pensiero di questo articolo di dubbia utilità: le formule descrivono come le cose accadono, ma non il perché. O meglio, con esoterismi tipo fisica quantistica e compagnia bella, i perché di molte formule vengono svelati. Anzi, solo spostati un po’ più in la.

Dalla fatica che si può provare nel fare le cose in fretta, pare proprio che il tempo guadagnato (dipende…) si paghi in energia. Moneta di scambio per tutti gli esseri viventi che cercano solo un po’ di tempo in più. Se non esisti non hai energia, sei uno con cui alla banca del tempo non vogliono avere a che fare e resti lì, immemore e senza tempo.

Ma di questo ne parlerò un’altra volta, tempo e voglia permettendo. Volevo dire, energia da spostare permettendo.

The anti-loud siren

2a

What happens if some one try to piss off people and make them scream, and you can’t calm down them?
What happens if you are in a crowded environment where people start talking when they shouldn’t?
Or what happens if you are one of those people who talk constantly loud out, but wants to improve they ability to talk “normal”?
Or if your boss always scream at you?
WHAT if there is a solution to this?

Ok, after this junk styled presentation, I want to show a little project born and made in a week-end. So very stupid, but also nice, imho. It’s based on make some loud when there is too noise around and I decided to build it ‘cause sometimes people talks loudly and they didn’t notice that. Presented as a little joke for them, here is shown the anti-figher siren.

CONCEPT AND SCHEMATICS

Here we are talking about a simple analog circuit which receive a signal from a microphone, bias and amplifying it, then put into a common emitter BJT which square it up to be read from a microcontroller – here an Atmega328 MCU, Arduino Duemilanove board.
I started by thinking about what is already available at home. And I realized that I can finally use that lonely LM358 (dual op-amp), then an BC337 was also available and a mic was re-born from.. I don’t remember, it was simply there, but with no mark helping to understand its capabilities.
That being said, after few suggestion of order of amplification of the preamplifier, I came up with a solution which magnifiying the signal up to 2550 times approximately, reduced accordingly by the potentiometer. This includes the second amplifier which amplifies of 12 times and drive the bjt, common emitter to work in saturation. The biasing of the final signal allow the BJT to act as a switch “normally closed”: in this way the signal which allow the MCU pin change is related to the “negative” wave of sound signal, and the digital value is not inverted.

Here the schematic, in Eagle:

mic

Now, since this project was started in Friday morning, and I was pretending to finishing it by the weekend, the fastest and rough thing to do was to use Arduino and sketching a program that uses interrupt on the pin from the microphone and “tone-out” an alarm of 1 second on a buzzer. Actually, the alarm sounds like a siren, and to be honest I find it as cool as stupid.

Here the sketch:

 // Definition of interrupt names
#include < avr/io.h >
// ISR interrupt service routine
#include < avr/interrupt.h >

static uint8_t buzz = 0;
uint16_t i = 0;

ISR(PCINT2_vect) {
  buzz = 1;
}


void setup() {

  pinMode(4, INPUT);
  pinMode(5, OUTPUT);
  EIMSK = 0;
  PCICR = 0b00000100;
  PCMSK2 = 0b00010000; // pin4 digital arduino

  sei();
}

void loop() {

  if (buzz){
    for (i = 2000; i<3000; i=i+10){
       tone(5, i);
       delay(2);
       }
    noTone(5);
    for (i = 3000; i>2000; i=i-10){
       tone(5, i);
       delay(2);
    }
    noTone(5);
    buzz=0;
  }
}

FINAL WORK

The breadboarded version looks like this:

 bread

But the final work, if we can call it this way, is made on a prototyping board and overlapped to Arduino. Then fixed with some tape, can be hooked to an arm, like we can do with our smartphones when jogging, or can simply be put smewehere on the desk. This ugly superimposition of boards (and also glued with tape, but not applied when taking these pics), shows my main skill hadicap: enclosures. 🙂

Ah, components are not too close to board to allow me to eventually reuse them in the future, inside a breadboard. I know, I could avoid it, but it’s a trick in case of more expensive components which are mounted on temporary circuits without any socket – this is not the case, though.

 1

DSCN3693[1]

The perfect final of every project – no matter what how stupid it is, is to build a final prototype all in a single board or in a system which is made for this purpose and nothing more (if it is not desired in the project, obviously). So, if an MCU is used, a proper smaller one should be used. Or in this case, one can have some more fun by building a detector and siren generation circuits without the use of a microcontroller, and put everything toghether, obtaining a nicer gadget… To keep people silent!