Aller au contenu


Photo
- - - - -

Robot détecteur de métaux


20 réponses à ce sujet

#1 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 25 janvier 2016 - 10:21

Bonjour, 

 

Je suis en terminale SSI, dans le cadre de mon projet, je dois réaliser un montage permettant au robot de signaler à l'utilisateur où se situe les métaux, via soit une application sur un smartphone, soit via une clé usb qui enregistre où se situent le robot dans une zone définie tout en continuant son chemin. De plus, je dois programmer un programme pour relier toutes les parties du robot et les faire fonctionner ensemble ( en quelque sorte le cerveau du robot ). Nous travaillons avec une Arduino mega. Par avance merci de votre aide et si vous voulez plus d'informations, je peux vous les envoyer.

 

Allain



#2 levend

levend

    Pilier du forum

  • Membres
  • PipPipPipPipPip
  • 5 572 messages
  • Gender:Male
  • Location:Vendée
  • Interests:Robotique, informatique, architecture et patrimoine...

Posté 25 janvier 2016 - 11:13

Projet intéressant, pour quoi est-ce je n'avais pas de projet aussi intéressant un BTS informatique  :(  :kez_12:


Imprimante 3D : Prusa i3 (MK1) + CR-10S + CR-10 S5 + Artillery Sidewinder X2 + CR-30 + Elegoo Mars + Anycubic Wash & cure 2 + Phrozen Sonic Mega 8K + Phrozen Cure Mega

#3 JEF

JEF

    Membre chevronné

  • Membres
  • PipPipPipPip
  • 819 messages
  • Gender:Male
  • Location:St Cannat (13)

Posté 26 janvier 2016 - 06:39

Bonjour Allain

Je ne trouve pas ta question, où est le problème ? Si c'est comme à l'époque de mon BAC, vous devez être déjà bien guidé dans l'avancé du projet, avec des TP en lien étroit avec ce projet, donc j'imagine que tu dois savoir déjà pas mal de petites choses ;-)


Chaque jour est le premier du reste de ta vie.


#4 Microrupteurman

Microrupteurman

    Pilier du forum

  • Modérateur
  • PipPipPipPipPip
  • 2 210 messages
  • Gender:Male
  • Location:Aquitaine,Gironde
  • Interests:Tout

Posté 27 janvier 2016 - 07:00

Le must c'est un petit robot avec détecteur de métaux et electroaimant, et tu lache ca sur un parking de centre commercial le soir !


  • ashira aime ceci

 
Page Facebook : https://www.facebook...appartelier2.0/
Page Twitter :  https://twitter.com/2Appartelier (bateau seulement)
Boutique Robot-Maker : https://www.robot-ma...er-20/produits/

Besoin d'une impression 3D grand format ? Contactez moi !
 


#5 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 11 février 2016 - 03:57

Bonjour,

 

Enfaite-je voudrais programmer un système qui permet au robot d'interagir avec l'utilisateur de ce robot. Le robot enregistre sa position dans un espace défini, et dès qu'il détecte un métal il l'enregistre sur une clé USB ou autres, l'emplacement exact du métal, ou sinon il informe via une application sur smartphone l'utilisateur( mais plus compliqué). Et quand il a fini sa "ronde" dans l'espace défini il revienne au point de départ pour que l'utilisateur puisse récupérer le robot.

Que dois-je acheter pour ce système et comment le programmer ?

 

Cordialement 

Allain 



#6 Microrupteurman

Microrupteurman

    Pilier du forum

  • Modérateur
  • PipPipPipPipPip
  • 2 210 messages
  • Gender:Male
  • Location:Aquitaine,Gironde
  • Interests:Tout

Posté 11 février 2016 - 07:04

Ne pourrai t'il pas poser une balise sonore ou lumineuse ?


 
Page Facebook : https://www.facebook...appartelier2.0/
Page Twitter :  https://twitter.com/2Appartelier (bateau seulement)
Boutique Robot-Maker : https://www.robot-ma...er-20/produits/

Besoin d'une impression 3D grand format ? Contactez moi !
 


#7 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 17 mars 2016 - 12:49

Bonjour, 

 

Si c'était l'idée au début. Mais dans le cadre du projet il faut avoir un système plus "complexe", l'idée est d'enregistrer les déplacements du robot et ainsi quand il détecte un métal il enregistre sa position sur une clef USB et à la fin de son "tour" l'utilisateur la récupère et voit à partir d'un ordinateur où se situe le métal.

 

