So-net無料ブログ作成

ATtiny85のタイマーを使う [Arduino]

生のATtiny85とDigisparkとではタイマーの使い方が違っていました。

C:\Users\(user)\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny\core_build_options.h より、
/*
  For various reasons, Timer 1 is a better choice for the millis timer on the
  '85 processor.
*/
#define TIMER_TO_USE_FOR_MILLIS                   1

Digisparkでは、やんごとなき理由でミリ秒のカウント用にタイマー1を使っているそうです。

タイマー0を使うか、タイマー1の割り込みを殺すかになります。

PWM使用(8bit高速PWM(TOP=0xff), 分周なし)の時のATtiny85用設定の覚え。
// PLLCSR - PLL制御/状態レジスタ (PLL Control and Status Register)
PLLCSR = B00000110;             // 0x06 (初期値)

// TIMSK - タイマ/カウンタ割り込み許可レジスタ (Timer/Counter Interrupt Mask Register)
TIMSK &= ~_BV(TOIE0);           // Timer0の割り込みを殺す場合
TIMSK &= ~_BV(TOIE1);           // Timer1の割り込みを殺す場合

// TCCR0A - タイマ/カウンタ0制御レジスタA (Timer/Counter0 Control Register A)
//         COM0A1 | COM0A0 | COM0B1 | COM0B0 | - | - | WGM01 | WGM00
TCCR0A = B10100011;             // OC0x比較一致でLow (表11-3参照)
                                // WGM02-0:8ビット高速PWM動作 (TOP値 $FF) (表11-5参照)

// TCCR0B - タイマ/カウンタ0制御レジスタB (Timer/Counter0 Control Register B)
//         FOC0A | FOC0B | - | - | WGM02 | CS02 | CS01 | CS00
TCCR0B = B00000001;             // CS02-1:前置分周なし (表11-6参照)

// TCCR1 - タイマ/カウンタ1制御レジスタ (Timer/Counter0 Control Register)
//         CTC1 | PWM1A | COM1A1 | COM1A0 | CS13 | CS12 | CS11 | CS10
TCCR1  = B01100001;             //  PWM動作A許可, OC1A比較一致でLow, ~OC1Aピン接続断 (表12-1参照), CK×16 (PCK)
                                //  PWM1A=1, COM1A1=1, COM1A0=0, CS13=0, CS12=0, CS11=0, CS10=1

// GTCCR - 一般タイマ/カウンタ制御レジスタ (General Timer/Counter Control Register)
//         TSM | PWM1B | COM1B1 | COM1B0 | FOC1B | FOC1A | PSR1 | PSR0
GTCCR  = B01100000;             //  PWM動作B許可, OC1B比較一致でLow, ~OC1Bピン接続断 (表12-1参照)
                                //  PWM1B=1, COM1B1=1, COM1B0=0
//OCR1C - タイマ/カウンタ1 比較Cレジスタ (Timer/Counter1 Output Compare Register C)
OCR1C  = 255;                   //  OCR1Cはタイマ/カウンタ1の最大値(比較一致での解除値)

// 高速PWM動作時に COM0x1 を 0 で標準ポート動作 (OC0x切断) (WGM02=0のとき)
// 高速PWM動作時に COM1x1 を 0 で標準ポート動作 (OC1x切断)

// TIFR - タイマ/カウンタ割り込み要求フラグ レジスタ (Timer/Counter Interrupt Flag Register)
while( !(TIFR & _BV(TOV0)) );   // タイマー0がオーバーフローするのを待つ
TIFR |= _BV(TOV0);              // Timer/Counter0 Overflow Flag をクリア 
                                //   (論理1を書くことによってもTOV0は解除(0)できる)
while( !(TIFR & _BV(TOV1)) );   // タイマー1がオーバーフローするのを待つ
TIFR |= _BV(TOV1);              // Timer/Counter1 Overflow Flag をクリア
                                //   (論理1を書くことによってもTOV1は解除(0)できる)

// タイマーを殺したときのdelay
void delayCentiseconds16M5Hz( uint16_t ds ) {       // 16.5MHz動作時 0.01sec単位のdelay
  while( ds-- )  _delay_loop_2( 41250 );            // 1MHzなら 2500
}

void delayCentiseconds16MHz( uint16_t ds ) {        // 16.5MHz動作時 0.01sec単位のdelay
  while( ds-- )  _delay_loop_2( 40000 );            // 1MHzなら 2500
}

