Posts | Comments

Planet Arduino

Archive for the ‘AVR’ Category

Jun
02

Optimizing AVR LCD Libraries

arduino hacks, AVR, C, LCD, Microcontroller, microcontrollers, SPI, TFT, TFT Display Comments Off on Optimizing AVR LCD Libraries 

A while ago, [Paul Stoffregen], the creator of the Teensy family of microcontrollers dug into the most popular Arduino library for driving TFT LCDs. The Teensy isn’t an Arduino – it’s much faster – but [Paul]’s library does everything more efficiently.

Even when using a standard Arduino, there are still speed and efficiency gains to be made when driving a TFT. [Xark] recently released his re-mix of the Adafruit GFX library and LCD drivers. It’s several times faster than the Adafruit library, so just in case you haven’t moved on the Teensy platform yet, this is the way to use one of these repurposed cell phone displays.

After reading about [Paul]’s experience with improving the TFT library for the Teensy, [Xark] grabbed an Arduino, an LCD, and an Open Workbench Logic Sniffer to see where the inefficiencies in the Adafruit library were. These displays are driven via SPI, where the clock signal goes low for every byte shifted out over the data line. With the Adafruit library, there was a lot of wasted time in between each clock signal, and with the right code the performance could be improved dramatically.

The writeup on how [Xark] improved the code for these displays is fantastic, and the results are impressive; he can fill a screen with pixels at about 13FPS, making games that don’t redraw too much of the screen at any one time a real possibility.


Filed under: Arduino Hacks, Microcontrollers
May
28

Mimimalist Arduino Gaming Platform

arduino, arduino hacks, AVR, game, LCD, tetris Comments Off on Mimimalist Arduino Gaming Platform 

A pretty color LCD screen, an Arduino, a buzzer and a joystick is all you need for a minimalist gaming console for under $20. At least, that’s all [João Vilaça] needed to get this sweet version of Tetris up and running. (He’s working on Breakout right now.)

It’s a testament to the current state of the hardware hacking scene that [João] could put this device together in an afternoon for so cheap, presumably after waiting a while for shipments from China. The 320×240 SPI color TFT LCD screen used to cost twice as much as this whole project did. And wiring it up is a simple matter of connecting this pin to that pin. Almost child’s play.

Equally impressive is the state of open source software. A TFT library from Seeed Studios makes the screen interface a piece of cake. [João] wrote his own sound and joystick code, and of course the Tetris gameplay itself, but it’d be much more than a few weeks’ work without standing on the shoulders of giants. Check out [João]’s Github for the project code and stick with us after the break for a demo video and some of our other favorite Arduino gaming hacks.

 

Now, we’ve seen a whole lot of Arduino-based gaming platforms around here before, and they range from the simplistic black-and-white to the bells-and-whistles of the Gameduino which tacks an FPGA onto your Arduino to enable sprites, awesome sound, and VGA output. But we’ve also got a place in our hearts for simplicity and comprehensibility, and [João]’s device and code has got those in spades.

If you’re ready to push your Arduino skills beyond blinking LEDs, [João]’s game project should be on your reading / building list. We can’t wait to see Breakout.


Filed under: Arduino Hacks
May
13

Arduino IDE Becomes More Open, Less Snarky

arduino, arduino hacks, AVR, board manager, ESP8266, IDE Comments Off on Arduino IDE Becomes More Open, Less Snarky 

Version 1.6.4 of the Arduino IDE has been out for a little while now, and it has a couple of notable changes. To our eyes, the most interesting change makes adding support for non-standard boards and their configurations within the Arduino IDE a lot simpler. We’ll get into details below.

unnamedBut before that, it’s time to bid farewell to the cheeky little popup window that would deliver a warning message when using a board bearing the USB IDs of their former-partner-turned-competitor. We absolutely agree with [Massimo] that the issues between Arduino SRL / Smart Projects and Arduino LLC are well-enough known in the community, and that it’s time for the popup to fade away.

