Mozzi  version v2.0
sound synthesis library for Arduino
twi_nonblock.h
1 /*
2  * twi_nonblock.h
3  *
4  * This file is part of Mozzi.
5  *
6  * Copyright 2012-2024 Marije Baalman and the Mozzi Team
7  *
8  * Mozzi is licensed under the GNU Lesser General Public Licence (LGPL) Version 2.1 or later.
9  *
10  */
11 
12 
13 #ifndef TWI_NONBLOCK_H_
14 #define TWI_NONBLOCK_H_
15 
16 #include <hardware_defines.h>
17 // Added by TB2014 for Teensy 3 port
18 #if IS_AVR() // this code is only for AVRs
19 
20 #include "Arduino.h"
21 #include <compat/twi.h>
22 
23 #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
24 #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
25 
26 // --- twi reading variables
27  #ifndef TWI_FREQ
28  #define TWI_FREQ 100000L
29  #endif
30 
31  #ifndef TWI_BUFFER_LENGTH
32  #define TWI_BUFFER_LENGTH 32
33  #endif
34 
35  #define TWI_READY 0
36  #define TWI_PRE_MRX 1
37  #define TWI_MRX 2
38  #define TWI_PRE_MTX 3
39  #define TWI_MTX 4
40  #define TWI_SRX 5
41  #define TWI_STX 6
42 
43 static volatile uint8_t twi_state;
44 static volatile uint8_t twi_oldstate;
45 // static uint8_t twiint_masrw;
46 static uint8_t twi_slarw;
47 
48 static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
49 static volatile uint8_t twi_masterBufferIndex;
50 static uint8_t twi_masterBufferLength;
51 
52 static volatile uint8_t twi_error;
53 
54 #define BUFFER_LENGTH 32
55 static uint8_t rxBuffer[BUFFER_LENGTH];
56 static uint8_t rxBufferIndex = 0;
57 static uint8_t rxBufferLength = 0;
58 
59 static uint8_t txAddress = 0;
60 static uint8_t txBuffer[BUFFER_LENGTH];
61 static uint8_t txBufferIndex = 0;
62 static uint8_t txBufferLength = 0;
63 
64 static uint8_t transmitting;
65 
66 
67 void initialize_twi_nonblock();
68 
69 uint8_t twowire_requestFrom(uint8_t address, uint8_t quantity);
70 void twowire_beginTransmission( uint8_t address );
71 void twowire_send( uint8_t data );
72 uint8_t twowire_endTransmission(void);
73 
74 /// non-blocking functions:
75 uint8_t twi_initiateReadFrom(uint8_t address, uint8_t length);
76 void twi_continueReadFrom();
77 
78 uint8_t twi_readMasterBuffer( uint8_t* data, uint8_t length );
79 
80 uint8_t twi_initiateWriteTo(uint8_t address, uint8_t* data, uint8_t length );
81 void twi_continueWriteTo();
82 
83 
84 void twi_reply(uint8_t ack);
85 void twi_stop(void);
86 void twi_releaseBus(void);
87 
88 /// blocking versions:
89 uint8_t twi_readFromBlocking(uint8_t address, uint8_t* data, uint8_t length);
90 uint8_t twi_writeToBlocking(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait);
91 
92 #endif
93 
94 #if !defined _MOZZI_TWI_HEADER_ONLY
95 #include "internal/twi_nonblock.hpp"
96 #endif
97 
98 #endif