Code pour shields et modules Arduino
Page mise à jour le 06-01-2026 à 23:21
// ACCELEROMETRES ADXL

const int xpin = A3; // axe x
const int ypin = A2; // axe y
const int zpin = A1; // axe z uniquement sur modèles 3 axes
const int apin = A0; // auto test si disponible

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.print(analogRead(xpin));
  Serial.print("\t");
  Serial.print(analogRead(ypin));
  Serial.print("\t");
  Serial.print(analogRead(zpin));
  Serial.println();
  delay(1000);
}
// BOUSSOLE CMPS03

#define PWM_PIN  15   // vers pin 4 du CMPS03    

unsigned int pwm_value, pwm_value_max, pwm_value_min;
 
void setup() {
  pinMode(PWM_PIN, INPUT);
  Serial.begin(9600);
  pwm_value_max = pulseIn(PWM_PIN, HIGH);
  pwm_value_min = pwm_value_max;
}
 
void loop() {
  pwm_value = pulseIn(PWM_PIN, HIGH);
  // recherche des valeurs min et max
  if (pwm_value > pwm_value_max)
    pwm_value_max=pwm_value;  
  if (pwm_value < pwm_value_min)
    pwm_value_min=pwm_value;  
  // NORD  = min
  // OUEST = max*90/360
  // SUD   = max*180/360
  // EST   = max*270/360
    
  Serial.print("min : ");
  Serial.print(pwm_value_min);
  Serial.print("   valeur : ");
  Serial.print(pwm_value);
  Serial.print("   max : ");
  Serial.println(pwm_value_max);
  delay(1000);
}
// CAPTEUR DE SON DIGITAL KY-XX

#define led 12
#define sound 2

boolean statusLED = false;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(sound, INPUT);
}

void loop() {
  if(digitalRead(sound) == HIGH) {
    statusLED = !statusLED;
    digitalWrite(led, statusLED);
    delay(50);
  }
}
// CAPTEUR DE COULEURS TCS230 / TCS3200

#define S0 4
#define S1 5
#define S2 6
#define S3 7
#define sensorOut 8

int redFrequency = 0;
int greenFrequency = 0;
int blueFrequency = 0;
int redColor = 0;
int greenColor = 0;
int blueColor = 0;

void setup() {
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(sensorOut, INPUT);
  digitalWrite(S0,HIGH);
  digitalWrite(S1,LOW);
  Serial.begin(9600);
}

void loop() {
  // lecture du rouge
  digitalWrite(S2,LOW);
  digitalWrite(S3,LOW);
  redFrequency = pulseIn(sensorOut, LOW);
  redColor = map(redFrequency, 70, 120, 255,0); // map(redFrequency, min, max, 255,0)
  Serial.print("R = ");
  Serial.print(redFrequency); // relever les valeurs min et max pour la fonction map()
  delay(100);
  
  // lecture du vert
  digitalWrite(S2,HIGH);
  digitalWrite(S3,HIGH);
  greenFrequency = pulseIn(sensorOut, LOW);
  greenColor = map(greenFrequency, 100, 199, 255, 0); // map(greenFrequency, min, max, 255,0)
  Serial.print(" G = ");
  Serial.print(greenFrequency); // relever les valeurs min et max pour la fonction map()
  delay(100);
 
  // lecture du bleu
  digitalWrite(S2,LOW);
  digitalWrite(S3,HIGH);
  blueFrequency = pulseIn(sensorOut, LOW);
  blueColor = map(blueFrequency, 38, 84, 255, 0); // map(blueFrequency, min, max, 255,0)
  Serial.print(" B = ");
  Serial.print(blueFrequency); // relever les valeurs min et max pour la fonction map()
  delay(100);

  if (redColor > greenColor && redColor > blueColor)
      Serial.println(" - ROUGE detecté");
  if (greenColor > redColor && greenColor > blueColor)
    Serial.println(" - VERT detecté");
  if (blueColor > redColor && blueColor > greenColor)
    Serial.println(" - BLEU detecté");
}
// ETHERNET SERVEUR HTTP

#include <SPI.h>
#include <Ethernet.h>

// déclaration de l'adresse MAC (voir étiquette sur le shield, sinon en inventer une)
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x1A, 0x71 }

// paramètres TCP/IP
IPAddress ip( 172, 16, 1, 70 );
byte masque[] = { 255, 255, 0, 0 };
byte passerelle[] = { 172, 16, 1, 1 };