comment puis-je programmer ce système ? 

Je pense finalement utiliser une carte Arduino Uno car plus simple.

Quel autre composant dois-je acheter pour faire ce système ?



#8 Mike118

Mike118

    Staff Robot Maker

  • Administrateur
  • PipPipPipPipPip
  • 9 934 messages
  • Gender:Male
  • Location:Anglet
  • Interests:Robotique, Entrepreneuriat, Innovation, Programmation, Résolution de problème, Recherche de solutions, Mécanique, Electronique, Créer, Concevoir

Posté 19 mars 2016 - 12:37

un module GPS et on enregistre les points GPS ... tu peux enregistrer ces point GPS sur une carte SD et te servir d'un écran LCD pour avoir un système te permettant de te guider vers le point GPS.


Si mon commentaire vous a plus laissez nous un avis  !  :thank_you:

Nouveau sur Robot Maker ? 

Jetez un oeil aux blogs, aux tutoriels, aux ouvrages, au robotscope  aux articles,  à la boutique  et aux différents services disponible !
En attendant qu'une bibliothèque de fichiers 3D soit mise en place n'hésitez pas à demander si vous avez besoin du fichier 3D d'un des produits de la boutique... On l'a peut être ! 
Si vous souhaitez un robot pilotable par internet n'hésitez pas à visiter www.vigibot.com et à lire le sous forum dédié à vigibot!

 

Les réalisations de Mike118  

 

 

 


#9 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 21 mars 2016 - 02:10

Bonne idée mais qu'elle est la précision d'un module GPS branché à une Arduino Uno ? 

Quels modules GPS choisir, et comment le programmer ? 

 

ceci ferait-il l'affaire ? : http://www.selectronic.fr/arduino-adafruit-gps-logger-shield-kit-v1-1-sans-module-gps-3.html



#10 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 05 juin 2016 - 10:03

Bonjour, j'ai acheté une carte GPS Adafruit ( Adafruit Ultimate GPS+logging Shield ), j'ai réussi à la faire fonctionner mais maintenant je voudrais changer le programme ci-dessous. Au lieu d'enregistrer la positon quand on appuie sur un bouton, il enregistre la position quand j'ai une tension qui dépasse 2v (branché sur les entrées Analog), cette tension vient du détecteur de métaux quand détecte un métal. 
Quelqu'un a-t-il une idée?

// Track Your Treats - Ultimate GPS Shield Halloween Candy Route Tracker
// Author: Tony DiCola
//
// See the guide at:
// https://learn.adafruit.com/track-your-treats-halloween-candy-gps-tracker/overview
// 
// Released under a MIT license:
// https://opensource.org/licenses/MIT
#include <SPI.h>
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
#include <SD.h>




// Configuration (you don't normally need to change these values):


#define LED_PIN              6   // Pin connected to an LED that flashes the status of the project.


#define BUTTON_PIN           5   // Pin connected to the button.


#define LOGGING_PERIOD_SEC   15  // Seconds to wait between logging GPS locations.


#define GPS_RX_PIN           8   // GPS receiver RX (pin 8 on the shield).


#define GPS_TX_PIN           7   // GPS receiver TX (pin 7 on the shield)   


#define SD_CS_PIN            10  // Chip select pin for SD card.




// Global state (you don't need to change these values):
SoftwareSerial gpsSerial(GPS_RX_PIN, GPS_TX_PIN);  // Software serial connection to GPS receiver.
Adafruit_GPS GPS(&gpsSerial);                      // GPS class to interact with receiver.
File logfile;                                      // SD card log file.
uint32_t logCounter = 0;                           // Counter until next location log is recorded.




// Halt function called when an error occurs.  Will print an error and stop execution while
// doing a fast blink of the LED.  If the watchdog is enabled it will reset after 8 seconds.
void halt(const __FlashStringHelper *error) {
  Serial.println(error);
  while (1) {
    digitalWrite(LED_PIN, LOW);
    delay(100); 
    digitalWrite(LED_PIN, HIGH);
    delay(100);
  }
}


// Timer interrupt called every millisecond to check for new data from the GPS.
SIGNAL(TIMER0_COMPA_vect) {
  // Check for new GPS data.
  GPS.read();
  // Decrease the count since last location log.
  if (logCounter > 0) {
    logCounter--;
  }
}


