Arduino & PureBasic

Informations pour bien débuter en PureBasic
Avatar de l’utilisateur
MetalOS
Messages : 1492
Inscription : mar. 20/juin/2006 22:17
Localisation : Lorraine
Contact :

Re: Arduino & PureBasic

Message par MetalOS »

G-Rom tu aurais un exemple de code Arduino qui permet d'envoyer le contenue des "Serial.println" vers un programme PureBasic. J'ai acheter une puce AS3935 qui permet de faire de la détection de la foudre dans un rayon d'environ 40 KM. Sur internet on trouve la lib et des code d'exemple.

En voici un fournit avec la lib de la puce:

Code : Tout sélectionner

/*
  LightningDetector.pde - AS3935 Franklin Lightning Sensor™ IC by AMS library demo code
  Copyright (c) 2012 Raivis Rengelis (raivis [at] rrkb.lv). All rights reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 3 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <SPI.h>
#include <AS3935.h>

void printAS3935Registers();

// Function prototype that provides SPI transfer and is passed to
// AS3935 to be used from within library, it is defined later in main sketch.
// That is up to user to deal with specific implementation of SPI
// Note that AS3935 library requires this function to have exactly this signature
// and it can not be member function of any C++ class, which happens
// to be almost any Arduino library
// Please make sure your implementation of choice does not deal with CS pin,
// library takes care about it on it's own
byte SPItransfer(byte sendByte);

// Iterrupt handler for AS3935 irqs
// and flag variable that indicates interrupt has been triggered
// Variables that get changed in interrupt routines need to be declared volatile
// otherwise compiler can optimize them away, assuming they never get changed
void AS3935Irq();
volatile int AS3935IrqTriggered;

// First parameter - SPI transfer function, second - Arduino pin used for CS
// and finally third argument - Arduino pin used for IRQ
// It is good idea to chose pin that has interrupts attached, that way one can use
// attachInterrupt in sketch to detect interrupt
// Library internally polls this pin when doing calibration, so being an interrupt pin
// is not a requirement
AS3935 AS3935(SPItransfer,SS,2);

void setup()
{
  Serial.begin(9600);
  // first begin, then set parameters
  SPI.begin();
  // NB! chip uses SPI MODE1
  SPI.setDataMode(SPI_MODE1);
  // NB! max SPI clock speed that chip supports is 2MHz,
  // but never use 500kHz, because that will cause interference
  // to lightning detection circuit
  SPI.setClockDivider(SPI_CLOCK_DIV16);
  // and chip is MSB first
  SPI.setBitOrder(MSBFIRST);
  // reset all internal register values to defaults
  AS3935.reset();
  // and run calibration
  // if lightning detector can not tune tank circuit to required tolerance,
  // calibration function will return false
  if(!AS3935.calibrate())
    Serial.println("Tuning out of range, check your wiring, your sensor and make sure physics laws have not changed!");

  // since this is demo code, we just go on minding our own business and ignore the fact that someone divided by zero

  // first let's turn on disturber indication and print some register values from AS3935
  // tell AS3935 we are indoors, for outdoors use setOutdoors() function
  AS3935.setIndoors();
  // turn on indication of distrubers, once you have AS3935 all tuned, you can turn those off with disableDisturbers()
  AS3935.enableDisturbers();
  printAS3935Registers();
  AS3935IrqTriggered = 0;
  // Using interrupts means you do not have to check for pin being set continiously, chip does that for you and
  // notifies your code
  // demo is written and tested on ChipKit MAX32, irq pin is connected to max32 pin 2, that corresponds to interrupt 1
  // look up what pins can be used as interrupts on your specific board and how pins map to int numbers

  // ChipKit Max32 - irq connected to pin 2
  attachInterrupt(1,AS3935Irq,RISING);
  // uncomment line below and comment out line above for Arduino Mega 2560, irq still connected to pin 2
  // attachInterrupt(0,AS3935Irq,RISING);
}

void loop()
{
  // here we go into loop checking if interrupt has been triggered, which kind of defeats
  // the whole purpose of interrupts, but in real life you could put your chip to sleep
  // and lower power consumption or do other nifty things
  if(AS3935IrqTriggered)
  {
    // reset the flag
    AS3935IrqTriggered = 0;
    // first step is to find out what caused interrupt
    // as soon as we read interrupt cause register, irq pin goes low
    int irqSource = AS3935.interruptSource();
    // returned value is bitmap field, bit 0 - noise level too high, bit 2 - disturber detected, and finally bit 3 - lightning!
    if (irqSource & 0b0001)
      Serial.println("Noise level too high, try adjusting noise floor");
    if (irqSource & 0b0100)
      Serial.println("Disturber detected");
    if (irqSource & 0b1000)
    {
      // need to find how far that lightning stroke, function returns approximate distance in kilometers,
      // where value 1 represents storm in detector's near victinity, and 63 - very distant, out of range stroke
      // everything in between is just distance in kilometers
      int strokeDistance = AS3935.lightningDistanceKm();
      if (strokeDistance == 1)
        Serial.println("Storm overhead, watch out!");
      if (strokeDistance == 63)
        Serial.println("Out of range lightning detected.");
      if (strokeDistance < 63 && strokeDistance > 1)
      {
        Serial.print("Lightning detected ");
        Serial.print(strokeDistance,DEC);
        Serial.println(" kilometers away.");
      }
    }
  }
}

void printAS3935Registers()
{
  int noiseFloor = AS3935.getNoiseFloor();
  int spikeRejection = AS3935.getSpikeRejection();
  int watchdogThreshold = AS3935.getWatchdogThreshold();
  Serial.print("Noise floor is: ");
  Serial.println(noiseFloor,DEC);
  Serial.print("Spike rejection is: ");
  Serial.println(spikeRejection,DEC);
  Serial.print("Watchdog threshold is: ");
  Serial.println(watchdogThreshold,DEC);  
}

// this is implementation of SPI transfer that gets passed to AS3935
// you can (hopefully) wrap any SPI implementation in this
byte SPItransfer(byte sendByte)
{
  return SPI.transfer(sendByte);
}

// this is irq handler for AS3935 interrupts, has to return void and take no arguments
// always make code in interrupt handlers fast and short
void AS3935Irq()
{
  AS3935IrqTriggered = 1;
}
J'aimerais pouvoir récupérer le contenue de chaque "Serial.print" afin de me faire un petit programme qui m'indique quand la puce détecte de la foudre. Merci d'avance.
Avatar de l’utilisateur
MetalOS
Messages : 1492
Inscription : mar. 20/juin/2006 22:17
Localisation : Lorraine
Contact :

Re: Arduino & PureBasic

Message par MetalOS »

Je vient de faire un test avec mon code:

Code : Tout sélectionner

;by MetalOS


OpenSerialPort(1,"/dev/ttyACM0",9600,#PB_SerialPort_EvenParity,8,1,#PB_SerialPort_NoHandshake,1024,1024) ;Changer le port et la vitesse au besoin
OpenWindow(1,0,0,500,500,"Moniteur série Arduino",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
  ButtonGadget(1,5,5,70,25,"Effacer")
  EditorGadget(2,5,40,490,400,#PB_Editor_ReadOnly)

  Repeat
    event=WaitWindowEvent(20)
    Select event
      Case #PB_Event_CloseWindow
        CloseSerialPort(1)
      Case #PB_Event_Gadget
        Select EventGadget()
          Case 1
            SetGadgetText(2,"")
        EndSelect
    EndSelect
    If IsSerialPort(1)
      input=AvailableSerialPortInput(1)
      If input
        a$=Space(input)
        ReadSerialPortData(1,@a$,input)
        text$=GetGadgetText(2)+a$
        SetGadgetText(2,text$)

      EndIf
    EndIf
  Until event=#PB_Event_CloseWindow
Et j'ai utilisé l'exemple ReadAnalogVoltage fournit avec l'IDE Arduino. Seulement j'ai un problème de texte sur Mac. Voici le résultat avec le support de l'unicode.

Image

Et voici sans le support de l'unicode.

Image

Je ne comprend pas pourquoi ca fait ça. J'ai testé toutes les vitesse de port pour être sûr et j'ai toujours le même résultat. Ma version de PB et 64bits vous pensez que ca peut jouer ?
nico
Messages : 3702
Inscription : ven. 13/févr./2004 0:57

Re: Arduino & PureBasic

Message par nico »

Code : Tout sélectionner

G-Rom tu aurais un exemple de code Arduino qui permet d'envoyer le contenue des "Serial.println" vers un programme PureBasic
Je crois que c'est plutôt l'inverse que tu veux, car Serial.println permet déjà d'envoyer vers l'ordi, il faut un prog purebasic qui gère la liaison série.
nico
Messages : 3702
Inscription : ven. 13/févr./2004 0:57

Re: Arduino & PureBasic

Message par nico »

Cela donne quoi avec le moniteur série d'arduino d'abord pour commencer?
nico
Messages : 3702
Inscription : ven. 13/févr./2004 0:57

Re: Arduino & PureBasic

Message par nico »

Met ça : #PB_SerialPort_NoParity parce que l'autre me parait pas du tout correct.
Avatar de l’utilisateur
MetalOS
Messages : 1492
Inscription : mar. 20/juin/2006 22:17
Localisation : Lorraine
Contact :

Re: Arduino & PureBasic

Message par MetalOS »

Petite rectification de mon code ou tous fonctionne bien maintenant sans le support de l'unicode.

Code : Tout sélectionner

OpenSerialPort(1,"/dev/tty.usbmodemfa1341",9600,#PB_SerialPort_NoParity,8,1,#PB_SerialPort_RtsCtsHandshake, 4, 4) ;Changer le port et la vitesse au besoin
OpenWindow(1,0,0,500,500,"Moniteur série Arduino",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
  ButtonGadget(1,5,5,70,25,"Effacer")
  EditorGadget(2,5,40,490,400,#PB_Editor_ReadOnly)

  Repeat
    event=WaitWindowEvent()
    Select event
      Case #PB_Event_CloseWindow
        CloseSerialPort(1)
      Case #PB_Event_Gadget
        Select EventGadget()
          Case 1
            SetGadgetText(2,"")
        EndSelect
    EndSelect
    If IsSerialPort(1)
      input=AvailableSerialPortInput(1)
      If input
        a$=Space(input)
        ReadSerialPortData(1,@a$,input)
        text$=GetGadgetText(2)+a$
        SetGadgetText(2,text$)

      EndIf
    EndIf
  Until event=#PB_Event_CloseWindow
nico a écrit :Met ça : #PB_SerialPort_NoParity parce que l'autre me parait pas du tout correct.
Je l'avais déjà dans mon code.
nico
Messages : 3702
Inscription : ven. 13/févr./2004 0:57

Re: Arduino & PureBasic

Message par nico »

On peut connaitre les modifications que tu as faites?
Avatar de l’utilisateur
MetalOS
Messages : 1492
Inscription : mar. 20/juin/2006 22:17
Localisation : Lorraine
Contact :

Re: Arduino & PureBasic

Message par MetalOS »

J'ai changé uniquement #PB_SerialPort_NoHandshake par #PB_SerialPort_RtsCtsHandshake dans OpenSerial ().
Golfy
Messages : 423
Inscription : mer. 25/août/2004 15:14
Localisation : Grenoble
Contact :

Re: Arduino & PureBasic

Message par Golfy »

G-Rom a écrit :c'est pas pareil , ici on parle de communication série avec le hardware arduino. lui utilise une dll fournie. ;)
Je viens de voir le sujet : négatif (pas de DLL) ! tout en "série" également. Par contre j'ai fait un serveur qui convertit l'USB vers tout les softs connectés en TCP sur le port de mon serveur.
Du coup, pour un port USB connecté, je peux utiliser plusieurs applications sur plusieurs PC différents (tout passe par le réseau LAN/WIFI).

Avantage de ne pas utiliser de DLL : mon serveur fonctionne aussi sur Linux avec presque le même code (merci Fred / Purebasic).
(actuellement testé sur Debian 32 bits par un utilisateur Velbus)

D'autre part, pour aider un peu sur le sujet (si Arduino fonctionne comme Velbus) : il faut détecter dans le buffer un code de début (Velbus = 0F) et de fin ( Velbus = 04) de message. Un Message Velbus ressemble à [ 0F FB 'adr' 'len' 'function' datas CRC 04 ] : Je cherche donc 0F, a Offset+3 j'ai la longueur du message puis le CRC et le code de fin. Jusqu'à maintenant, Velbus n'envoie que des trames entières dans mon buffer sinon, je serais obligé de vérifier que mon message n'est pas à cheval sur 2 résultats de lecture.

Enfin, pour faire un serveur IP, c'est simple : tu copies les trames lues en Série/USB dans les connexions TCP. Inversement, les trames émises par un client TCP sont transmises sur le lien série/USB mais aussi (bien sur) sur les autres connexions TCP. Pour cela, j'adore les listes chainées de Purebasic...

Bon courage pour ce projet :)
Purebasic 5.30 full sous Windows XP (x86) et Win7 (64 bits), Linux Debian. Orientation réseaux, domotique
http://golfy.olympe.in/Teo-Tea/
Avatar de l’utilisateur
blendman
Messages : 2017
Inscription : sam. 19/févr./2011 12:46

Re: Arduino & PureBasic

Message par blendman »

salut

Je viens de voir qu'jn étudiant avait créé une console de jeu avec Arduino.
Je me disais que certains qui font des jeux en pb pourraient peut-être exporter leurs jeux, non ?

Plus d'info sur la console :
http://gamebuino.com/
G-Rom
Messages : 3627
Inscription : dim. 10/janv./2010 5:29

Re: Arduino & PureBasic

Message par G-Rom »

blendman a écrit :salut

Je viens de voir qu'jn étudiant avait créé une console de jeu avec Arduino.
Je me disais que certains qui font des jeux en pb pourraient peut-être exporter leurs jeux, non ?

Plus d'info sur la console :
http://gamebuino.com/
C'est pas possible, l'arduino seul n'a pas assez de puissance pour generé un signal VGA en 640x480 par exemple , pas assez de mémoire vive non plus pour stoker un buffer vidéo , on peu faire de l'affichage , mais cela se limite à la rigueur au n&b avec une résolution crado ^^
J'ai les pièces pour me faire une FuzeBox : http://www.ladyada.net/make/fuzebox/
Si tu bricole un peu en électronique , tu peu rajouté un peu de ram à ton arduino via le SPI avec des 23k256/512
Avatar de l’utilisateur
MetalOS
Messages : 1492
Inscription : mar. 20/juin/2006 22:17
Localisation : Lorraine
Contact :

Re: Arduino & PureBasic

Message par MetalOS »

Arduino a sortie une carte pour faire une console portable.

http://www.minimachines.net/actu/gamebu ... uino-16581
Avatar de l’utilisateur
graph100
Messages : 1318
Inscription : sam. 21/mai/2005 17:50

Re: Arduino & PureBasic

Message par graph100 »

Ca à l'air génial !

Si seulement j'avais du temps :roll:
_________________________________________________
Mon site : CeriseCode (Attention Chantier perpétuel ;))
Répondre