// création de l'objet server et du port utilisé
EthernetServer server(80);

void setup() {
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.begin(9600);
  Serial.print("IP Server: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  EthernetClient client = server.available(); // écoute des clients entrants
  if (client) {
    Serial.println("New client");
    boolean currentLineIsBlank = true; // une requête http se termine par une ligne vide
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // la requête HTTP est terminée et on peut envoyer une réponse
        // si on reçoit en fin de ligne un caractère de nouvelle ligne et que la ligne est vide 
        if (c == '\n' && currentLineIsBlank) {
          // entête HTML
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");   // la connexion sera fermée après l'achèvement de la réponse
          client.println("Refresh: 5");          // raffraichit la page toutes les 5 secondes
          client.println();
          // page HTML (affiche les valeurs d'entrées analogiques pour l'exemple)
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input A");
            client.print(analogChannel);
            client.print(" = ");
            client.print(sensorReading);
            client.println("<br>");       
          }
          client.println("</html>");
          break;
        }
        if (c == '\n')
          currentLineIsBlank = true; // nouvelle ligne
        else if (c != '\r')
          currentLineIsBlank = false; // obtention d'un caracactère sur la ligne courante
      }
    }
    delay(1); // laisse le temps au navigateur Web pour recevoir les données
    client.stop(); // ferme la connexion
    Serial.println("Client disconnected");
  }
}
// HORLOGE RTC

#include <iarduino_RTC.h>
// iarduino_RTC time (RTC_DS1302,7,5,6);  // pour module DS1302
// iarduino_RTC time (RTC_DS1307);        // pour module DS1307 i2C
iarduino_RTC time (RTC_DS3231);           // pour module DS3231 i2C

void setup() {
   Serial.begin(9600);
   time.begin();
   time.settime(0, 30, 18, 2, 1, 22, 0) // mise à l'heure : sec, min, heures, date, mois, année, jour
}

void loop() {
   // affichage toutes les secondes
   if (millis() % 1000 == 0) {
      Serial.println(time.gettime("d-m-Y, H:i:s, D"));
   }
}
// CLAVIER 4x4

#include <Keypad.h>

const byte ROWS = 4; 
const byte COLS = 4; 
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[ROWS] = {2,3,4,5}; // entrées digitales vers pins 5,6,7,8 du clavier
byte colPins[COLS] = {6,7,8,9}; // entrées digitales vers pins 1,2,3,4 du clavier

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup() {
  Serial.begin(9600);
}

void loop() {
  char key = keypad.getKey();
  if (key != NO_KEY)
    Serial.println(key);
}
// LCD DATA-IMAGE (16 caractères, 4 lignes) + MODULE I2C

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,4) // adresse 0x27, 16 caractères, 4 lignes

void setup() {
  lcd.init() ;
  lcd.cursor_off() ;
  lcd.blink_off() ;
}

void loop() {
  // décalage 0 pour lignes 1 et 2
  lcd.setCursor(0,0) ;
  lcd.print("ligne 1") ;
  lcd.setCursor(0,1) ;
  lcd.print("ligne 2") ;
  // décalage x-4 pour lignes 3 et 4
  lcd.setCursor(-4,2) ;
  lcd.print("ligne 3") ;
  lcd.setCursor(-4,3) ;
  lcd.print("ligne 4") ;
  
  delay(1000);
  lcd.clear();
  
  // décalage 0 pour lignes 1 et 2
  lcd.setCursor(9,0) ;
  lcd.print("ligne 1") ;
  lcd.setCursor(9,1) ;
  lcd.print("ligne 2") ;
  // décalage x-4 pour lignes 3 et 4
  lcd.setCursor(5,2) ;
  lcd.print("ligne 3") ;
  lcd.setCursor(5,3) ;
  lcd.print("ligne 4") ;
  
  delay(1000);
  lcd.clear();
}
// LCD KEYPAD SHIELD

#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // Pins utilisés par le LCD

// valeurs utilisées par le panneau et les boutons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// lecture des boutons
int read_LCD_buttons() {
  adc_key_in = analogRead(0);
  if (adc_key_in > 1000) return btnNONE;
  if (adc_key_in < 50)   return btnRIGHT;  
  if (adc_key_in < 250)  return btnUP; 
  if (adc_key_in < 450)  return btnDOWN; 
  if (adc_key_in < 650)  return btnLEFT; 
  if (adc_key_in < 850)  return btnSELECT;  
  return btnNONE;
}

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);
  lcd.print("Push the buttons");
}
 