Now on to the meat of this post. The new “Board Manager” functionality makes it significantly easier for other non-Arduino products to be programmed within the Arduino IDE. Adafruit has a tutorial on using the Board Manager functionality with their products, and it basically boils down to “enter the right URL, click on the boards you want, download, restart Arduino, bam!”

The list of unofficially supported third-party boards is still a bit short, but it includes some stellar entries. For instance, Adafruit has provided the files needed for the ESP8266, which recently received the Arduino treatment. This means that you can simply point your IDE at Adafruit’s URL, and it’ll set you up with everything needed to develop for the ESP8266 from within the comfy Arduino IDE.

Another standout, from our perspective, is this link that simplifies programming bare AVR chips from the Arduino IDE. While programming your Arduino code into a simple AVR ATmega168 has always been possible, it’s never been as easy as it is now.

How it Works

Under the hood, the new board manager system is pretty straightforward. Clicking on one of the links leads to a JSON file with any number of board architecture definitions. Each entry provides text descriptions of the target board that are used for generating menu entries in the Arduino IDE’s pulldown menus, and a link to a zip file. This zip file contains everything necessary to adapt the Arduino libraries to the target board or chip.

For instance, with something simple like the bare-AVR modifications, the zip file simply includes the boards.txt and platform.txt files that the Arduino IDE uses to fill in a lot of board-specific parameters like the CPU clock speed, fuse bit settings, and AVRDUDE command options for flashing new code. For something more involved, like porting Arduino to the ESP8266, the zip file additionally includes the ported Arduino core and library functions, as well as the uploader tools that make Arduino work on that target.

It’s a very interesting experiment to open up the Arduino IDE so transparently to third-party devices. It’ll surely win points with both hackers and retailers of *duinos, and we’re guessing it’ll only encourage porting the Arduino libraries to more platforms. Let’s see where the community takes this one. What do you want to see Arduino ported to next?


Filed under: Arduino Hacks
Apr
27

Slick Six-Voice Synth for AVRs

arduino, arduino hacks, AVR, musical hacks, wavetable synthesis Comments Off on Slick Six-Voice Synth for AVRs 

He started off making an AVR synthesized guitar, but [Erix] ended up with much more: a complete six-voice AVR wavetable synthesis song machine that’ll run on an ATMega328 — for instance, on an Arduino Uno.

If you’re an AVR coder, or interested in direct-digital synthesis or PWM audio output, you should have a look at his code (zip file). If you’d just like to use the chip to make some tunes, have a gander at the video below the break.

It’s pretty sweet to get six channels of 31.25 kHz sampled 8-bit audio running on a 16MHz chip. The code underlying it works through some tricky optimization in the sample update routine (UpdateVoiceSample() in play.c if you’re reading along) and by carefully prioritizing the time critical elements.

For instance, the pitch is updated once every two PWM samples, I/O and other auxiliary player tasks every eights samples, and the sound’s dynamic volume envelope is only recalculated every 48 samples. Doing the slow math as infrequently as possible lets [Erix] make his timing.

And to round out the tools, [Erix] also provides wavetable editors and song generators in Lua to compile the tables of music data that the AVR routines need to run.

If you’re not impressed by this bit of AVR C coding, then you’ve not tried to implement something similar yourself.


Filed under: Arduino Hacks, musical hacks
Apr
08

DAN64 – an AVR based 8-bit microcomputer

arduino, AVR, computer Comments Off on DAN64 – an AVR based 8-bit microcomputer 

tv-out

by Juan J. Martínez:

This is my first serious attempt to learn electronics. DAN64 is my first project and it has been a discovery process during 3 months of my free time. I had to learn a lot of things I didn’t know much about, from basic electronics to the details of the AVRs -and specifically the ATmega328-, and a whole world of things in between such as signalling, protocols, interfaces, modulation and demodulation, SDKs, EDA software, prototyping, PCB fabrication, etc.

I’m certain that in this project I’m doing many stupid things and I’m sure my approach to solving some of the problems is not the best, but in my discharge I can only say: it works! (to some extent at least).