(参考) wiring_private.h の cbi(), sbi()
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

digispark_wav.jpg
DigisparkでWAVファイル配列化したものを再生する。
// Digispark(Default 16.5MHz)で WAVファイル(8bit, 4kHz, monoral) を配列化したものを再生する。
#include <util/delay_basic.h>   // _delay_loop_2() を使うため
#include <avr/pgmspace.h>       // PROGMEM使用時のお約束
#include "hello4.h"             // 音声データ hello4[]  =「こんにちは」8bit,  4kHz,  monoral

void setup() {
  pinMode( 1, OUTPUT);          //  OC1A(PB1)
  TCCR1 = B01100001;            //  8ビット タイマ/カウンタ1用レジスタ (PWM動作A許可, OC1A比較一致でLow, ~OC1Aピン接続断)
  OCR1C = 255;                  //  タイマ/カウンタ1 比較Cレジスタ
  TIMSK &= ~_BV(TOIE1);         //  タイマ/カウンタ1溢れ割り込み許可(TOIE1) 取り消し
}

void loop() {
  playWav( hello4 );            // hello4[]を再生
  delayCentiseconds16M5Hz(100); // 100センチ秒 = 1秒まつ 
}

void playWav( const uint8_t d[] ) { 
  uint8_t  cyc;                                     // 次の1byte読み込むまでのサイクル数カウンタ(cyc)
  uint16_t i, len = pgm_read_word_near(&d[0x28]);   // データサイズ
  for( i = 0x2c; i < len;) {
    if(!(cyc = ++cyc % 16))  OCR1A =  pgm_read_byte_near(&d[ i++ ]);  // 8kHzの音声なら 除数を16→8へ
    while( !(TIFR & _BV(TOV1)) );                   // タイマのオーバーフロー待ち (256cycle @ 16.5MHz≒15.5usec毎)
    TIFR |= _BV(TOV1);                              // Timer/Counter1 Overflow Flag をクリア
  }
}

void delayCentiseconds16M5Hz( uint16_t ds ) {       // 16.5MHz動作時 0.01sec単位のdelay
  while( ds-- )  _delay_loop_2( 41250 );            // 1MHzなら 2500
}

nice!(0)  コメント(2)  トラックバック(0) 

nice! 0

コメント 2

Rickeli

В Сервисе диагностирует скважины, производит Обслуживание систем водоснабжения.

В компании вы можете купить КАНАЛИЗАЦИОННЫЕ ДРОБИЛКИ, Силосы для хранения сыпучих продуктов, Мешалка коническая, Термическая сушка осадков сточных вод, Водоприемный колодец, Тонкослойные модули (БМТ), Статические смесители, ОДЪЕМНЫЕ УСТРОЙСТВА И МЕТАЛЛОКОНСТРУКЦИИ Подъемники, ВОДООЧИСТНОЕ ОБОРУДОВАНИЕ Канализационные насосные станции (КНС), ПОДЪЕМНЫЕ УСТРОЙСТВА И МЕТАЛЛОКОНСТРУКЦИИ Металлоконструкции фермы, ОЧИСТКА ЛИВНЕВЫХ СТОЧНЫХ ВОД Песколовки тангенциальные, НАСОСНОЕ И КОМПРЕССОРНОЕ ОБОРУДОВАНИЕ (Грунфос, КСБ, Вило, КИТ, Взлёт, ТВП) Канализационный насос сухой установки, ВОДОПОДГОТОВКУ Сорбционная фильтрация, а также все для автомойки Система очистки воды для автомоек.

У нас вы найдете Обслуживание очистных сооружений, а также Коллектора, мы можем произвести Обустройство скважин под ключ. Бурение скважин на воду, Оценка запасов подземных вод, Водоснабжение частного дома.

Полная очистка скважин : <a href=https://gmgd.ru/> Обслуживание скважин</a>
by Rickeli (2018-08-30 18:30) 

DavidCouts

Gallagher 100 days 16 hrs ago #12


"If there is something inherently dangerous about feminism, then why do some people defend misogyny, sexism, white privilege and racism?" "I'd rather have a bunch of white males who are all misogynistic and racism-happy than a bunch of feminists in purple," she says. "No, you don't need to get to know all the feminists." "If there is something inherently dangerous about feminism, then why do some people defend misogyny, sexism, white privilege and racism?" "I'd rather have a bunch of white males who are all misogynistic and racism-happy than a bunch of feminists in purple," she says. "No, you don't need to get to know all the feminists."

