Hirdetés

Új hozzászólás Aktív témák

  • #70211840

    törölt tag

    Nem tudom mennyire illik a topicba (bár szerepel a címben), kezdőként programozási kérdésem volna.
    Szóljatok, ha off és menjek át a C++ programozás topicba.

    Elakadtam egy referencia átadásnál, nem értem miért nem csinálja meg.
    Egy egyszerű I2C Scan a példa, aminél a main-ben hoznék létre és indítanék a TwoWire-t és egy másik osztályban szeretném ezt használni.
    Viszont egyetlen eszközt sem talál, míg visszapakolva a loop()-ba a WireScanner::scanI2C tartalmát, rendben fut és listázza az eszközök címeit.

    Mit rontok el?

    Test.ino
    #include <Wire.h>
    #include "WireScanner.h"
    TwoWire wirePort(PB11, PB10);  // STM32F103 I2C_2
    WireScanner ws(wirePort);
    void setup() {
      Serial.begin(9600);
      wirePort.begin();
    }
    void loop() {
      ws.scanI2C();
      delay(5000);  // wait 5 seconds for next scan
    }

    WireScanner.h
    #ifndef WireScanner_h
    #define WireScanner_h
    #include <Wire.h>
    class WireScanner {
    public:
      WireScanner(TwoWire& i2cPort);
      void scanI2C(void);
    };
    #endif

    WireScanner.cpp
    #include "WireScanner.h"
    TwoWire _i2cPort;
    WireScanner::WireScanner(TwoWire& i2cPort) {
      _i2cPort = i2cPort;
    }
    void WireScanner::scanI2C(void) {
      byte error, address;
      int nDevices;
      Serial.println("Scanning...");
      nDevices = 0;
      for (address = 1; address < 127; address++) {
        _i2cPort.beginTransmission(address);
        error = _i2cPort.endTransmission();
        if (error == 0) {
          Serial.print("I2C device found at address 0x");
          if (address < 16)
            Serial.print("0");
          Serial.println(address, HEX);
          nDevices++;
        } else if (error == 4) {
          Serial.print("Unknown error at address 0x");
          if (address < 16)
            Serial.print("0");
          Serial.println(address, HEX);
        }
      }
      if (nDevices == 0)
        Serial.println("No I2C devices found");
      else
        Serial.println("done");
    }

Új hozzászólás Aktív témák