Gorgy Time

De Wiki LOGre
Aller à la navigation Aller à la recherche

Projet réalisé par fma38.

En cours

Présentation

Ayant récupéré une horloge Gorgy Time, disposant d'une entrée de synchronisation AFNOR IRIG.B NF S87-500, l'idée est de développer une horloge maître pour la maintenir à l'heure via un micro-contrôleur, connecté de son côté à internet pour se synchroniser en ntp.

AFNOR IRIG.B NF S87-500

D'après Wikipedia, la version B à un framerate de 1Hz. Je ne sais pas encore quel est le type de modulation, la porteuse, et le codage de cette horloge ; j'ai fait la demande au constructeur (pas encore de réponse), mais il y a toutes les chances que ce soit la version 122, c'est à dire une porteuse sinusoïdale modulée en amplitude, de fréquence 1kHz, et un encodage BCD.

Documentation de l'horloge

Architecture

L'horloge maître est construite autour d'une carte à base de RP2040, sous Micropython, en utilisant les puissants mécanismes de ce chip (PIO, DMA...).

La porteuse et sa modulation sont entièrement générées par 2 DMA, lesquels alimentent soit un PWM, soit un DAC construit avec un réseau R-2R alimenté par un PIO.

Le processeur n'a donc pour sa part qu'à préparer la trame à envoyer. Plusieurs options sont à tester :

  • si l'horloge incrémente elle-même le temps en absence de signal, on peut se contenter d'envoyer la trame lors de la mise en route ;
  • sinon, l'horloge maître devra incrémenter le temps en interne, et renvoyer la trame chaque seconde.