ReplyFavorite 3 3 5


And what makes them racist? How do you see them attacking white men?


And what makes them racist? How do you see them attacking white men?

Anonymous 2 2 2 · Opinions

Jenny

3 2 4 · 7 years ago

Mamazie

2 1 1 · 25 months ago

Lola

0 0 · 23 days ago

Anonymous

0 0 · 23 days ago

Anonymous

0 0 · 23 days ago

Anonymous

The white dudes are fucking insane:

"Oh gee, I could've sworn that one of the other women had sex with all five men..."


If there are more than 5 white dudes in bed with you, you've got white privilege.

The white dudes are fucking insane: https://t.co/8yXxI9FZ0H The white dudes are fucking insane:"Oh gee, I could've sworn that one of the other women had sex with all five men..."If there are more than 5 white dudes in bed with you, you've got white privilege.

Anonymous 5 3 4 · 12 hours ago

jenny

Anonymous 5 3 4 · 12 hours ago

Lola

3 0 4 · 1 day ago

Anonymous

0 0 · 1 day ago

Anonymous

You're not helping your case. The ones who are actually violent tend to be the ones that have the power to control everyone.


I'll take the 5th option.

The 5th option. "I wouldn't like to get raped by the white girls of my dream college. Because it's gonna happen, don't you worry. It's gonna happen for a reason. You'll be okay. You'll do fine, trust me." You're not helping your case. The ones who are actually violent tend to be the ones that have the power to control everyone.I'l
<a href=https://www.grupo-huk.com/>예스카지노</a>
<a href=https://www.uzgitwebtasarim.com/>더킹카지노</a>

Greek debt slashed to junk status after China slowdown?

Sector analysts and banking analysts say that China's slowing economy could leave many of its banks vulnerable to sudden insolvency.

A Chinese banker is seen holding a money transfer terminal inside the headquarters of Citicorp in Shenzhen, China, January 17, 2015. REUTERS/Kim Kyung-Hoon

"We've heard the whispers that there could be a Chinese slowdown and that there could be some problems with China," said William F. Shinn, managing director of Wells Fargo Securities Inc in Toronto, Ontario, where he oversees $100 million in credit-rating and investment banking assets.

"And the question is - with interest rates in the future very negative - will those Chinese bank funds run out?"

Shinn noted in a research note that U.S. banks have increased their exposure to a range of Chinese banks by taking positions on U.S. dollar-denominated securities in recent years.

But he was less optimistic about financial institutions' capacity to protect themselves, given that Chinese regulators are "unfazed by bank-induced volatility and they have so little tolerance for bank failure," he said.

China is the world's second-largest lender, after the United States. It now accounts for about 27 percent of its banking debt, with most of the rest held by state-controlled institutions.

The central bank announced last November that it would impose restrictions on some lending to state-owned firms to prevent bank failures and boost its balance sheet as investors worry about a slowdown.

Last month, Citigroup Inc said it was cutting its forecast for Chinese lending as much as 45 percent, after the country's central bank cut short its plans to print new money through its newly created national bank.

China's Bank of China (BOC.UL) said last month it would not raise rates by April 16. Analysts at Credit Suisse said in May that they believed the BOC's plans would cause new bank failures of "moderate or high severity", and they pointed to the Bank of China's announcement last December that it would issue its first new bonds this year.

The Chinese Communist Party's ruling People's Bank of China (PBOC) said in November that it would take action against foreign money lenders in a bid to curb the threat of financial instability.

It gave no reason for its decision, but China's central bank is likely to increase interest rates at least for short-term assets, such as sovereign bonds, if the Chinese economy slows down as expected, analysts said.

That would also encourage financial stability authorities to take more action to prevent bank collapse. The PBOC does not publish its forecast for economic conditions, but it is expected to do so when Chin
by DavidCouts (2020-05-27 06:11) 

コメントを書く

お名前:
URL:
コメント:
画像認証:
下の画像に表示されている文字を入力してください。

トラックバック 0

Arduinoとスピーカだけで音声を出す|- ブログトップ

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。

この広告は180日新規投稿のないブログに表示されます