I got lots of gotcha! moments, ups and downs where I though I couldn’t finish the project because perhaps what I was trying to achieve was just impossible.

So this is not about perfection but about good enough for me and about the learning process and having fun.

DAN64 – an AVR based 8-bit microcomputer - [Link]

Feb
06

Piconomic FW Library 0.4.2 released

ADC, arduino, arduino uno, ATmega328P, atmel, AVR, GPIO, i2c, Piconomic, SPI Comments Off on Piconomic FW Library 0.4.2 released 

tera_term_cli

by Pieter @ piconomic.co.za:

If you can beg, steal or borrow an Atmel ISP programmer, then you can use the Arduino environment to develop on the Atmel AVR Atmega328P Scorpion Board. An Arduino on Scorpion Board guide, Optiboot bootloader and example sketches have been added.

If you own an Arduino Uno board, you can now try out the Piconomic FW Library risk free without abandoning the creature comforts of the Arduino environment. You can use the existing Optiboot bootloader to upload code. I have added a getting started guide for the Arduino Uno. There are examples, including a CLI (Command Line Interpreter) Application that creates a “Linux Shell”-like environment running on the Arduino Uno so that you can experiment with GPIO, ADC, I2C and SPI using only Terminal software (for example Tera Term)… it is really cool!

Piconomic FW Library 0.4.2 released - [Link]

Nov
21

Phoenard: World’s 1st Arduino-compatible Prototyping Gadget

arduino, ATMEGA2560, AVR, kickstarter, prototype Comments Off on Phoenard: World’s 1st Arduino-compatible Prototyping Gadget 

a938ea6cb4b3475cce88c4306bdce57a_large

The ultimate combination of an Arduino-compatible board and your day-to-day Gadget in one handheld Device.

Phoenard is an All-in-one Arduino-compatible prototyping Gadget powered by an 8-bit AVR ATMEGA2560, identical to the one you find in Arduino Mega. It is essentially a pocket-sized prototyping platform which you can use as the ‘brain’ in your projects, similar to using an Arduino. BUT, it has a lot more features built into a single case developed in such a way that you can use it as your day-to-day Gadget.

Phoenard: World’s 1st Arduino-compatible Prototyping Gadget - [Link]

Nov
07

Arduino Wifi With Hi Flying HF-LPT100

arduino, AVR, HF-LPT100, internet, wifi, WIFI232-T Comments Off on Arduino Wifi With Hi Flying HF-LPT100 

HF-LPT100_or_USR-WIFI232-T_connected_to_arduino_sm

by 2xod.com:

The Arduino’s greatest weakness is also it’s greatest triumph. That is, it is only a low power simple processor, which makes internet connectivity for such a simple device difficult. Often the network interface has a few orders of magnitude greater performance than the arduino atmel avr processor itself.

Arduino Yun is the answer to wifi connectivity for arduino. Ushering in a new era known as the internet of things, Yun is actually a complete 400mhz system on chip. There is irony in the fact that the powerful system on chip’s only duty is to serve the lowly AVR. Akin to “You Pass Butter”

Arduino Wifi With Hi Flying HF-LPT100 - [Link]

Sep
29

Microduino-Joypad: an open source 8-bit game console & more!

arduino, AVR, Joypad, Microduino, MSP430, STM32 Comments Off on Microduino-Joypad: an open source 8-bit game console & more! 

94174be2ccad26a7f0caaff399007b25_large

Microduino-Joypad is … an 8-bit game console + open source + UPin27 + AVR,STM32,MSP430,51 compatible + smart controller == Awesome!  by Microduino Studio:

Microduino studio launched the first kickstarter in September 2013, introducing the brand new Arduino-compatible development board—Microduino. We achieved success with the unique Upin27 interface, compact size, rich expansion boards as well as many applications. Over the past year, Microduino community has been growing rapidly. Now we have nearly 10,000 players worldwide.

