「Arduino Mega 2560 LESSON:9 サーボ」の版間の差分

提供:yonewiki
編集の要約なし
編集の要約なし
 
(同じ利用者による、間の9版が非表示)
70行目: 70行目:


 接続図は以下のとおりです。
 接続図は以下のとおりです。
[[ファイル:Mega2560 L09 01 接続図.png|380px||none|接続図]]
 完成図
[[ファイル:Mega2560 L09 02 完成図.jpg|380px||none|完成図]]
 またPCB図も作っておきました。
[[ファイル:Mega2560 L09 03 PCB図.png|380px||none|PCB図]]
 3DPreview図
[[ファイル:Mega2560 L09 04 3DReview図.png|380px||none|3DReview図]]




268行目: 287行目:
   // 16MHz / 8 = 2MHz
   // 16MHz / 8 = 2MHz
   // 1カウント = 0.5µs
   // 1カウント = 0.5µs
   OCR5A = pulseWidthUs * 2 - 1;
   OCR5A = pulseWidthUs * 2 - 1;//(*(volatile uint16_t *)(0x128))= 2999 と同じ。
  //OCR5Aは0x128レジスタを示す名前定義


   // CTCモード(OCR5A一致でカウンタをクリア)
   // CTCモード(OCR5A一致でカウンタをクリア)
   TCCR5B |= (1 << WGM52);
   TCCR5B |= (1 << WGM52);//WGM52 = 3 00000001→00001000 (*(volatile uint8_t *)(0x121)) = 8 と同じ
  // 00000000 OR  00001000 = 00001000 TCCR5Bは0x121のレジスタを示す名前定義です。


   // 比較一致A割り込みを有効化
   // 比較一致A割り込みを有効化
   TIMSK5 |= (1 << OCIE5A);
   TIMSK5 |= (1 << OCIE5A);//OCIE5A = 1 00000001→00000010 (*(volatile uint8_t *)(0x73)) = 2 と同じ
  // 00000000 OR  00000010 = 00000010 TIMSK5は0x73のレジスタを示す名前定義です。


   // プリスケーラ8でタイマー開始
   // プリスケーラ8でタイマー開始
   TCCR5B |= (1 << CS51);
   TCCR5B |= (1 << CS51);//CS51 = 1 (*(volatile uint8_t *)(0x121)) = 10  と同じ
  // 00001000 OR  00000010 = 00001010


   interrupts();
   interrupts();
283行目: 306行目:


// Timer5比較一致A割り込み
// Timer5比較一致A割り込み
ISR(TIMER5_COMPA_vect) {
ISR(TIMER5_COMPA_vect) { //ISR(__vector_47)
 
/*
void __vector_47(void)
    __attribute__((signal, used, externally_visible));
 
void __vector_47(void) {
    // 割り込み処理
}
属性 コンパイラへの指示
signal AVRの割り込み処理関数としてコンパイルする
used 通常のコードから呼ばれていなくても、この関数を生成する
externally_visible 外部から参照される可能性がある関数として扱う
 
1.TCNT5 が0からカウントを開始する。
2.TCNT5 == OCR5A になる。
3.比較一致Aの割り込み要求が発生する。
4.割り込みが許可されていれば、CPUが __vector_47() を実行する。
5.CTCモードにより TCNT5 が0に戻り、再びカウントを始める。
*/


   if (nextHigh) {
   if (nextHigh) {
314行目: 356行目:
C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr
C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr


<freescript></script><div class="hljs-wrap"><pre data-label="Arduino Code" class="pre-wrap">
<code class="cpp">/* Copyright (c) 2002,2005,2007 Marek Michalkiewicz
  Copyright (c) 2007, Dean Camera


  All rights reserved.
[[Arduino Mega 2560 LESSON:9 サーボ interrupt.h]]


  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:


  * Redistributions of source code must retain the above copyright
■<avr/io.h>
    notice, this list of conditions and the following disclaimer.


  * Redistributions in binary form must reproduce the above copyright
C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.


  * Neither the name of the copyright holders nor the names of
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.


  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
[[ Arduino Mega 2560 LESSON:9 サーボ io.h]]
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE. */


/* $Id$ */


#ifndef _AVR_INTERRUPT_H_
■<avr/iom2560.h>
#define _AVR_INTERRUPT_H_


#include <avr/io.h>
C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr


#if !defined(__DOXYGEN__) && !defined(__STRINGIFY)
/* Auxiliary macro for ISR_ALIAS(). */
#define __STRINGIFY(x) #x
#endif /* !defined(__DOXYGEN__) */


/**
[[ Arduino Mega 2560 LESSON:9 サーボ iom2560.h]]
\file
\@{
*/




/** \name Global manipulation of the interrupt flag
■<avr/iomxx0_1.h>


    The global interrupt flag is maintained in the I bit of the status
C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr
    register (SREG).


    Handling interrupts frequently requires attention regarding atomic
    access to objects that could be altered by code running within an
    interrupt context, see <util/atomic.h>.


    Frequently, interrupts are being disabled for periods of time in
[[ Arduino Mega 2560 LESSON:9 サーボ iomxx0_1.h]]
    order to perform certain operations without being disturbed; see
    \ref optim_code_reorder for things to be taken into account with
    respect to compiler optimizations.
*/


#if defined(__DOXYGEN__)
/** \def sei()
    \ingroup avr_interrupts


    Enables interrupts by setting the global interrupt mask. This function
 上記のプログラムのように待ち時間をクロックによってカウントするタイマーを用いて、そのタイマーが一致したら割り込み処理を発生させる方式にすると、安定してサーボの舵を変更できます。
    actually compiles into a single line of assembly, so there is no function
    call overhead.  However, the macro also implies a <i>memory barrier</i>
    which can cause additional loss of optimization.


    In order to implement atomic access to multi-byte objects,
    consider using the macros from <util/atomic.h>, rather than
    implementing them manually with cli() and sei().
*/
#define sei()
#else  /* !DOXYGEN */
# define sei()  __asm__ __volatile__ ("sei" ::: "memory")
#endif /* DOXYGEN */


#if defined(__DOXYGEN__)
 さらに発展させて
/** \def cli()
    \ingroup avr_interrupts


    Disables all interrupts by clearing the global interrupt mask. This function
    actually compiles into a single line of assembly, so there is no function
    call overhead.  However, the macro also implies a <i>memory barrier</i>
    which can cause additional loss of optimization.


    In order to implement atomic access to multi-byte objects,
<freescript></script><div class="hljs-wrap"><pre data-label="Arduino Code" class="pre-wrap">
    consider using the macros from <util/atomic.h>, rather than
<code class="cpp">const uint8_t servoPin = 45;  // OC5B
    implementing them manually with cli() and sei().
const uint16_t pulseWidthUs = 1600;
*/
const uint16_t periodUs = 20000;
#define cli()
#else  /* !DOXYGEN */
# define cli()  __asm__ __volatile__ ("cli" ::: "memory")
#endif /* DOXYGEN */


void setup() {
  pinMode(servoPin, OUTPUT);


/** \name Macros for writing interrupt handler functions */
  noInterrupts();
 
 
#if defined(__DOXYGEN__)
/** \def ISR(vector [, attributes])
    \ingroup avr_interrupts


    Introduces an interrupt handler function (interrupt service
  // Timer5を初期化
    routine) that runs with global interrupts initially disabled
  TCCR5A = 0; //レジスタ0x120
    by default with no attributes specified.
  TCCR5B = 0; //レジスタ0x121
  TCNT5 = 0; //レジスタ0x124


    The attributes are optional and alter the behaviour and resultant
  // 16MHz / 8 = 2MHz(1カウント = 0.5µs)
    generated code of the interrupt routine. Multiple attributes may
  // Fast PWMモード14:TOP = ICR5
    be used for a single function, with a space seperating each
  ICR5 = periodUs * 2 - 1;    // 39999 ICR5:レジスタ0x126
    attribute.


    Valid attributes are ISR_BLOCK, ISR_NOBLOCK, ISR_NAKED and
  // HIGH時間を1500µsに設定
    ISR_ALIASOF(vect).
  OCR5B = pulseWidthUs * 2;  // 3000 OCR5B:レジスタ0x12A


    \c vector must be one of the interrupt vector names that are
  // OC5Bを非反転PWM出力に設定
    valid for the particular MCU type.
  TCCR5A |= (1 << COM5B1);//COM5B1=5 TCCR5A=00100000
*/
#  define ISR(vector, [attributes])
#else  /* real code */


#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4)
  // Fast PWMモード14(WGM53:0 = 1110)
#  define __INTR_ATTRS used, externally_visible
  TCCR5A |= (1 << WGM51); //WGM51=1 TCCR5A=00100010←00100000 Or 00000010
#else /* GCC < 4.1 */
  TCCR5B |= (1 << WGM53) | (1 << WGM52); //WGM52=3, WGM53=4 TCCR5B=00011000←00000000 Or 00001000 Or 00010000
#  define __INTR_ATTRS used
#endif


#ifdef __cplusplus
  // 分周比8でタイマー開始
#  define ISR(vector, ...)            \
  TCCR5B |= (1 << CS51); //CS51=1 TCCR5B=00011010←00011000 Or 00000010 0.5μsec
    extern "C" void vector (void) __attribute__ ((signal,__INTR_ATTRS)) __VA_ARGS__; \
    void vector (void)
#else
#  define ISR(vector, ...)            \
    void vector (void) __attribute__ ((signal,__INTR_ATTRS)) __VA_ARGS__; \
    void vector (void)
#endif


#endif /* DOXYGEN */
/*
Fast PWMモード14(WGM53:0 = 1110)
TOP = ICR5、OC5Bは非反転PWM出力


#if defined(__DOXYGEN__)
1. TCNT5 = 0 で新しいPWM周期が始まり、D45がHIGHになる。
/** \def SIGNAL(vector)
2. TCNT5 = OCR5B(3000)で比較一致し、D45がLOWになる。
    \ingroup avr_interrupts
3. TCNT5 = ICR5(39999)までカウントする。
4. 次のタイマークロックでTCNT5が0に戻り、再びD45がHIGHになる。
5. 以後、同じ動作を繰り返す。


    Introduces an interrupt handler function that runs with global interrupts
クロック:
    initially disabled.
CPUクロック = 16MHz
分周比 = 8(CS52:0 = 010)
Timer5クロック = 16MHz / 8 = 2MHz
1カウント = 0.5µs


    This is the same as the ISR macro without optional attributes.
PWM周期 = (39999 + 1) × 0.5µs = 20000µs
    \deprecated Do not use SIGNAL() in new code. Use ISR() instead.
HIGH時間 = 3000 × 0.5µs = 1500µs
LOW時間 = 18500µs
*/
*/
#  define SIGNAL(vector)
  interrupts();
#else  /* real code */
}


#ifdef __cplusplus
void loop() {
#  define SIGNAL(vector) \
    extern "C" void vector(void) __attribute__ ((signal, __INTR_ATTRS)); \
    void vector (void)
#else
#  define SIGNAL(vector) \
    void vector (void) __attribute__ ((signal, __INTR_ATTRS)); \
    void vector (void)
#endif


#endif /* DOXYGEN */
  OCR5B = 1500 * 2;
  delay(5000);


#if defined(__DOXYGEN__)
  for(int i = 1500; i > 999; i--){
/** \def EMPTY_INTERRUPT(vector)
    OCR5B = i * 2;
    \ingroup avr_interrupts
    delay(1);
  }


    Defines an empty interrupt handler function. This will not generate
  for(int i = 1000; i < 2001; i++){
    any prolog or epilog code and will only return from the ISR. Do not
     OCR5B = i * 2;
    define a function body as this will define it for you.
     delay(1);
     Example:
  }
     \code EMPTY_INTERRUPT(ADC_vect);\endcode */
#  define EMPTY_INTERRUPT(vector)
#else  /* real code */


#ifdef __cplusplus
  for(int i = 2000; i > 999; i--){
#  define EMPTY_INTERRUPT(vector)                \
     OCR5B = i * 2;
    extern "C" void vector(void) __attribute__ ((signal,naked,__INTR_ATTRS));   \
     delay(1);
    void vector (void) { __asm__ __volatile__ ("reti" ::); }
  }
#else
#  define EMPTY_INTERRUPT(vector)                \
     void vector (void) __attribute__ ((signal,naked,__INTR_ATTRS));   \
     void vector (void) { __asm__ __volatile__ ("reti" ::); }
#endif


#endif /* DOXYGEN */
  for(int i = 1000; i < 2001; i++){
    OCR5B = i * 2;
    delay(1);
  }


#if defined(__DOXYGEN__)
  for(int i = 2000; i > 1499; i--){
/** \def ISR_ALIAS(vector, target_vector)
    OCR5B = i * 2;
    \ingroup avr_interrupts
    delay(1);
  }


    Aliases a given vector to another one in the same manner as the
    ISR_ALIASOF attribute for the ISR() macro. Unlike the ISR_ALIASOF
    attribute macro however, this is compatible for all versions of
    GCC rather than just GCC version 4.2 onwards.


    \note This macro creates a trampoline function for the aliased
}
    macro.  This will result in a two cycle penalty for the aliased
</code></pre></div><script></freescript>
    vector compared to the ISR the vector is aliased to, due to the
    JMP/RJMP opcode used.
 
    \deprecated
    For new code, the use of ISR(..., ISR_ALIASOF(...))  is
    recommended.
 
    Example:
    \code
    ISR(INT0_vect)
    {
        PORTB = 42;
    }
 
    ISR_ALIAS(INT1_vect, INT0_vect);
    \endcode
   
*/
#  define ISR_ALIAS(vector, target_vector)
#else /* real code */
 
#ifdef __cplusplus
#  if defined(__AVR_MEGA__) && __AVR_MEGA__
#    define ISR_ALIAS(vector, tgt) extern "C" void vector (void) \
__attribute__((signal, naked, __INTR_ATTRS)); \
void vector (void) { asm volatile ("jmp " __STRINGIFY(tgt) ::); }
#  else /* !__AVR_MEGA */
#    define ISR_ALIAS(vector, tgt) extern "C" void vector (void) \
__attribute__((signal, naked, __INTR_ATTRS)); \
void vector (void) { asm volatile ("rjmp " __STRINGIFY(tgt) ::); }
#  endif  /* __AVR_MEGA__ */
#else   /* !__cplusplus */
#  if defined(__AVR_MEGA__) && __AVR_MEGA__
#  define ISR_ALIAS(vector, tgt) void vector (void) \
__attribute__((signal, naked, __INTR_ATTRS)); \
void vector (void) { asm volatile ("jmp " __STRINGIFY(tgt) ::); }
#  else /* !__AVR_MEGA */
#  define ISR_ALIAS(vector, tgt) void vector (void) \
__attribute__((signal, naked, __INTR_ATTRS)); \
void vector (void) { asm volatile ("rjmp " __STRINGIFY(tgt) ::); }
#  endif  /* __AVR_MEGA__ */
#endif /* __cplusplus */
 
#endif /* DOXYGEN */


#if defined(__DOXYGEN__)
/** \def reti()
    \ingroup avr_interrupts


    Returns from an interrupt routine, enabling global interrupts. This should
 更にピンの状態変更もハードウェアでやる方式もあります。
    be the last command executed before leaving an ISR defined with the ISR_NAKED
    attribute.


    This macro actually compiles into a single line of assembly, so there is
    no function call overhead.
*/
#  define reti()
#else  /* !や
#  define reti()  __asm__ __volatile__ ("reti" ::)
#endif /* DOXYGEN */


#if defined(__DOXYGEN__)
TIMSK5 |= (1 << TOIE5);  // Timer5オーバーフロー割り込みを許可
/** \def BADISR_vect
    \ingroup avr_interrupts


    \code #include <avr/interrupt.h> \endcode


    This is a vector which is aliased to __vector_default, the vector
 を追加すれば、上記に以下の割り込み関数が動くようにすることもできます。
    executed when an ISR fires with no accompanying ISR handler. This
    may be used along with the ISR() macro to create a catch-all for
    undefined but used ISRs for debugging purposes.
*/
#  define BADISR_vect
#else  /* !DOXYGEN */
#  define BADISR_vect __vector_default
#endif /* DOXYGEN */


/** \name ISR attributes */


#if defined(__DOXYGEN__)
ISR(TIMER5_OVF_vect) { … }
/** \def ISR_BLOCK
    \ingroup avr_interrupts


    Identical to an ISR with no attributes specified. Global
    interrupts are initially disabled by the AVR hardware when
    entering the ISR, without the compiler modifying this state.


    Use this attribute in the attributes parameter of the ISR macro.
 44ピン以外にも3つのピンが同じようなことができることに対応しています。Mega2560はね。
*/
#  define ISR_BLOCK


/** \def ISR_NOBLOCK
    \ingroup avr_interrupts


    ISR runs with global interrupts initially enabled. The interrupt
  Arduinoピン 出力比較チャネル    比較レジスタ
    enable flag is activated by the compiler as early as possible
D46        OC5A                OCR5A
    within the ISR to ensure minimal processing delay for nested
D45        OC5B                OCR5B
    interrupts.
D44        OC5C                OCR5C


    This may be used to create nested ISRs, however care should be
    taken to avoid stack overflows, or to avoid infinitely entering
    the ISR for those cases where the AVR hardware does not clear the
    respective interrupt flag before entering the ISR.


    Use this attribute in the attributes parameter of the ISR macro.
 Arduino IDEで.inoファイルで記述した場合はArduino.hが読み込まれるのでinterrupt.hのヘッダの読み込みは省略できますが、Cppファイルに記述した場合は省略することはできません。
*/
#  define ISR_NOBLOCK


/** \def ISR_NAKED
    \ingroup avr_interrupts


    ISR is created with no prologue or epilogue code. The user code is
 サーボの勉強をするというこのレッスンでは割り込みというWindowsプログラミングでも滅多に登場しないコードが登場していることに気を付けたいところですね。
    responsible for preservation of the machine state including the
    SREG register, as well as placing a reti() at the end of the
    interrupt routine.


    Use this attribute in the attributes parameter of the ISR macro.
*/
#  define ISR_NAKED


/** \def ISR_ALIASOF(target_vector)
Mega2560はTimer5ではD44,45,46他にもTimerが3種類あって3ピンづつあって全部で12種類のピンで同じことができるようになっています。
    \ingroup avr_interrupts


    The ISR is linked to another ISR, specified by the vect parameter.
    This is compatible with GCC 4.2 and greater only.


    Use this attribute in the attributes parameter of the ISR macro.
  タイマー    Arduino Mega2560の出力ピン
*/
  Timer1      D11、D12、D13
# define ISR_ALIASOF(target_vector)
  Timer3      D2、D3、D5
#else /* !DOXYGEN */
  Timer4      D6、D7、D8
# define ISR_BLOCK
  Timer5     D44、D45、D46
# define ISR_NOBLOCK    __attribute__((interrupt))
# define ISR_NAKED     __attribute__((naked))
#  define ISR_ALIASOF(v) __attribute__((alias(__STRINGIFY(v))))
#endif /* DOXYGEN */
 
/* \@} */
 
#endif
</code></pre></div><script></freescript>
 
 
■<avr/io.h>
 
C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr
 
 
[[ Arduino Mega 2560 LESSON:9 サーボ io.h]]




 ながくなってしまいました。
タイマー自体は他にも2基あり全部で6基体制です。使いたい場合はさらに調べるなりGPTに聞くなりしてみて下さい。


 
 


[[Arduino Mega 2560]]に戻る。
[[Arduino Mega 2560]]に戻る。

2026年10月11日 (日) 22:53時点における最新版

Arduino Mega 2560に戻る。

概要

 サーボを使った課題です。


 接続図は以下のとおりです。


接続図


 完成図

完成図


 またPCB図も作っておきました。


PCB図


 3DPreview図

3DReview図


 コードは以下のようなものです。

//www.elegoo.com
//2018.12.19
#include <Servo.h>
Servo myservo;

void setup(){
  myservo.attach(9);
  myservo.write(90);// move servos to center position -> 90°
} 
void loop(){
  myservo.write(90);// move servos to center position -> 90°
  delay(500);
  myservo.write(30);// move servos to center position -> 60°
  delay(500);
  myservo.write(90);// move servos to center position -> 90°
  delay(500);
  myservo.write(150);// move servos to center position -> 120°
  delay(500);
}

 サーボライブラリを使った角度の調整です。サーボの位置を瞬時に角度を変えていくという内容のコードですね。サーボの舵の部分を自分に向けて置いた場合の表現で以後、話を進めます。左とか右とか言う表現をしますが、自分に舵を向けた状態から見て左と右とか言ってるんだなぁって思って下さい。


 サーボは赤と黒にあたる線で電源を供給します。赤は+5Vに黒にあたる茶色の線は、GNDへ接続します。サーボの信号線である橙色の線では、パルス波を受け取り角度を調整しています。ライブラリを使わずにまずはパルス波を送ってみましょう。


// SG90サーボ制御
// Servoライブラリ不使用
// タイマー割り込み処理なし

const int servoPin = 9;  // サーボ信号線:D9

void setup() {
  pinMode(servoPin, OUTPUT);
  digitalWrite(servoPin, LOW);
}

void loop() {

  // サーボ信号をHIGHにする
  digitalWrite(servoPin, HIGH);

  // 1500マイクロ秒待つ(中央位置)
  delayMicroseconds(1500);

  // サーボ信号をLOWにする
  digitalWrite(servoPin, LOW);

  // 次のパルスまで待つ
  delayMicroseconds(18500);
}


 このように1500μsecのONと18500μsecのOffを繰り返すパルス波を送ると概ね真ん中の位置でキープしますが、少し不安定であるためサーボがピクピク震えます。1000μsecのONと19000μsecだと左に振れた状態をキープします


  • 1500μsecのONと18500μsecのOff:真ん中
  • 1000μsecのONと19000μsecのOff:左
  • 2000μsecのONと18000μsecのOff:右


 以下のようにすると、左右にサーボがうごきます。左も右も45度くらいしか動かないので、完全に横に向いた状態にはならないですね。


// SG90サーボ制御
// Servoライブラリ不使用
// タイマー割り込み処理なし
// 左右振り

const int servoPin = 9;  // サーボ信号線:D9

void setup() {
  pinMode(servoPin, OUTPUT);
  digitalWrite(servoPin, LOW);
}

void loop() {

  for(int i = 1000; i < 2000; i++){
    // サーボ信号をHIGHにする
    digitalWrite(servoPin, HIGH);

    // 1500マイクロ秒待つ(左位置から右位置へ)
    delayMicroseconds(i);

    // サーボ信号をLOWにする
    digitalWrite(servoPin, LOW);

    // 次のパルスまで待つ
    delayMicroseconds(19000 - i);
  }
  for(int i = 2000; i > 1000; i--){
    // サーボ信号をHIGHにする
    digitalWrite(servoPin, HIGH);

    // 1500マイクロ秒待つ(右位置から左位置へ)
    delayMicroseconds(i);

    // サーボ信号をLOWにする
    digitalWrite(servoPin, LOW);

    // 次のパルスまで待つ
    delayMicroseconds(19000 - i);
  }

}


 サーボライブラリを使わなくても動かすこと自体はできますが、これでは途中で処理を入れる都度、パルス幅が変わって位置が不安定になっていきます。そこで割り込みという技術を使います。


 以下のようにライブラリを使って真ん中に設定するとものすごく安定しています。舵をさわってもほとんど振動を感じません。


#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(9);
  myservo.writeMicroseconds(1500);
}

void loop() {
}


 上記のコードは非常に安定します。


void setup() {
  pinMode(servoPin, OUTPUT);
  digitalWrite(servoPin, LOW);
}

void loop() {
  noInterrupts();

  digitalWrite(9, HIGH);
  delayMicroseconds(1500);
  digitalWrite(9, LOW);

  interrupts();

  delayMicroseconds(18500);
}


 上記のようなコードにすると少し改善されます。舵を触るとかすかに振動を感じます。チャットGPTによるとこれは、


 Arduino Mega2560の標準環境では、Timer0のオーバーフロー割り込みが代表例です。Timer0は通常、約1.024msごとにオーバーフローし、millis() や micros() などの時間管理に使われます。とのことでしたので、delayMicrosecondsだけで制御してもTime0のオーバーフローによる割り込みが入っていたのが、noInterrupts();という命令によって割り込みが禁止された期間が作られたことによって少しだけ安定したのではないかという見立てです。なんだかよくわからないことを言われているように感じるでしょうけれど、とにかく小手先の割り込み禁止という手法をもってしてもサーボライブラリの安定性に負けているコードであったということです。


 では、どうすればいいのかという解決編に近づいていきたいと思います。


#include <avr/interrupt.h>

const uint8_t servoPin = 9;

// HIGH期間:1500µs(中央位置)
const uint16_t pulseWidthUs = 1500;

// 信号周期:20000µs(50Hz)
const uint16_t periodUs = 20000;

// 次の割り込みでHIGHにするか、LOWにするか
volatile bool nextHigh = true;

void setup() {
  pinMode(servoPin, OUTPUT);
  digitalWrite(servoPin, LOW);

  noInterrupts();

  // Timer5の設定を初期化
  TCCR5A = 0;
  TCCR5B = 0;
  TCNT5 = 0;

  // 16MHz / 8 = 2MHz
  // 1カウント = 0.5µs
  OCR5A = pulseWidthUs * 2 - 1;//(*(volatile uint16_t *)(0x128))= 2999 と同じ。
  //OCR5Aは0x128レジスタを示す名前定義

  // CTCモード(OCR5A一致でカウンタをクリア)
  TCCR5B |= (1 << WGM52);//WGM52 = 3 00000001→00001000 (*(volatile uint8_t *)(0x121)) = 8 と同じ
  // 00000000 OR  00001000 = 00001000 TCCR5Bは0x121のレジスタを示す名前定義です。

  // 比較一致A割り込みを有効化
  TIMSK5 |= (1 << OCIE5A);//OCIE5A = 1 00000001→00000010 (*(volatile uint8_t *)(0x73)) = 2 と同じ
  // 00000000 OR  00000010 = 00000010 TIMSK5は0x73のレジスタを示す名前定義です。

  // プリスケーラ8でタイマー開始
  TCCR5B |= (1 << CS51);//CS51 = 1 (*(volatile uint8_t *)(0x121)) = 10  と同じ
  // 00001000 OR  00000010 = 00001010 

  interrupts();
}

// Timer5比較一致A割り込み
ISR(TIMER5_COMPA_vect) { //ISR(__vector_47)

/*
void __vector_47(void)
    __attribute__((signal, used, externally_visible));

void __vector_47(void) {
    // 割り込み処理
}
属性	コンパイラへの指示
signal	AVRの割り込み処理関数としてコンパイルする
used	通常のコードから呼ばれていなくても、この関数を生成する
externally_visible	外部から参照される可能性がある関数として扱う

1.TCNT5 が0からカウントを開始する。
2.TCNT5 == OCR5A になる。
3.比較一致Aの割り込み要求が発生する。
4.割り込みが許可されていれば、CPUが __vector_47() を実行する。
5.CTCモードにより TCNT5 が0に戻り、再びカウントを始める。
*/

  if (nextHigh) {
    digitalWrite(servoPin, HIGH);

    // 次はHIGH期間の終了時に割り込み
    OCR5A = pulseWidthUs * 2 - 1;

    nextHigh = false;
  }
  else {
    digitalWrite(servoPin, LOW);

    // 次はLOW期間の終了時に割り込み
    OCR5A = (periodUs - pulseWidthUs) * 2 - 1;

    nextHigh = true;
  }
}

void loop() {
  // サーボ信号はTimer5割り込みが生成する
  // ここでは何もしない
}


■<avr/interrupt.h>

C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr


Arduino Mega 2560 LESSON:9 サーボ interrupt.h


■<avr/io.h>

C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr


Arduino Mega 2560 LESSON:9 サーボ io.h


■<avr/iom2560.h>

C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr


Arduino Mega 2560 LESSON:9 サーボ iom2560.h


■<avr/iomxx0_1.h>

C:\Users\(UserID)\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\avr\include\avr


Arduino Mega 2560 LESSON:9 サーボ iomxx0_1.h


 上記のプログラムのように待ち時間をクロックによってカウントするタイマーを用いて、そのタイマーが一致したら割り込み処理を発生させる方式にすると、安定してサーボの舵を変更できます。


 さらに発展させて


const uint8_t servoPin = 45;  // OC5B
const uint16_t pulseWidthUs = 1600;
const uint16_t periodUs = 20000;

void setup() {
  pinMode(servoPin, OUTPUT);

  noInterrupts();

  // Timer5を初期化
  TCCR5A = 0; //レジスタ0x120
  TCCR5B = 0; //レジスタ0x121
  TCNT5 = 0; //レジスタ0x124

  // 16MHz / 8 = 2MHz(1カウント = 0.5µs)
  // Fast PWMモード14:TOP = ICR5
  ICR5 = periodUs * 2 - 1;    // 39999 ICR5:レジスタ0x126

  // HIGH時間を1500µsに設定
  OCR5B = pulseWidthUs * 2;   // 3000 OCR5B:レジスタ0x12A

  // OC5Bを非反転PWM出力に設定
  TCCR5A |= (1 << COM5B1);//COM5B1=5 TCCR5A=00100000

  // Fast PWMモード14(WGM53:0 = 1110)
  TCCR5A |= (1 << WGM51); //WGM51=1 TCCR5A=00100010←00100000 Or 00000010
  TCCR5B |= (1 << WGM53) | (1 << WGM52); //WGM52=3, WGM53=4 TCCR5B=00011000←00000000 Or 00001000 Or 00010000

  // 分周比8でタイマー開始
  TCCR5B |= (1 << CS51); //CS51=1 TCCR5B=00011010←00011000 Or 00000010 0.5μsec

/*
Fast PWMモード14(WGM53:0 = 1110)
TOP = ICR5、OC5Bは非反転PWM出力

1. TCNT5 = 0 で新しいPWM周期が始まり、D45がHIGHになる。
2. TCNT5 = OCR5B(3000)で比較一致し、D45がLOWになる。
3. TCNT5 = ICR5(39999)までカウントする。
4. 次のタイマークロックでTCNT5が0に戻り、再びD45がHIGHになる。
5. 以後、同じ動作を繰り返す。

クロック:
CPUクロック = 16MHz
分周比 = 8(CS52:0 = 010)
Timer5クロック = 16MHz / 8 = 2MHz
1カウント = 0.5µs

PWM周期 = (39999 + 1) × 0.5µs = 20000µs
HIGH時間 = 3000 × 0.5µs = 1500µs
LOW時間 = 18500µs
*/
  interrupts();
}

void loop() {

  OCR5B = 1500 * 2;
  delay(5000);

  for(int i = 1500; i > 999; i--){
    OCR5B = i * 2;
    delay(1);
  }

  for(int i = 1000; i < 2001; i++){
    OCR5B = i * 2;
    delay(1);
  }

  for(int i = 2000; i > 999; i--){
    OCR5B = i * 2;
    delay(1);
  }

  for(int i = 1000; i < 2001; i++){
    OCR5B = i * 2;
    delay(1);
  }

  for(int i = 2000; i > 1499; i--){
    OCR5B = i * 2;
    delay(1);
  }


}


 更にピンの状態変更もハードウェアでやる方式もあります。


TIMSK5 |= (1 << TOIE5);  // Timer5オーバーフロー割り込みを許可


 を追加すれば、上記に以下の割り込み関数が動くようにすることもできます。


ISR(TIMER5_OVF_vect) { … }


 44ピン以外にも3つのピンが同じようなことができることに対応しています。Mega2560はね。


Arduinoピン 出力比較チャネル    比較レジスタ 
D46         OC5A                OCR5A
D45         OC5B                OCR5B
D44         OC5C                OCR5C


 Arduino IDEで.inoファイルで記述した場合はArduino.hが読み込まれるのでinterrupt.hのヘッダの読み込みは省略できますが、Cppファイルに記述した場合は省略することはできません。


 サーボの勉強をするというこのレッスンでは割り込みというWindowsプログラミングでも滅多に登場しないコードが登場していることに気を付けたいところですね。


Mega2560はTimer5ではD44,45,46他にもTimerが3種類あって3ピンづつあって全部で12種類のピンで同じことができるようになっています。


タイマー    Arduino Mega2560の出力ピン
Timer1      D11、D12、D13
Timer3      D2、D3、D5
Timer4      D6、D7、D8
Timer5      D44、D45、D46


タイマー自体は他にも2基あり全部で6基体制です。使いたい場合はさらに調べるなりGPTに聞くなりしてみて下さい。

 

Arduino Mega 2560に戻る。