tiny.c


1
#include <stdint.h>
2
#include <avr/io.h>
3
#include <avr/wdt.h>
4
#include <avr/interrupt.h>
5
6
#define FAN_BIT    3
7
#define FAN_PORT  PORTA
8
// #define FAN_DDR    DDRA
9
10
 #define PM_BIT    PINA7
11
 #define PM_PIN    PINA
12
13
14
// Software-defines
15
#define ADMUX_REFS  ((0<<REFS1)|(0<<REFS0))
16
#define ADMUX_CH_MASK  7
17
#define ADCSRA_BASE_MASK ((1<<ADEN)|(1<<ADATE)|(1<<ADIF)|(1<<ADIE)|7)  // enable ADC, clear Interrupt Flag, enable ADC-Interrupts, select prescaler 7 == 1/128
18
#define GIMSK_INIT  (1<<PCIE1)
19
20
//  State-Bits
21
#define SB_ADC_NEWDAT  0
22
#define SB_SPI_NEWTX  1
23
#define SB_SPI_ACTIVE  2
24
#define SB_SPI_NEWRX  3
25
#define SB_SPI_TXVALID  4
26
27
28
// globale Variablen
29
volatile uint8_t state_bits = 0;
30
volatile uint8_t spi_cntr;
31
volatile uint8_t spi_tx_buf[5];
32
volatile uint8_t spi_rx_buf[6];
33
34
35
36
37
int main(void)
38
{
39
  // initialize Ports
40
  DDRA   = (1<<FAN_BIT);
41
  PORTA   = (1<<FAN_BIT);                // Fan is default on
42
  
43
  // initialize external interrupts
44
  PCMSK1   = (1<<PCINT9);                  // select PCINT1 for #SS-pin
45
  GIMSK   = GIMSK_INIT;                  // enable external interrupts
46
  
47
  // enable Interrupts
48
  sei();
49
  
50
    while(1)
51
    {
52
    }
53
}
54
55
ISR( PCINT1_vect )
56
{
57
  // SS-pin toggled
58
  if( !( PINB & (1<<PB1) ) )
59
  {
60
    // Slave selected
61
    spi_cntr  = 0;
62
    // enable SPI
63
    USISR  = (1<<USIOIF) | 0;              // reset InterruptFlag and USI-counter
64
    USICR  = (1<<USIOIE) | (1<<USIWM0) | (1<<USICS1);  // Enable USI-Overflow-Interrupt, select 3-Wire-Mode, set SPI-Mode 0
65
    DDRA  = (1<<FAN_BIT) | (1<<MISO_BIT);        // MISO-Pin is Output
66
    // transmit state
67
    uint8_t tmp = state_bits;
68
    USIDR  = tmp;
69
    state_bits = (tmp & ~(1<<SB_SPI_NEWRX)) | (1<<SB_SPI_ACTIVE);
70
  }
71
  else
72
  {
73
    // Slave unselsected => disable SPI
74
    USICR  = 0;                  // deactivate USI
75
    DDRA  = (1<<FAN_BIT) & ~(1<<MISO_BIT);    // set MISO-Pin as Input
76
77
    uint8_t tmp = state_bits;
78
    tmp &= ~(1<<SB_SPI_ACTIVE);
79
    if( spi_cntr <= 6 )
80
      tmp = ( tmp & ~(1<<SB_SPI_NEWTX) ) | (1<<SB_SPI_NEWRX);
81
    state_bits = tmp;
82
  }
83
}
84
85
ISR( USI_OVF_vect )
86
{
87
  FAN_PORT ^= (1<<FAN_BIT); // debug
88
  
89
  // SPI data transfer complete
90
  uint8_t state = spi_cntr;
91
  if( state <= 5 )
92
    spi_rx_buf[state] = USIBR;
93
  if( state < 5 )
94
    //USIDR = spi_tx_buf[state];
95
    USIDR = spi_rx_buf[state];    // empfangene Daten direkt wieder zurück schicken...
96
  if( state < 255 )
97
    state++;
98
  spi_cntr = state;
99
100
  FAN_PORT ^= (1<<FAN_BIT); // debug
101
}