// Log the current GPS location with the specified note.
void logLocation(const char* note) {
  logfile.print(GPS.latitudeDegrees, 6);
  logfile.print(',');
  logfile.print(GPS.longitudeDegrees, 6);
  logfile.print(',');
  logfile.print(note);
  logfile.println();
  logfile.flush();
}


void setup() {
  // Initialize serial port.
  Serial.begin(115200);
  Serial.println(F("Track your Treats - Ultimate GPS Shield"));


  // Initialize LED and button.
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);


  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(SD_CS_PIN, OUTPUT);


  // Initialize SD card (assumes running on Uno, for Leonardo see below).
  if (!SD.begin(SD_CS_PIN)) {
  // Initialize SD card for Leonardo or other chips (using software SPI)
  //if (!SD.begin(SD_CS_PIN, 11, 12, 13)) {
    halt(F("Card init. failed!"));
  }


  // Create the next log file on the SD card.
  char filename[15];
  strcpy(filename, "GPSLOG00.CSV");
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = '0' + i/10;
    filename[7] = '0' + i%10;
    // Create file if it does not exist.
    if (!SD.exists(filename)) {
      break;
    }
  }
  Serial.print("Using log file: "); 
  Serial.println(filename);


  // Open the log file.
  logfile = SD.open(filename, FILE_WRITE);
  if(!logfile) {
    halt(F("Failed to open log file!"));
  }


  // Set the first line of the log file as the column headers.
  logfile.println("latitude,longitude,note");
  logfile.flush();


  // Connect to the GPS receiver and configure it to receive location updates once a second.
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY); // Recommended minimum output only (all we need for this project).
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);     // Once a second update rate.
  GPS.sendCommand(PGCMD_NOANTENNA);              // Turn off antenna status.


  // Configure timer0 compare interrupt to run and parse GPS data every millisecond.
  // See the SIGNAL function further below for the code that is called during this interrupt.
  OCR0A = 0xAF;
  TIMSK0 |= _BV(OCIE0A);


  Serial.println("Ready!");
}


void loop() {
  // Parse GPS messages when they are received.
  if (GPS.newNMEAreceived()) {
    GPS.parse(GPS.lastNMEA());
  }
  
  // Light the LED solid if there's a GPS fix, otherwise flash it on and off once a second.
  if (GPS.fix) {
    digitalWrite(LED_PIN, HIGH);
  }
  else {
    // No fix, blink the LED once a second and stop further processing.
    digitalWrite(LED_PIN, (millis()/1000) % 2);
    return;
  }


  // Check if the button is pressed.
  if (digitalRead(BUTTON_PIN) == LOW) {
    // Pause a bit to debounce.
    delay(100);
    if (digitalRead(BUTTON_PIN) == LOW) {
      // Button pressed! Log the current location as having good candy.
      logLocation("Good Candy");
      // Then flash the light 5 times to signal the location was recorded.
      for (int i=0; i<5; ++i) {
        digitalWrite(LED_PIN, HIGH);
        delay(250);
        digitalWrite(LED_PIN, LOW);
        delay(250);
      }
    }
  }


  // Periodically log the location.
  if (logCounter == 0) {
    logLocation("Location");
    logCounter = LOGGING_PERIOD_SEC*1000;
  }
}

Cordialement 
Allain



#11 Path

Path

    Made By Humans

  • Modérateur
  • PipPipPipPipPip
  • 2 504 messages
  • Gender:Male
  • Location:Paris

Posté 05 juin 2016 - 11:26

Salut Alain,

 

Sauf erreur, j'ai pas vu de code concernant le détecteur de métaux. Commence par faire un petit programme qui allume une led quand il y a un métal (> 2V si j'ai bien compris). 

 

Cette première étape te permet de valider le fonctionnement et le comportement de ton détecteur.

 

Après, tu remplace le if bouton pressé par ta condition de detection de métaux (if Ax > 2V). Le corps du if doit être quasiment le même à part le bounce.

 

Quand tu en seras là, tu auras certainement besoin de ne pas écrire plusieurs fois la même position.  Il te faudra lire dans le fichier ou garder en mémoire les positions déjà trouvées.



#12 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 05 juin 2016 - 08:02

Salut,

 

