wiki:MAX6675

Version 1 (modified by sgk, 12 years ago) ( diff )

--

MAX665

MAX6675.pde

#include "SPI.h"

#define VCC  8
#define GND  9
#define SLAVE  10

void
setup()
{
  pinMode(GND, OUTPUT);
  pinMode(VCC, OUTPUT);
  digitalWrite(GND, LOW); 
  digitalWrite(VCC, HIGH);
  Serial.begin(9600);
  SPI_Master.begin(SLAVE);
}

void
loop()
{
  int value;

  delay(500);
  SPI_Master.enable(SLAVE);
  value = SPI_Master.read() << 8;
  value |= SPI_Master.read();
  SPI_Master.disable();
  
  if ((value & 0x0004) != 0)
    Serial.println("Error");
  else
    Serial.println((value >> 3) * 0.25);
}

SPI.cpp

#include "SPI.h"

boolean SPI_Master_Class::initialized_ = false;
int SPI_Master_Class::enabled_ = -1;

void
SPI_Master_Class::begin(int slaveselecter) {
  if (!initialized_) {
    initialized_ = true;
    enabled_ = -1;
    pinMode(SS, OUTPUT);  // Must be set as OUTPUT before SPE is asserted.
    pinMode(MOSI, OUTPUT);
    pinMode(MISO, INPUT);
    digitalWrite(MISO, HIGH);  // Pull-up
    pinMode(SCK, OUTPUT);
    SPCR = (1<<SPE)|(1<<MSTR);  // SPE: SPI Enable; MSTR: Master
    byte garbage;
    garbage = SPSR;
    garbage = SPDR;
  }

  if (slaveselecter != SS)
    pinMode(slaveselecter, OUTPUT);
  digitalWrite(slaveselecter, HIGH);  // Disable
}

void
SPI_Master_Class::enable(int slaveselecter) {
  disable();
  digitalWrite(slaveselecter, LOW);
  enabled_ = slaveselecter;
}

void
SPI_Master_Class::disable() {
  if (enabled_ >= 0) {
    digitalWrite(enabled_, HIGH);
    enabled_ = -1;
  }
}

byte
SPI_Master_Class::write_and_read(byte data) const {
  SPDR = data;
  while (!(SPSR & (1<<SPIF)))
    ;
  return SPDR;
}

void
SPI_Master_Class::write(byte data) const {
  write_and_read(data);
}

byte
SPI_Master_Class::read() const {
  return write_and_read(0x00);
}

SPI_Master_Class SPI_Master;

SPI.h

#ifndef __SPI_H__
#define __SPI_H__

#include "WProgram.h"

class SPI_Master_Class {
public:
  static void begin(int slaveselecter);
  void enable(int slaveselecter);
  void disable();
  byte write_and_read(byte data) const;
  void write(byte data) const;
  byte read() const;

private:
  static boolean initialized_;
  static const int SS = 10;
  static const int MOSI = 11;
  static const int MISO = 12;
  static const int SCK = 13;
  static int enabled_;
};

extern SPI_Master_Class SPI_Master;

#endif //__SPI_H__

Attachments (3)

Download all attachments as: .zip

Note: See TracWiki for help on using the wiki.