At the 25th anniversary of the Gameboy console, we are now releasing Joypad – 8-bit multi-functional game console to show our respects to Gameboy–the most classic game console in the history.

With this elegantly designed little Joypad, we are hoping to bring you the greatest joy from your childhood memory. The best thing is it’s completely open source and you can even create and develop your own game to inspire your imagination. Moreover, it’s not only a game console, it’s also a remote controller for other devices, such as Quadcopter, robot and cell phone, etc.

Microduino-Joypad: an open source 8-bit game console & more! - [Link]

Étant donné que je n’ai pas encore tout le matériel nécessaire pour avancer mes autres projets, j’en profite pour approfondir un peu mes connaissances théoriques et vous en fait donc profiter. Mon projet ici est simple : Réguler une température à l’aide d’un microcontrolleur, mais surtout bien comprendre les tenants et aboutissements des différents réglages et algorithmes. L’objectif ici n’est pas tant d’expliquer ce qu’est un PID, ni comment il fonctionne dans le detail, mais plutôt de donner une méthode permettant d’approximer les coefficients du régulateur.

Je profiterais de cette expérience pour faire 2 articles :
– celui-ci concernant le PID a proprement parler
– Un second article concernant ma méthode pour obtenir des courbes « lives » a partir d’un arduino et d’un PC.

Qu’es-ce qu’un PID

Pour simplifier, on parlera dans la suite de régulation de température, vu que ce sera notre application ici. Mais bien entendu, une régulation peut se faire sur tout type de process (vitesse, débit, etc…)

Lorsqu’on veut réguler la température (d’une pièce par exemple), l’idée la plus simple qui nous vient à l’esprit est de faire une régulation tout-ou-rien : on est en dessous d’un premier seuil, on allume la chauffe, on passe au dessus d’un second seuil on coupe la chauffe. Cette façon de procéder, bien que très simple à implémenter n’est pas exempte de défauts. Par exemple, la température ne sera jamais vraiment constante, même si elle l’est « en moyenne ». Selon le process, on peut arriver à fortement dépasser les consignes (dans un sens ou dans l’autre), en fonction de l’inertie du système, ce qui peut s’avérer nuisible selon ce qu’on veut faire. Enfin, la puissance du chauffage oscillera entre 0 et 100%, ce qui engendre une surconsommation non négligeable.

La régulation PID permet de coller « au plus juste » à la consigne, en évitant les dépassement (en fonction du réglage comme on le verra plus loin), et en n’utilisant que la puissance nécessaire à aller à la consigne et à la maintenir. Concrètement, dans PID, on a P pour Proportionnelle, D pour Dérivée, et I pour Intégrale. Si comme moi vous avez tendance à être un peu allergique aux maths, vous commencez déjà à vous sauver, mais en fait c’est moins compliqué que ça n’en a l’air.

Proportionnelle : c’est ni plus ni moins que la différence entre votre consigne et la valeur actuelle, multiplié par un coefficient de proportionnalité (Que vous définissez, cf la suite). Dans la suite, nous l’écrirons Kc.e(t)

Intégrale : A chaque mesure, vous allez avoir une différence avec la consigne (en plus ou en moins). Prenez cette erreur à chaque pas de temps, multipliez la par un (autre) coefficient de proportionnalité, et additionnez le résultat de tous les pas de temps depuis le début, et vous avez la fameuse composante Intégrale. Dans la suite, l’intégrale sera notée de la façon suivante :

I

 

Dérivée : Son rôle est de « freiner » l’augmentation de puissance calculée en fonction de P et de I, de manière à ne pas dépasser la consigne. C’est une façon de prendre en compte la vitesse d’évolution de notre process. Pour le calculer, vous faites erreur actuelle – erreur précédente, multiplié par un troisième coefficient de proportionnalité

La formule globale de notre régulateur PID peut donc s’écrire de la manière suivante (plus d’explications plus bas):

Formule PID, source ControlGuru

Formule PID, source ControlGuru

 

Description du materiel