Enfaite nous avons une carte détectrice de métaux, qui allume une led quand un métal est détecté. Cette led s'allume quand la tension dépasse 2v donc je récupère cette tension pour les entrées analog.
Mais comment faire en sorte dans le programme ci dessus, qu'il lise la tension et qu'il enregistre la position quand tension>2v?



#13 Path

Path

    Made By Humans

  • Modérateur
  • PipPipPipPipPip
  • 2 504 messages
  • Gender:Male
  • Location:Paris

Posté 05 juin 2016 - 08:33

Alors il me semble que cette page devrait t'aider : https://www.arduino....ence/AnalogRead.

 

Le but est de faire un petit programme qui test ton entrée analogique. Avant de changer ton if, il faut bien valider le comportement de ta carte qui détecte les métaux.



#14 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 07 juin 2016 - 11:18

Merci pour ce lien, cependant j'ai un problème quand je compile sous Arduino, j'ai une erreur de ce type:

 
...arduino-1.6.4-windows\arduino-1.6.4\hardware\tools\avr/etc/avrdude.conf:332: programmer type must be written as "id_type"
 
Je ne comprends d'où vient l'erreur, que dois-je faire ? 


#15 Path

Path

    Made By Humans

  • Modérateur
  • PipPipPipPipPip
  • 2 504 messages
  • Gender:Male
  • Location:Paris

Posté 07 juin 2016 - 11:31

D'abord, mettez à jour votre IDE.

 

Est-ce que vous avez le problème avec les programmes d'exemple ?

 

Si le problème persiste, Google !! :) Cherchez le texte : programmer type must be written as "id_type"

On tombe très vite sur la solution : https://lists.nongnu...8/msg00008.html



#16 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 07 juin 2016 - 06:01

Bonjour,

j'ai résolu le problème de compilation.

J'ai changé le programme pour qu'il lise l'entrée analog, mais j'ai essayé de mettre la condition quand

if val = analogRead(analogPin)>2v;    // read the input pin

mais cela ne marche pas, où dois je mettre la condition? (ou je dois utiliser 

  if (digitalRead(analog_PIN) >2v) {

 ?)

De plus je voudrais enregistrer l'heure et la date dans le fichier qui est créé dans la carte SD, comment dois-je faire ?

#include <Adafruit_GPS.h>


#include <SD.h>


// Track Your Treats - Ultimate GPS Shield Halloween Candy Route Tracker
// Author: Tony DiCola
//
// See the guide at:
// https://learn.adafruit.com/track-your-treats-halloween-candy-gps-tracker/overview
// 
// Released under a MIT license:
// https://opensource.org/licenses/MIT
#include <SPI.h>
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
#include <SD.h>




// Configuration (you don't normally need to change these values):


#define LED_PIN              6   // Pin connected to an LED that flashes the status of the project.


#define analog_PIN           3   // Pin connected to the LED of detector.


#define LOGGING_PERIOD_SEC   15  // Seconds to wait between logging GPS locations.


#define GPS_RX_PIN           8   // GPS receiver RX (pin 8 on the shield).


#define GPS_TX_PIN           7   // GPS receiver TX (pin 7 on the shield)   


#define SD_CS_PIN            10  // Chip select pin for SD card.




// Global state (you don't need to change these values):
SoftwareSerial gpsSerial(GPS_RX_PIN, GPS_TX_PIN);  // Software serial connection to GPS receiver.
Adafruit_GPS GPS(&gpsSerial);                      // GPS class to interact with receiver.
File logfile;                                      // SD card log file.
uint32_t logCounter = 0;                           // Counter until next location log is recorded.




// Halt function called when an error occurs.  Will print an error and stop execution while
// doing a fast blink of the LED.  If the watchdog is enabled it will reset after 8 seconds.
void halt(const __FlashStringHelper *error) {
  Serial.println(error);
  while (1) {
    digitalWrite(LED_PIN, LOW);
    delay(100); 
    digitalWrite(LED_PIN, HIGH);
    delay(100);
  }
}


// Timer interrupt called every millisecond to check for new data from the GPS.
SIGNAL(TIMER0_COMPA_vect) {
  // Check for new GPS data.
  GPS.read();
  // Decrease the count since last location log.
  if (logCounter > 0) {
    logCounter--;
  }
}


// Log the current GPS location with the specified note.
void logLocation(const char* note) {
  logfile.print(GPS.latitudeDegrees, 6);
  logfile.print(',');
  logfile.print(GPS.longitudeDegrees, 6);
  logfile.print(',');
  logfile.print(note);
  logfile.println();
  logfile.flush();
}


void setup() {
  // Initialize serial port.
  Serial.begin(115200);
  Serial.println(F("Track your Treats - Ultimate GPS Shield"));


  // Initialize LED and button.
  pinMode(LED_PIN, OUTPUT);
  pinMode(analog_PIN, INPUT_PULLUP);


  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(SD_CS_PIN, OUTPUT);


  // Initialize SD card (assumes running on Uno, for Leonardo see below).
  if (!SD.begin(SD_CS_PIN)) {
  // Initialize SD card for Leonardo or other chips (using software SPI)
  //if (!SD.begin(SD_CS_PIN, 11, 12, 13)) {
    halt(F("Card init. failed!"));
  }


  // Create the next log file on the SD card.
  char filename[15];
  strcpy(filename, "GPSLOG00.CSV");
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = '0' + i/10;
    filename[7] = '0' + i%10;
    // Create file if it does not exist.
    if (!SD.exists(filename)) {
      break;
    }
  }
  Serial.print("Using log file: "); 
  Serial.println(filename);


  // Open the log file.
  logfile = SD.open(filename, FILE_WRITE);
  if(!logfile) {
    halt(F("Failed to open log file!"));
  }


  // Set the first line of the log file as the column headers.
  logfile.println("latitude,longitude,note");
  logfile.flush();


  // Connect to the GPS receiver and configure it to receive location updates once a second.
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY); // Recommended minimum output only (all we need for this project).
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);     // Once a second update rate.
  GPS.sendCommand(PGCMD_NOANTENNA);              // Turn off antenna status.


  // Configure timer0 compare interrupt to run and parse GPS data every millisecond.
  // See the SIGNAL function further below for the code that is called during this interrupt.
  OCR0A = 0xAF;
  TIMSK0 |= _BV(OCIE0A);


  Serial.println("Ready!");
}


