2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

衝撃の事実!!ATtinyではprintfが使えない?!

Last updated at Posted at 2022-04-18

今日はとても恐ろしい話をしたいと思います。

ATtinyで開発を行っていたところ

mySerial.printf(" Done. Gradient value = %.10fd\n", gradient);

という部分でエラーが発生した。。。

なんで(・・?

しかもエラー分が

'class SoftwareSerial' has no member named 'printf'; did you mean 'print'?

【翻訳】
え?おまえ「printf」ってなに?いや「print」の間違いだろ?!

いやちゃうわ!!
printfだぞ!

printf!!

しかし何回やってもエラー分が

'class SoftwareSerial' has no member named 'printf'; did you mean 'print'?

【翻訳】
だからー!!「printf」ってなに?「print」の間違いだろ?!何回やってんの?まじで!!

え?嘘だろ?お前今まで何回もprintfやってたやん(;・∀・)
ちょっと調べてみるか。。。。

おい嘘だろ?!ATtinyでは「printf」使えないの?!
(すんません。もしかしたら自分のやり方が悪いだけかもしれません)

ということで海外のサイトからprintfのやり方を頂戴致しました。
以下の文を追加すると使用できるようです。
↑すみません嘘です。。
下のやつもエラーで使えませんでした。

#include <SoftwareSerial.h>
#include <inttypes.h>

#define PD0  0
#define PD1  1

class mySerial : public SoftwareSerial {

  public:
    mySerial(uint8_t receivePin, uint8_t transmitPin,
      bool inverse_logic = false) :
      SoftwareSerial(receivePin, transmitPin,inverse_logic) {}

    virtual size_t write(uint8_t byte) {
      return SoftwareSerial::write(byte);
    }

    int printf(char* fmt, ...) {
      char buff[256];
      va_list args;
      va_start(args, fmt);
      int return_status = vsnprintf(buff, sizeof(buff), fmt, args);
      va_end(args);
      uint8_t *s = (uint8_t *)&buff;
      while (*s) write(*s++);
      return return_status;
    }
};

mySerial m(PD0,PD1);

void setup() {
  m.begin(9600);

  m.print("Hello from Arduino!\n");
  m.printf("%s 0x%x %d %4o\n", "Hello", 0x80, 333, 128);
  m.printf("%16s x\n", "Hello");
  m.printf("%08x %e\n", 0x1234, 1e-10);

  m.printf("Floats:\n");
  m.printf("%.3lf %e\n", 3.14159f, 3.14159f);

}

上のやつは私の環境では使えませんでした。
どうも浮動小数点などを使いたい場合は以下のやり方でいいみたいです。

void setup() {
  Double abc = 1.23456789;
  Serial.begin(9600);
  Serial.print(abc,5);//1.23456が表示される
}

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?