Dans tous les cas, pour éviter la dérive, on pourra se resynchroniser chaque jour à minuit sur un serveur ntp (et renvoyer une trame à l'horloge dans le premier cas).

Électronique

La solution à base de PWM a l'avantage de n'utiliser qu'une seule broche de la carte, mais nécessite de filtrer fortement le PWM avec un passe-bas pour obtenir un signal sinusoïdal propre.

Dans le cas du DAC, n broches de la carte sont nécessaires pour construire le signal de sortie, et 23 résistances pour créer le réseau R-2R, mais aucun filtrage n'est ensuite nécessaire.

Une fois le signal sinusoïdal obtenu, il reste à le rendre symétrique, avec une amplitude crête-crête de 2,2V maxi. Cela peut-être fait avec un ampli-op, comme suggéré par Edgar :

 Vin = (Vcc + Vout) / 2
 Vout = 2 . (Vin − Vcc/2)

Ou en ajoutant un condensateur de liaison en série pour éliminer la composante continue et un potentiomètre pour ajuster l'amplitude, comme suggéré par Marc.

Logiciel

Premier jet de code générant un timecode complet (avec un PWM) :

Cliquer sur le bouton à droite pour faire apparaître/disparaître le code...

<syntaxhighlight lang="Python">

  1. -*- coding: utf-8 -*-

""" IRIG.B122 timecode generator.

Written in Micropython for a RP2040-based board.

An IRIG.B122 timecode is written over a 1KHz sinusoidal carrier. The timecode consists of 100 bits, each bit is made of 10 carrier periods.

Bits are encoded as followed:

- a marker bit is 8 periods at full amplitude, and 2 periods of reduced (1/4) amplitude; - a 1 bit is 5 periods at full amplitude, and 5 periods of reduced (1/4) amplitude; - a 0 bit is 2 periods at full amplitude, and 8 periods of reduced (1/4) amplitude.

The waveforms are generated using a PWM (and a low pass filter). For each bit, a DMA feeds the PWM, and sends the 10 periods according to the bit encoding. To send the complete timecode, a second DMA feeds the first DMA with the address of each bit in the timecode. """

import math import array import uctypes import machine import rp2

LED_BUILTIN_PIN = 25 OUTPUT_PIN = 0

READ_ADD_TRIG_REG = 15 # see RP2040 datasheet "2.5.2.1 Aliases and Triggers" TREQ_PERMANENT = 0x3f

PWM_CH0_CC = 0x4005000c PWM_CH1_CC = 0x40050020 PWM_CH2_CC = 0x40050034 PWM_CH3_CC = 0x40050048 PWM_CH4_CC = 0x4005005c PWM_CH5_CC = 0x40050070 PWM_CH6_CC = 0x40050084 PWM_CH7_CC = 0x40050098

PWM_CHn_CC = [

   PWM_CH0_CC, PWM_CH0_CC,  # GPIO00, GPIO01
   PWM_CH1_CC, PWM_CH1_CC,
   PWM_CH2_CC, PWM_CH2_CC,
   PWM_CH3_CC, PWM_CH3_CC,
   PWM_CH4_CC, PWM_CH4_CC,
   PWM_CH5_CC, PWM_CH5_CC,
   PWM_CH6_CC, PWM_CH6_CC,
   PWM_CH7_CC, PWM_CH7_CC,
   PWM_CH0_CC, PWM_CH0_CC,
   PWM_CH1_CC, PWM_CH1_CC,
   PWM_CH2_CC, PWM_CH2_CC,
   PWM_CH3_CC, PWM_CH3_CC,
   PWM_CH4_CC, PWM_CH4_CC,
   PWM_CH5_CC, PWM_CH5_CC,
   PWM_CH6_CC, PWM_CH6_CC   # GPIO28, GPIO29

]

DREQ_PWM_WRAP0 = 0x18 DREQ_PWM_WRAP1 = 0x19 DREQ_PWM_WRAP2 = 0x1a DREQ_PWM_WRAP3 = 0x1b DREQ_PWM_WRAP4 = 0x1c DREQ_PWM_WRAP5 = 0x1d DREQ_PWM_WRAP6 = 0x1e DREQ_PWM_WRAP7 = 0x1f

DREQ_PWM_WRAPn = [

   DREQ_PWM_WRAP0, DREQ_PWM_WRAP0,  # GPIO00, GPIO01
   DREQ_PWM_WRAP1, DREQ_PWM_WRAP1,
   DREQ_PWM_WRAP2, DREQ_PWM_WRAP2,
   DREQ_PWM_WRAP3, DREQ_PWM_WRAP3,
   DREQ_PWM_WRAP4, DREQ_PWM_WRAP4,
   DREQ_PWM_WRAP5, DREQ_PWM_WRAP5,
   DREQ_PWM_WRAP6, DREQ_PWM_WRAP6,
   DREQ_PWM_WRAP7, DREQ_PWM_WRAP7,
   DREQ_PWM_WRAP0, DREQ_PWM_WRAP0,
   DREQ_PWM_WRAP1, DREQ_PWM_WRAP1,
   DREQ_PWM_WRAP2, DREQ_PWM_WRAP2,
   DREQ_PWM_WRAP3, DREQ_PWM_WRAP3,
   DREQ_PWM_WRAP4, DREQ_PWM_WRAP4,
   DREQ_PWM_WRAP5, DREQ_PWM_WRAP5,
   DREQ_PWM_WRAP6, DREQ_PWM_WRAP6   # GPIO28, GPIO29

]

BIT_SHIFT = [

   0, 16,  # GPIO00, GPIO01
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,
   0, 16,  # GPIO28, GPIO29

]

F_CPU = 125_000_000 # 125MHz

IRIG_CARRIER_FREQ = 1_000 # IRIG.B carrier clock (1kHz) NB_SAMPLES_PER_PERIOD = 256 # nb sample in a single period NB_PERIODS_PER_BIT = 10 # nb periods in a single IRIG.B122 bit

PWM_FREQ = IRIG_CARRIER_FREQ * NB_SAMPLES_PER_PERIOD # Hz

OFFSET = (F_CPU / PWM_FREQ) // 2 LARGE_AMPLITUDE = OFFSET - 1 SMALL_AMPLITUDE = LARGE_AMPLITUDE // 4

CARRIER_ON = [round(OFFSET+LARGE_AMPLITUDE*math.sin(2*math.pi*t/NB_SAMPLES_PER_PERIOD)) for t in range(NB_SAMPLES_PER_PERIOD)] CARRIER_OFF = [round(OFFSET+SMALL_AMPLITUDE*math.sin(2*math.pi*t/NB_SAMPLES_PER_PERIOD)) for t in range(NB_SAMPLES_PER_PERIOD)]

BIT_MARKER_WAVE = array.array('I') for b in int(0.8 * NB_PERIODS_PER_BIT) * CARRIER_ON + int(0.2 * NB_PERIODS_PER_BIT) * CARRIER_OFF:

   BIT_MARKER_WAVE.append(b << BIT_SHIFT[OUTPUT_PIN])

print(f"DEBUG::BIT_MARKER_WAVE address = {uctypes.addressof(BIT_MARKER_WAVE)}")

BIT_0_WAVE = array.array('I') for b in int(0.2 * NB_PERIODS_PER_BIT) * CARRIER_ON + int(0.8 * NB_PERIODS_PER_BIT) * CARRIER_OFF:

   BIT_0_WAVE.append(b << BIT_SHIFT[OUTPUT_PIN])

print(f"DEBUG::BIT_0_WAVE address = {uctypes.addressof(BIT_0_WAVE)}")

BIT_1_WAVE = array.array('I') for b in int(0.5 * NB_PERIODS_PER_BIT) * CARRIER_ON + int(0.5 * NB_PERIODS_PER_BIT) * CARRIER_OFF:

   BIT_1_WAVE.append(b << BIT_SHIFT[OUTPUT_PIN])

print(f"DEBUG::BIT_1_WAVE address = {uctypes.addressof(BIT_1_WAVE)}")


class IrigB122:

   """
   """
   def __init__(self, pwmPin):
       """
       """
       self._pwmPin = pwmPin
       self._dmaPwm = rp2.DMA()
       self._dmaPwm.active(False)
       #self._dmaPwm.irq(self._dmaPwmIsr, hard=True)
       print(f"DMA PWM channel = {self._dmaPwm.channel}")
       self._dmaFrame = rp2.DMA()
       self._dmaFrame.active(False)
       #self._dmaFrame.irq(self._dmaFrameIsr)  # only 1 hard interupt to avoid conflict
       print(f"DMA Frame channel = {self._dmaFrame.channel}")
       self._pwm = machine.PWM(machine.Pin(pwmPin, machine.Pin.OUT), freq=PWM_FREQ, duty_u16=0)
       self._frame = None
   # def _dmaPwmIsr(self, dma):
   #     """
   #     """
   #     print("DEBUG::_dmaPwmIsr::dma.read =", dma.read)
   #
   # def _dmaFrameIsr(self, dma):
   #     """
   #     """
   #     print("DEBUG::_dmaFrameIsr::dma.read =", dma.read)
   def start(self, timecode):
       """ Start generating IRIG.B122 timecode
       """
       self._frame = array.array('I')
       for b in timecode:
           if b == 'P':
               self._frame.append(uctypes.addressof(BIT_MARKER_WAVE))
           else if b in ('I', 'E', '0'):
               self._frame.append(uctypes.addressof(BIT_0_WAVE))
           else if b == '1':
               self._frame.append(uctypes.addressof(BIT_1_WAVE))
       self._frame.append(0)  # mark end of frame
       print(f"DEBUG::frame address = {uctypes.addressof(self._frame)} ({self._frame})")
       dmaPwmCtrl = self._dmaPwm.pack_ctrl(enable=True,
                                           high_pri=True,
                                           size=2,
                                           inc_read=True,
                                           inc_write=False,
                                           ring_size=0, ring_sel=False,
                                           chain_to=self._dmaFrame.channel,
                                           treq_sel=DREQ_PWM_WRAPn[self._pwmPin],
                                           irq_quiet=True,  #False,
                                           bswap=False,
                                           sniff_en=False,
                                           write_err=False,
                                           read_err=False)
       self._dmaPwm.config(write=PWM_CHn_CC[self._pwmPin],
                           count=NB_PERIODS_PER_BIT*NB_SAMPLES_PER_PERIOD,
                           ctrl=dmaPwmCtrl)
       dmaFrameCtrl = self._dmaFrame.pack_ctrl(enable=True,
                                               high_pri=True,
                                               size=2,
                                               inc_read=True,
                                               inc_write=False,
                                               ring_size=0, ring_sel=False,
                                               chain_to=self._dmaFrame.channel,  # disable chaining
                                               treq_sel=TREQ_PERMANENT,          # unpaced transfert, synchronization is done by PWM wrap
                                               irq_quiet=True,  #False,
                                               bswap=False,
                                               sniff_en=False,
                                               write_err=False,
                                               read_err=False)
       self._dmaFrame.config(read=self._frame,
                             write=self._dmaPwm.registers[READ_ADD_TRIG_REG:],  # see https://github.com/micropython/micropython/issues/16083
                             count=1,
                             ctrl=dmaFrameCtrl)
                             # trigger=True)  # start DMA
       print("INFO::Start")
       self._dmaFrame.active(True)  # start DMA
   def cancel(self):
       """
       """
       self._dmaPwm.active(False)    # cancel DMA
       self._dmaFrame.active(False)  # cancel DMA
   def isBusy(self):
       """
       """
       return self._dmaFrame.read < uctypes.addressof(self._frame) + 4 * len(self._frame)


def main():

   """
   # See: https://en.wikipedia.org/wiki/IRIG_timecode#IRIG_timecode
   # P: position identifier (marker bit)
   # I: index marker (0 bit)
   # E: empty bit (0 bit)
   # 0: bit clear (0 bit)
   # 1: bit set (1 bit)
   # Example: 2024-10-21 14:10:07 (Day of year=295)
   timecode = "P1110I000P0000I100EP0010I10EEP1010I1001P01EEEEEEEPEEEEEEEEEPEEEEEEEEEPEEEEEEEEEPEEEEEEEEEPEEEEEEEEEP"
   #            |||| ||| |||| |||  |||| ||   |||| |||| ||
   #               7   0    0   1     4  1      5    9  2
   """
   irigb122 = IrigB122(OUTPUT_PIN)
   try:
       timecode = "P1110I000P0000I100EP0010I10EEP1010I1001P01EEEEEEEPEEEEEEEEEPEEEEEEEEEPEEEEEEEEEPEEEEEEEEEPEEEEEEEEEP"
       irigb122.start(timecode)
       while irigb122.isBusy():
           pass
   finally:
       print("INFO::End")
       irigb122.cancel()


if __name__ == "__main__":

   main()

</syntaxhighlight>

Librairies

Liens