void loop() {
  // Parse GPS messages when they are received.
  if (GPS.newNMEAreceived()) {
    GPS.parse(GPS.lastNMEA());
  }
  
  // Light the LED solid if there's a GPS fix, otherwise flash it on and off once a second.
  if (GPS.fix) {
    digitalWrite(LED_PIN, HIGH);
  }
  else {
    // No fix, blink the LED once a second and stop further processing.
    digitalWrite(LED_PIN, (millis()/1000) % 2);
    return;
  }


  // Check if the button is pressed.
  if (digitalRead(analog_PIN) == LOW) {
    // Pause a bit to debounce.
    delay(100);
    if (digitalRead(analog_PIN) == LOW) {
      // Button pressed! Log the current location as having good candy.
      logLocation("Good Candy");
      // Then flash the light 5 times to signal the location was recorded.
      for (int i=0; i<5; ++i) {
        digitalWrite(LED_PIN, HIGH);
        delay(250);
        digitalWrite(LED_PIN, LOW);
        delay(250);
      }
    }
  }


  // Periodically log the location.
  if (logCounter == 0) {
    logLocation("Location");
    logCounter = LOGGING_PERIOD_SEC*1000;
  }
}


#17 Path

Path

    Made By Humans

  • Modérateur
  • PipPipPipPipPip
  • 2 504 messages
  • Gender:Male
  • Location:Paris

Posté 07 juin 2016 - 06:25

Avez-vous vraiment fait un petit programme qui ne fait que lire le signale du détecteur de métaux ?

 

Ce que retourne analogRead est un entier entre 0 et 1023. Il faut multiplier ce résultat par .0049 pour retrouver la tension en volt. Tout est est dans la doc. Il faut la lire.

 

En second lieu, il vous faut comprendre chaque ligne de votre code.

Je vous ai déjà donné l'endroit où modifier. ;)



#18 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 08 juin 2016 - 11:46

Oui voilà un programme du détecteur de métaux qui lit la tension et qui affiche si elle est supérieure à 2v: 

<code>

 

 
#include <LiquidCrystal.h>



const int RS=2; //declaration constante de broche 
const int E=3; //declaration constante de broche 
const int D4=4; //declaration constante de broche 
const int D5=5; //declaration constante de broche 
const int D6=6; //declaration constante de broche 
const int D7=7; //declaration constante de broche 