void loop() {
  lcd.setCursor(9,1);            // positionnement du curseur
  lcd.print(millis()/1000);      // secondes écoulées depuis le dernier reset
  lcd.setCursor(0,1);            // positionnement du curseur
  lcd_key = read_LCD_buttons() // lecture des boutons
  switch (lcd_key) {
    case btnRIGHT :
      lcd.print("RIGHT  ");
      break;
    case btnLEFT :
      lcd.print("LEFT   ");
      break;
    case btnUP :
      lcd.print("UP     ");
      break;
    case btnDOWN :
      lcd.print("DOWN   ");
      break;
    case btnSELECT :
      lcd.print("SELECT ");
      break;
    case btnNONE :
      lcd.print("NONE   ");
      break;
  }
}
// MATRICE LED 8x8

#include <LedControl.h>

LedControl lc = LedControl(12,11,10,1);
// MAX7219 pin  1 (din) => pin 12
// MAX7219 pin 13 (clk) => pin 11
// MAX7219 pin 12 (cs)  => pin 10
// MAX7219 x 1
 
void setup() {
  // 0 = numéro du MAX7219
  lc.shutdown(0,false) // power saving off et enable display
  lc.setIntensity(0,8) // intensité 0 à 15
  lc.clearDisplay(0);    // effacer
}

void loop() {
  prog(15); // durée en millisecondes
}

void prog(int lapse) {
  for (int row=0; row<8; row++) {
    for (int col=0; col<8; col++) {
      lc.setLed(0,col,row,true);
      delay(lapse);
    }
  }
  for (int row=0; row<8; row++) {
    for (int col=0; col<8; col++) {
      lc.setLed(0,col,row,false);
      delay(lapse);
    }
  }
}
// MULTI FUNCTION DIGITS

int latchPin = 4;
int clockPin = 7;
int dataPin = 8;

unsigned char Dis_table[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};
unsigned char Dis_buf[] = {0xF1,0xF2,0xF4,0xF8};
unsigned char disbuff[] = {0, 0, 0, 0};
unsigned int  add[65] = {0};

int rT = 0;
float temp;

void setup () {
  pinMode(latchPin,OUTPUT);
  pinMode(clockPin,OUTPUT);
  pinMode(dataPin,OUTPUT);
}

void display() {
  for (byte i=0; i<=3; i++) {
    digitalWrite(latchPin,LOW);
    if (i == 0)
      shiftOut(dataPin,clockPin,MSBFIRST,Dis_table[disbuff[i]]&0x7F);
    else
      shiftOut(dataPin,clockPin,MSBFIRST,Dis_table[disbuff[i]]);
    shiftOut(dataPin,clockPin,MSBFIRST,Dis_buf[i]);
    digitalWrite(latchPin,HIGH);
    delay(2);
  }
}

void loop() {
  float vol = analogRead(A0)*(4.97 / 1023.0); // tension en sortie de résistance ajustable
  rT = (int)(vol*1000);  
  disbuff[0] = rT/1000;
  disbuff[1] = rT%1000/100;
  disbuff[2] = rT%100/10;
  disbuff[3] = rT%10;
  for (byte time=0;time<30;time++) display();
}
// PAP MOTOR DRIVER L298N

#include <Stepper.h>

const int stepsPerRevolution = 100;  // nombre de pas par tour

Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); // initialisation des ports

void setup() {
  myStepper.setSpeed(60); // vitesse en tr/mn
  Serial.begin(9600);
}

void loop() {
  Serial.println("clockwise"); // 1 tour en sens horaire
  myStepper.step(stepsPerRevolution);
  delay(500);

  Serial.println("counterclockwise"); // 1 tour en sens anti-horaire
  myStepper.step(-stepsPerRevolution);
  delay(500);
}
// PWM MOTORS DRIVER L298N

// pins connecés au pont en H
int IN1 = 4;
int IN2 = 5;
int IN3 = 6;
int IN4 = 7;

void setup() {
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
}

void loop() {
  // Rotation Moteur A en sens horaire
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  delay(2000);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, HIGH);
  delay(500);
  // Rotation Moteur B en sens horaire
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  delay(2000);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, HIGH);
  delay(500);
  // Rotation Moteur A en sens anti-horaire
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  delay(2000);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, HIGH);
  delay(500);
  // Rotation Moteur B en sens anti-horaire
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  delay(2000);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, HIGH);
  delay(500);
}
// SD CARD : INFOS SUR LE VOLUME
// MOSI -> arduino pin 11
// MISO -> arduino pin 12
// SCK --> arduino pin 13
// SC ---> arduino pin 4