Le montage utilisé pour ces essais est très simple : un arduino, un bouton 2 positions, 1 capteur de température (DS18B20), un mosfet (IRF540), une résistance 10Ω 5W, et une alimentation 12V. Le mosfet est piloté par une sortie PWM de l’arduino, et gère le courant (puissance) transitant dans la résistance. Cette dernière chauffe donc plus ou moins en fonction du ratio PWM (la tension change) envoyé par l’arduino. Le bouton 2 positions sert à passer d’une première consigne (valeur PWM 5 sur 255) à une seconde (valeur PWM 30 sur 255) Un petit programme python enregistre les valeurs dans un fichier texte sur le pc (via connection série), et j’utilise GnuPlot pour avoir une jolie courbe et pouvoir lire les valeurs des graphiques plus facilement que directement sur l’image. Par la suite, j’ai ameliore mon script python, de maniere a pouvoir saisir une consigne via le port serie, tout en continuant de logguer.

Montage régulation de température

Montage régulation de température. Attention, utiliser une résistance 5W mini !

Méthode de réglage

Je vous présente une méthode « graphique » directement tirée du site Control Guru, appliquée à mon montage de test. Ce site étant en anglais et très dense en informations, j’ai essayé de résumer les points essentiels ici. J’invite ceux qui voudraient approfondir le sujet à consulter ce site qui est une véritable mine d’information sur la régulation.

Définitions

  • PV : Process Variable, cela correspond à la grandeur mesurée que l’on veut influencer (la température dans cet exemple)
  • CO : Controller Output , la sortie de notre contrôleur en %. (Correspond à l’ouverture de la vanne par exemple)
  • Kp : Gain du process
  • Kc : Gain du contrôleur

Introduction

Une fois modélisé notre boucle de contrôle, nous allons pouvoir en déterminer les trois paramètres principaux par expérimentation, mesure et calcul (et oui…)

Les paramètres à déterminer sont :

  • Kp : la Gain du process, ou, dit autrement, le sens et la grandeur de la variation de la sortie
  • Tp : Constante de temps du process, ou la vitesse de variation quand le process a commencé à répondre
  • θp : (Prononcer Thêta P) Temps mort du process, ou le délai écoulé avant que le process commence à réagir
Boucle de contrôle

Boucle de contrôle

Afin de pouvoir déterminer nos trois paramètres, il va nous falloir mesurer la façon dont réagis notre système. La première étape consiste donc à fixer une première valeur de sortie à notre contrôleur (CO) et attendre que la variable de sortie (PV, ici la température) soit bien stabilisée.

Une fois cette dernière stable, nous allons modifier la valeur de sortie du contrôleur (CO), et mesurer le changement obtenu sur la variable de sortie (PV). On logue bien sûr tout ça dans un fichier, avec les pas de temps, de manière à pouvoir également déterminer le temps mort du process (θp) et la vitesse de variation (Tp).

On se sert ensuite de ces mesures pour tracer un joli graphique, qui nous servira à déterminer nos différentes valeurs.

La formule permettant de déterminer notre premier paramètre Kc, qui est à la base du calcul de nos 3 paramètres (cf. formule) est la suivante :

source : controlguru

source : controlguru

pour déterminer Kc, nous devons donc commencer par déterminer différentes variables intermédiaires.

Calcul de Kp

Kp décrit le sens et de combien va évoluer PV, en fonction d’un changement de consigne (CO) Le cacul de Kp est assez simple : Kp=ΔPV/ΔCO ou en d’autre termes Kp = (différence en PV initial et PV final)/(différence entre consigne initiale et finale)

Sur mon prototype, j’ai modifié la consigne initiale (1,96%) pour une nouvelle consigne à 11.76%, voici la courbe obtenue:

Graphique test du système.

Graphique test du système.

En appliquant la formule ci-dessus, on a donc Kp = (79-40)/(11,76-1,96) = 39/9.8 = 3.98°C/%

Détermination de la constante de temps Tp