LiquidCrystal lcd(RS, E, D4, D5, D6, D7);




const int analogInPin = A0;  
int valeurLue = 0;
float tension ;




void setup() {
  
  Serial.begin(9600);
  lcd.begin(16,2); // Initialise le LCD avec 16 colonnes x 2 lignes 
  delay(10);
  lcd.print("EN FONCTION") ;
  delay(1000); // pause rapide pour laisser temps initialisation
  
}


void loop() {
  lcd.clear();
  lcd.home();
  //delay (10);  
  
  valeurLue = analogRead(analogInPin);
  tension = valeurLue*5.0/1023;
    
 if (tension >2)
  { 
  lcd.print("METAL DETECTE") ; 
  delay(150); 
  }
else 
{
  lcd.print("PAS DE METAL");
  delay(150);
}
delay(10);
  


}

<code/>

je dois reprendre la condition ? 



#19 Path

Path

    Made By Humans

  • Modérateur
  • PipPipPipPipPip
  • 2 504 messages
  • Gender:Male
  • Location:Paris

Posté 08 juin 2016 - 12:12

Tu peux la reprendre si ce petit programme te donne satisfaction.

#20 Conrad Allain

Conrad Allain

    Membre

  • Membres
  • 26 messages

Posté 16 juin 2016 - 07:26

Bonjour, j'ai une autre question, concernant le code ci-dessous, je voudrais que les led restent allumées, ce code vient de chez Adafruit, mais j'ai un peu de mal à le comprendre.
Auriez-vous une idée? 
 
source : https://learn.adafru...eopixel-goggles
 
 

// Bluetooth Goggles Sketch -- shows the Adafruit Bluefruit LE UART Friend
// can be used even with Trinket or Gemma!
 
// https://www.adafruit.com/products/2479
 
// Works in conjunction with Bluefruit LE Connect app on iOS or Android --
// pick colors or use '1' and '2' buttons to select pinwheel or sparkle modes.
// You can try adding more, but space is VERY tight...helps to use Arduino IDE
// 1.6.4 or later; produces slightly smaller code than the 1.0.X releases.
 
// BLUEFRUIT LE UART FRIEND MUST BE SWITCHED TO 'UART' MODE
 
#include <SoftwareSerial.h>
#include <Adafruit_NeoPixel.h>
#ifdef __AVR_ATtiny85__ // Trinket, Gemma, etc.
 #include <avr/power.h>
#endif
 
#define RX_PIN    4 // Connect this Trinket pin to BLE 'TXO' pin
#define CTS_PIN   3 // Connect this Trinket pin to BLE 'CTS' pin
#define LED_PIN   2 // Connect NeoPixels to this Trinket pin
#define NUM_LEDS 32 // Two 16-LED NeoPixel rings
#define FPS      30 // Animation frames/second (ish)
 
SoftwareSerial    ser(RX_PIN, 4);
Adafruit_NeoPixel pixels(NUM_LEDS, LED_PIN);
 
void setup() {
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
  // MUST do this on 16 MHz Trinket for serial & NeoPixels!
  clock_prescale_set(clock_div_1);
#endif
  // Stop incoming data & init software serial
  pinMode(CTS_PIN, OUTPUT); digitalWrite(CTS_PIN, HIGH);
  ser.begin(9600);
 
  pixels.begin(); // NeoPixel init
  // Flash space is tight on Trinket/Gemma, so setBrightness() is avoided --
  // it adds ~200 bytes.  Instead the color picker input is 'manually' scaled.
}
 
uint8_t  buf[3],              // Enough for RGB parse; expand if using sensors
         animMode = 0,        // Current animation mode
         animPos  = 0;        // Current animation position
uint32_t color    = 0x400000, // Current animation color (red by default)
         prevTime = 0L;       // For animation timing
 