#include <SPI.h>
#include <SD.h>

Sd2Card card;
SdVolume volume;
SdFile root;

const int chipSelect = 4;    

void print_uint64_t(uint64_t num) {
  char rev[128]
  char *p = rev+1;
  while (num > 0) {
    *p++ = '0' + ( num % 10);
    num/= 10;
  }
  p--;
  while (p > rev) {
    Serial.print(*p--);
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(SS, OUTPUT);

  while (!card.init(SPI_HALF_SPEED, chipSelect)) 
    Serial.println("Echec d'initialisation");

  Serial.print("\nCarte type: ");
  switch(card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Inconnu");
  }

  if (!volume.init(card)) {
    Serial.println("Partition FAT16/FAT32 non trouvée.\nAssurez-vous d'avoir formaté la carte");
    return;
  }

  uint64_t volumesize;
  Serial.print("Volume de type FAT");
  Serial.println(volume.fatType(), DEC);

  volumesize = volume.blocksPerCluster();
  volumesize *= volume.clusterCount();
  volumesize *= 512;
  Serial.print("Volume size: ");
  print_uint64_t(volumesize);
  Serial.println(" octets");

  Serial.println("\nFichiers présents sur la carte (nom, date et taille en octets)");
  root.openRoot(volume);
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop() {
}
// SD CARD : LIRE ET ECRIRE
// MOSI -> arduino pin 11
// MISO -> arduino pin 12
// SCK --> arduino pin 13
// SC ---> arduino pin 4

#include <SPI.h>
#include <SD.h>

File myFile;

const int chipSelect = 4;    

void setup() {
  Serial.begin(9600);
  pinMode(SS, OUTPUT);
  while (!SD.begin(SPI_HALF_SPEED, chipSelect)) 
    Serial.println("Echec d'initialisation");

  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    Serial.println("Ecriture d'une ligne dans test.txt");
    myFile.println("Test d'écriture réussi");
    myFile.close();
  }
  else Serial.println("Erreur d'ouverture du fichier test.txt");

  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.print("\nLecture du fichier test.txt (");
    Serial.print(myFile.size());
    Serial.println(" octets)");
    while (myFile.available())
      Serial.write(myFile.read());
      myFile.close();
  }
  else Serial.println("Erreur d'ouverture du fichier test.txt");
}

void loop() {
}
// SMC PRO
// DIP switches 1 à 5 sur ON (1 seul module SMCpro)
// DIP switch       6 sur ON (9600 bps)
// TX du port RS232 microcontrôleur -> pin TX0 du Arduino

void smcOut(byte data) {
  Serial.write(data);       // envoi du message au servo
  delayMicroseconds(500);   // délai minimum entre messages
}

void setSpeed(byte servo, byte speed) {
  smcOut(servo);            // numéro du servo
  smcOut(0);                // 0 = mode vitesse
  smcOut(speed);            // vitesse (0 à 255)
  delay(200);
}

void setDegre(byte servo, byte degres) {
  smcOut(servo);            // numéro du servo
  smcOut(1);                // 1 = mode angle
  smcOut(degres);           // angle en degrés (0 à 180)
  delay(200);
}

void setup() {
  Serial.begin(9600);
}

void loop() {
  byte servo = 1;           // numéro du servo (0 à 7)
  setSpeed(servo,255);      // vitesse (0 à 255)
  setDegre(servo,0);        // angle (0 à 180)
  delay(100);
  setSpeed(servo,255);
  setDegre(servo,180);
  delay(100);
}
// SONAR ULTRASONS SRF05

long duration;
int distance;

const int trig = 9;
const int echo = 10;

void setup() {
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);
}

void loop() {
  distance = calculDistance();
  Serial.println(distance)
  delay(1000);
}

int calculDistance(){ 
  digitalWrite(trig, LOW)
  delayMicroseconds(2);
  digitalWrite(trig, HIGH); // trigger état haut durant µs
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH); // temps de parcours de l'onde sonore en µs
  distance= duration*0.034/2;
  return distance; // distance en cm
}
Papy WinTux - Philippe DESLOGES - 2023-2026 - Powered by Debian - Apache 2.4.54 - PHP 7.4.33 - Last update 06-01-2026 23:21 - Page size 123 ko built in 37 ms
All trademarks, logos, images and documents on these pages belong exclusively to their respective owners.