Tp représente le « en combien de temps » le système va réagir. En partant du même graphique, on va déterminer quand l’état de sortie vaut 63% de δPV, à partir du moment où le système à déjà commencé à réagir (et pas à partir du moment où on a modifié la consigne. Pour ceux qui se demandent d’où sort les 63%, vous trouverez toutes les explications (attention, maths !) dans ce pdf Fichier:Derive63rule.pdf On regarde donc le nombre de secondes écoulées lorsqu’on arrive à 63% de δPV (ici 39*0.63 + 40 = 64.6°C), et le nombre de secondes écoulées au moment où le système commence à réagir (très rapide ici)

Détermination de la constante de temps TP

Détermination de la constante de temps Tp

On obtiens donc Tp = 172 secondes.

Le cas de θp

θp représente le temps mort avant réaction. Dans une boucle de contrôle, il n’est jamais très bon d’avoir du temps mort, et il sera nécessaire d’avoir cette valeur la plus faible possible. Du fait de mon montage de test, le temps mort est ici très réduit. Ceci s’explique facilement par la position du capteur (sur la résistance), et par le faible volume à chauffer (uniquement la résistance. De manière assez intuitive, on imagine très bien que plus le volume à chauffer sera important, plus le temps mort sera long, pour une même puissance de chauffe.

Si on reprend le graphique ci-dessus, on vois que la consigne a été modifié à T1=195s, et j’ai décider de compter le début de la réaction à T2=198s. On a donc θp = T2 – T1 = 198 – 195 = 3s.

Il est intéressant de noter ici que mon échantillonnage étant d’une seconde, la valeur de θp peut être sensiblement erronée, du fait de sa faible durée dans ce cas.

Application à un modèle PID

Formule PID, source ControlGuru

Formule PID, source ControlGuru

Avec:

  • CO = Sortie du contrôleur (Controller Output)
  • CObias = biais du contrôleur, ou valeur nulle.
  • e(T) = Erreur actuelle, définie par SP – PV
  • SP = consigne (Set Point)
  • PV = valeur actuelle du process (Process Value)
  • Kc = Gain du controlleur, un paramètre de réglage
  • Ti = reset time, un paramètre de réglage
  • Td = derivative time, un paramètre de réglage

Calcul du gain et du reset time

Il faut tout d’abord se demander si notre process accepte un dépassement de consigne ou pas, ainsi que la vitesse à laquelle ce process doit réagir.

  • Si on accepte un dépassement, on peut choisir un réglage agressif, et donc un faible temps de réponse (petit Tc). Dans ce cas, Tc est le plus grand de 0.1Tp ou 0.8θp
  • Modéré, le contrôleur produira peu ou pas de dépassement. Dans ce cas, Tc est le plus grand de 1.Tp ou 8.θP
  • Conservateur, le contrôleur ne produira pas de dépassement, mais ira doucement, Tc sera le plus grand de 10.Tp ou 80.θP

Une fois décidé du comportement de notre contrôleur, et calculé Tc, on peut calculer le gain du contrôleur et le reset time grâce à la formule suivante :

source : controlguru

source : controlguru

Pour mon application, je vais choisir un comportement modéré. Tc sera donc la plus grande valeur de 1.Tp ou 8.θP (1×172 ou 8*3=24). On retiendra donc Tc = 172.

J’obtiens donc Kc = (1/3.98)*(172/(3+172)) = 0.25%/°C et Ti = 172

Je peux maintenant calculer mes deux principaux paramètres P et I :
P = Kc = 0.25
I=Kc/Ti. = 0.25/172 = 0.00145
Reste à déterminer D. la formule permettant de déterminer D est Kc.Td, avec Td = (Tp.θP)/(2Tp+θP) = (172*3)/(344+3) = 1.487. D vaut donc 0.25*1.487=0.372
D = 0.372

Mise en application

Reste maintenant à confronter les calculs à la réalité. Voici le code Arduino que j’ai utilisé pour effectuer mes tests :

#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);
DeviceAddress insideThermometer;

unsigned long lastTime;
double Input, Output, Setpoint;
double ITerm, lastInput;
double kp, ki, kd;
int sampleTime = 1000; //1 sec
double outMin, outMax;
String cmd = String("");
double tfirst = 0;

float printTemperature(DeviceAddress deviceAddress)
{
  sensors.getAddress(insideThermometer, 0);
  float tempC = sensors.getTempC(deviceAddress);
  Serial.print(tempC);
  Serial.print(" ");
  Serial.print(Output);
  Serial.print(" ");
  Serial.println(Setpoint);
  return(tempC);
}

void compute()
{
  unsigned long now = millis();
  int timeChange = (now-lastTime);
  if(timeChange>=sampleTime)
    {
      //get the new input value
      Input = getInput();
      //compute all working error variables
      double error = Setpoint - Input;
      ITerm+=(ki * error);
      if(ITerm>outMax) ITerm = outMax;
      else if(ITerm < outMin) ITerm = outMin;
      double dInput = (Input - lastInput);
      
      //compute PID output
      Output = kp * error + ITerm - kd * dInput;
      if(Output > outMax) Output = outMax;
      else if(Output < outMin) Output = outMin;
      
      //remember some variables for next round
      lastInput = Input;
      lastTime = now;
    }
}

void setTunings(double Kp, double Ki, double Kd)
{
  double sampleTimeInSec = ((double)sampleTime)/1000;
  kp = Kp;
  ki = Ki * sampleTimeInSec;
  kd = Kd / sampleTimeInSec;
}

void setSampleTime(int NewSampleTime)
{
  if (NewSampleTime>0)
  {
    double ratio = (double)NewSampleTime / (double)sampleTime;
    
    ki *= ratio;
    kd /= ratio;
    sampleTime = (unsigned long)NewSampleTime;
  }
}

void setOutputLimits(double Min, double Max)
{
  if(Min > Max) return;
  outMin = Min;
  outMax = Max;
  
  if(Output > outMax) Output = outMax;
  else if (Output < outMin) Output = outMin;
  
  if(ITerm>outMax) ITerm = outMax;
  else if(ITerm<outMin) ITerm = outMin;
}

double getInput(void)
{
  sensors.setResolution(insideThermometer, 9);
  sensors.requestTemperatures(); // Send the command to get temperatures
  return printTemperature(insideThermometer);
}

void setup()
{
  Serial.begin(9600);
  pinMode(3, OUTPUT);
  Setpoint = 0; //on fixe 0 de consigne
  double P, I, D;
  P = 0.25;
  I = 0.00145;
  D = 0.372;
  int STime = 1000;
  setTunings(P,I,D);
  setSampleTime(STime);
  setOutputLimits(0, 255);
}

void loop(){
compute();
analogWrite(3,Output);
if (Serial.available() > 0) {
      char SerialInByte;
      SerialInByte = Serial.read();
      
      if(SerialInByte==13){
        Setpoint = cmd.toInt();
        cmd = String("");
      }
      else
      {
        cmd += String(SerialInByte);
      }
  }
}

et voici le résultat :

Test des paramètres PID calculés

Test des paramètres PID calculés

Conclusion :

J’ai utilisé des paramètres « conservateurs » afin d’éviter de dépasser la consigne. On peut voir qu’effectivement la consigne n’est jamais dépassée, au prix d’une montée en charge un peu lente. En partant sur cette bonne base, il est maintenant facile d’affiner si l’on souhaite quelque chose d’un peu plus réactif, il reste de la marge de manœuvre.

Sources :

La régulation étant un vaste domaine, j’ai trouvé beaucoup d’informations pertinentes sur les deux sites suivants. Si vous n’êtes pas anglophobe, et désirez approfondir le sujet, je vous les recommandes chaudement !
ControlGuru
brettbeauregard.com, auteur d’osPID



  • Newsletter

    Sign up for the PlanetArduino Newsletter, which delivers the most popular articles via e-mail to your inbox every week. Just fill in the information below and submit.

  • Like Us on Facebook