void loop(void) {
  int      c;
  uint32_t t;
 
  // Animation happens at about 30 frames/sec.  Rendering frames takes less
  // than that, so the idle time is used to monitor incoming serial data.
  digitalWrite(CTS_PIN, LOW); // Signal to BLE, OK to send data!
  for(;  {
    t = micros();                            // Current time
    if((t - prevTime) >= (1000000L / FPS)) { // 1/30 sec elapsed?
      prevTime = t;
      break;                                 // Yes, go update LEDs
    }                                        // otherwise...
    if((c = ser.read()) == '!') {            // Received UART app input?
      while((c = ser.read()) < 0);           // Yes, wait for command byte
      switch(c) {
       case 'B':       // Button (Control Pad)
        if(readAndCheckCRC(255-'!'-'B', buf, 2) & (buf[1] == '1')) {
          buttonPress(buf[0]); // Handle button-press message
        }
        break;
       case 'C':       // Color Picker
        if(readAndCheckCRC(255-'!'-'C', buf, 3)) {
          // As mentioned earlier, setBrightness() was avoided to save space.
          // Instead, results from the color picker (in buf[]) are divided
          // by 4; essentially equivalent to setBrightness(64).  This is to
          // improve battery run time (NeoPixels are still plenty bright).
          color = pixels.Color(buf[0]/4, buf[1]/4, buf[2]/4);
        }
        break;
       case 'Q':       // Quaternion
        skipBytes(17); // 4 floats + CRC (see note below re: parsing)
        break;
       case 'A':       // Accelerometer
#if 0
        // The phone sensors are NOT used by this sketch, but this shows how
        // they might be read.  First, buf[] must be delared large enough for
        // the expected data packet (minus header & CRC) -- that's 16 bytes
        // for quaternions (above), or 12 bytes for most of the others.
        // Second, the first arg to readAndCheckCRC() must be modified to
        // match the data type (e.g. 'A' here for accelerometer).  Finally,
        // values can be directly type-converted to float by using a suitable
        // offset into buf[] (e.g. 0, 4, 8, 12) ... it's not used in this
        // example because floating-point math uses lots of RAM and code
        // space, not suitable for the space-constrained Trinket/Gemma, but
        // maybe you're using a Pro Trinket, Teensy, etc.
        if(readAndCheckCRC(255-'!'-'A', buf, 12)) {
          float x = *(float *)(&buf[0]),
                y = *(float *)(&buf[4]),
                z = *(float *)(&buf[8]);
        }
        // In all likelihood, updates from the buttons and color picker
        // alone are infrequent enough that you could do without any mention
        // of the CTS pin in this code.  It's the extra sensors that really
        // start the firehose of data.
        break;
#endif
       case 'G':       // Gyroscope
       case 'M':       // Magnetometer
       case 'L':       // Location
        skipBytes(13); // 3 floats + CRC
      }
    }
  }
  digitalWrite(CTS_PIN, HIGH); // BLE STOP!
 
  // Show pixels calculated on *prior* pass; this ensures more uniform timing
  pixels.show();
 
  
 
boolean readAndCheckCRC(uint8_t sum, uint8_t *buf, uint8_t n) {
  for(int c;  {
    while((c = ser.read()) < 0); // Wait for next byte
    if(!n--) return (c == sum);  // If CRC byte, we're done
    *buf++ = c;                  // Else store in buffer
    sum   -= c;                  // and accumulate sum
  }
}
 
void skipBytes(uint8_t n) {
  while(n--) {
    while(ser.read() < 0);
  }
}
 
void buttonPress(char c) {
  pixels.clear(); // Clear pixel data when switching modes (else residue)
  switch(c) {
   case '1':
    animMode = 0; // Switch to pinwheel mode
    break;
   case '2':
    animMode = 1; // Switch to sparkle mode
    break;
   case '3':
    break;
   case '4':
    break;
   case '5': // Up
    break;
   case '6': // Down
    break;
   case '7': // Left
    break;
   case '8': // Right
    break;
  }
}

 
je ne sais pas trop oû remplacer ce code par : 
 

// NeoPixel Ring simple sketch (c) 2013 Shae Erisson
// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library
 
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif
 
// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            6
 
// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      16
 
// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
 
int delayval = 500; // delay for half a second
 
void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
  // End of trinket special code
 
  pixels.begin(); // This initializes the NeoPixel library.
}
 
void loop() {
 
  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
 
  for(int i=0;i<NUMPIXELS;i++){
 
    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
    pixels.setPixelColor(i, pixels.Color(0,150,0)); // Moderately bright green color.
 
    pixels.show(); // This sends the updated pixel color to the hardware.
 
    delay(delayval); // Delay for a period of time (in milliseconds).
 
  }
}

 





Répondre à ce sujet



  


0 utilisateur(s) li(sen)t ce sujet

0 members, 0 guests, 0 anonymous users