Adafruit_SPITFT.cpp 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274
  1. /*!
  2. * @file Adafruit_SPITFT.cpp
  3. *
  4. * @mainpage Adafruit SPI TFT Displays (and some others)
  5. *
  6. * @section intro_sec Introduction
  7. *
  8. * Part of Adafruit's GFX graphics library. Originally this class was
  9. * written to handle a range of color TFT displays connected via SPI,
  10. * but over time this library and some display-specific subclasses have
  11. * mutated to include some color OLEDs as well as parallel-interfaced
  12. * displays. The name's been kept for the sake of older code.
  13. *
  14. * Adafruit invests time and resources providing this open source code,
  15. * please support Adafruit and open-source hardware by purchasing
  16. * products from Adafruit!
  17. * @section dependencies Dependencies
  18. *
  19. * This library depends on <a href="https://github.com/adafruit/Adafruit_GFX">
  20. * Adafruit_GFX</a> being present on your system. Please make sure you have
  21. * installed the latest version before using this library.
  22. *
  23. * @section author Author
  24. *
  25. * Written by Limor "ladyada" Fried for Adafruit Industries,
  26. * with contributions from the open source community.
  27. *
  28. * @section license License
  29. *
  30. * BSD license, all text here must be included in any redistribution.
  31. */
  32. #if !defined(__AVR_ATtiny85__) // Not for ATtiny, at all
  33. #include "Adafruit_SPITFT.h"
  34. #if defined(__AVR__)
  35. #if defined(__AVR_XMEGA__) //only tested with __AVR_ATmega4809__
  36. #define AVR_WRITESPI(x) for(SPI0_DATA = (x); (!(SPI0_INTFLAGS & _BV(SPI_IF_bp))); )
  37. #else
  38. #define AVR_WRITESPI(x) for(SPDR = (x); (!(SPSR & _BV(SPIF))); )
  39. #endif
  40. #endif
  41. #if defined(PORT_IOBUS)
  42. // On SAMD21, redefine digitalPinToPort() to use the slightly-faster
  43. // PORT_IOBUS rather than PORT (not needed on SAMD51).
  44. #undef digitalPinToPort
  45. #define digitalPinToPort(P) (&(PORT_IOBUS->Group[g_APinDescription[P].ulPort]))
  46. #endif // end PORT_IOBUS
  47. #if defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO))
  48. // #pragma message ("GFX DMA IS ENABLED. HIGHLY EXPERIMENTAL.")
  49. #include <Adafruit_ZeroDMA.h>
  50. #include "wiring_private.h" // pinPeripheral() function
  51. #include <malloc.h> // memalign() function
  52. #define tcNum 2 // Timer/Counter for parallel write strobe PWM
  53. #define wrPeripheral PIO_CCL // Use CCL to invert write strobe
  54. // DMA transfer-in-progress indicator and callback
  55. static volatile bool dma_busy = false;
  56. static void dma_callback(Adafruit_ZeroDMA *dma) {
  57. dma_busy = false;
  58. }
  59. #if defined(__SAMD51__)
  60. // Timer/counter info by index #
  61. static const struct {
  62. Tc *tc; // -> Timer/Counter base address
  63. int gclk; // GCLK ID
  64. int evu; // EVSYS user ID
  65. } tcList[] = {
  66. { TC0, TC0_GCLK_ID, EVSYS_ID_USER_TC0_EVU },
  67. { TC1, TC1_GCLK_ID, EVSYS_ID_USER_TC1_EVU },
  68. { TC2, TC2_GCLK_ID, EVSYS_ID_USER_TC2_EVU },
  69. { TC3, TC3_GCLK_ID, EVSYS_ID_USER_TC3_EVU },
  70. #if defined(TC4)
  71. { TC4, TC4_GCLK_ID, EVSYS_ID_USER_TC4_EVU },
  72. #endif
  73. #if defined(TC5)
  74. { TC5, TC5_GCLK_ID, EVSYS_ID_USER_TC5_EVU },
  75. #endif
  76. #if defined(TC6)
  77. { TC6, TC6_GCLK_ID, EVSYS_ID_USER_TC6_EVU },
  78. #endif
  79. #if defined(TC7)
  80. { TC7, TC7_GCLK_ID, EVSYS_ID_USER_TC7_EVU }
  81. #endif
  82. };
  83. #define NUM_TIMERS (sizeof tcList / sizeof tcList[0]) ///< # timer/counters
  84. #endif // end __SAMD51__
  85. #endif // end USE_SPI_DMA
  86. // Possible values for Adafruit_SPITFT.connection:
  87. #define TFT_HARD_SPI 0 ///< Display interface = hardware SPI
  88. #define TFT_SOFT_SPI 1 ///< Display interface = software SPI
  89. #define TFT_PARALLEL 2 ///< Display interface = 8- or 16-bit parallel
  90. // CONSTRUCTORS ------------------------------------------------------------
  91. /*!
  92. @brief Adafruit_SPITFT constructor for software (bitbang) SPI.
  93. @param w Display width in pixels at default rotation setting (0).
  94. @param h Display height in pixels at default rotation setting (0).
  95. @param cs Arduino pin # for chip-select (-1 if unused, tie CS low).
  96. @param dc Arduino pin # for data/command select (required).
  97. @param mosi Arduino pin # for bitbang SPI MOSI signal (required).
  98. @param sck Arduino pin # for bitbang SPI SCK signal (required).
  99. @param rst Arduino pin # for display reset (optional, display reset
  100. can be tied to MCU reset, default of -1 means unused).
  101. @param miso Arduino pin # for bitbang SPI MISO signal (optional,
  102. -1 default, many displays don't support SPI read).
  103. @return Adafruit_SPITFT object.
  104. @note Output pins are not initialized; application typically will
  105. need to call subclass' begin() function, which in turn calls
  106. this library's initSPI() function to initialize pins.
  107. */
  108. Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h,
  109. int8_t cs, int8_t dc, int8_t mosi, int8_t sck, int8_t rst, int8_t miso) :
  110. Adafruit_GFX(w, h), connection(TFT_SOFT_SPI), _rst(rst), _cs(cs), _dc(dc) {
  111. swspi._sck = sck;
  112. swspi._mosi = mosi;
  113. swspi._miso = miso;
  114. #if defined(USE_FAST_PINIO)
  115. #if defined(HAS_PORT_SET_CLR)
  116. #if defined(CORE_TEENSY)
  117. #if !defined(KINETISK)
  118. dcPinMask = digitalPinToBitMask(dc);
  119. swspi.sckPinMask = digitalPinToBitMask(sck);
  120. swspi.mosiPinMask = digitalPinToBitMask(mosi);
  121. #endif
  122. dcPortSet = portSetRegister(dc);
  123. dcPortClr = portClearRegister(dc);
  124. swspi.sckPortSet = portSetRegister(sck);
  125. swspi.sckPortClr = portClearRegister(sck);
  126. swspi.mosiPortSet = portSetRegister(mosi);
  127. swspi.mosiPortClr = portClearRegister(mosi);
  128. if(cs >= 0) {
  129. #if !defined(KINETISK)
  130. csPinMask = digitalPinToBitMask(cs);
  131. #endif
  132. csPortSet = portSetRegister(cs);
  133. csPortClr = portClearRegister(cs);
  134. } else {
  135. #if !defined(KINETISK)
  136. csPinMask = 0;
  137. #endif
  138. csPortSet = dcPortSet;
  139. csPortClr = dcPortClr;
  140. }
  141. if(miso >= 0) {
  142. swspi.misoPort = portInputRegister(miso);
  143. #if !defined(KINETISK)
  144. swspi.misoPinMask = digitalPinToBitMask(miso);
  145. #endif
  146. } else {
  147. swspi.misoPort = portInputRegister(dc);
  148. }
  149. #else // !CORE_TEENSY
  150. dcPinMask =digitalPinToBitMask(dc);
  151. swspi.sckPinMask =digitalPinToBitMask(sck);
  152. swspi.mosiPinMask=digitalPinToBitMask(mosi);
  153. dcPortSet =&(PORT->Group[g_APinDescription[dc].ulPort].OUTSET.reg);
  154. dcPortClr =&(PORT->Group[g_APinDescription[dc].ulPort].OUTCLR.reg);
  155. swspi.sckPortSet =&(PORT->Group[g_APinDescription[sck].ulPort].OUTSET.reg);
  156. swspi.sckPortClr =&(PORT->Group[g_APinDescription[sck].ulPort].OUTCLR.reg);
  157. swspi.mosiPortSet=&(PORT->Group[g_APinDescription[mosi].ulPort].OUTSET.reg);
  158. swspi.mosiPortClr=&(PORT->Group[g_APinDescription[mosi].ulPort].OUTCLR.reg);
  159. if(cs >= 0) {
  160. csPinMask = digitalPinToBitMask(cs);
  161. csPortSet = &(PORT->Group[g_APinDescription[cs].ulPort].OUTSET.reg);
  162. csPortClr = &(PORT->Group[g_APinDescription[cs].ulPort].OUTCLR.reg);
  163. } else {
  164. // No chip-select line defined; might be permanently tied to GND.
  165. // Assign a valid GPIO register (though not used for CS), and an
  166. // empty pin bitmask...the nonsense bit-twiddling might be faster
  167. // than checking _cs and possibly branching.
  168. csPortSet = dcPortSet;
  169. csPortClr = dcPortClr;
  170. csPinMask = 0;
  171. }
  172. if(miso >= 0) {
  173. swspi.misoPinMask=digitalPinToBitMask(miso);
  174. swspi.misoPort =(PORTreg_t)portInputRegister(digitalPinToPort(miso));
  175. } else {
  176. swspi.misoPinMask=0;
  177. swspi.misoPort =(PORTreg_t)portInputRegister(digitalPinToPort(dc));
  178. }
  179. #endif // end !CORE_TEENSY
  180. #else // !HAS_PORT_SET_CLR
  181. dcPort =(PORTreg_t)portOutputRegister(digitalPinToPort(dc));
  182. dcPinMaskSet =digitalPinToBitMask(dc);
  183. swspi.sckPort =(PORTreg_t)portOutputRegister(digitalPinToPort(sck));
  184. swspi.sckPinMaskSet =digitalPinToBitMask(sck);
  185. swspi.mosiPort =(PORTreg_t)portOutputRegister(digitalPinToPort(mosi));
  186. swspi.mosiPinMaskSet=digitalPinToBitMask(mosi);
  187. if(cs >= 0) {
  188. csPort = (PORTreg_t)portOutputRegister(digitalPinToPort(cs));
  189. csPinMaskSet = digitalPinToBitMask(cs);
  190. } else {
  191. // No chip-select line defined; might be permanently tied to GND.
  192. // Assign a valid GPIO register (though not used for CS), and an
  193. // empty pin bitmask...the nonsense bit-twiddling might be faster
  194. // than checking _cs and possibly branching.
  195. csPort = dcPort;
  196. csPinMaskSet = 0;
  197. }
  198. if(miso >= 0) {
  199. swspi.misoPort =(PORTreg_t)portInputRegister(digitalPinToPort(miso));
  200. swspi.misoPinMask=digitalPinToBitMask(miso);
  201. } else {
  202. swspi.misoPort =(PORTreg_t)portInputRegister(digitalPinToPort(dc));
  203. swspi.misoPinMask=0;
  204. }
  205. csPinMaskClr = ~csPinMaskSet;
  206. dcPinMaskClr = ~dcPinMaskSet;
  207. swspi.sckPinMaskClr = ~swspi.sckPinMaskSet;
  208. swspi.mosiPinMaskClr = ~swspi.mosiPinMaskSet;
  209. #endif // !end HAS_PORT_SET_CLR
  210. #endif // end USE_FAST_PINIO
  211. }
  212. /*!
  213. @brief Adafruit_SPITFT constructor for hardware SPI using the board's
  214. default SPI peripheral.
  215. @param w Display width in pixels at default rotation setting (0).
  216. @param h Display height in pixels at default rotation setting (0).
  217. @param cs Arduino pin # for chip-select (-1 if unused, tie CS low).
  218. @param dc Arduino pin # for data/command select (required).
  219. @param rst Arduino pin # for display reset (optional, display reset
  220. can be tied to MCU reset, default of -1 means unused).
  221. @return Adafruit_SPITFT object.
  222. @note Output pins are not initialized; application typically will
  223. need to call subclass' begin() function, which in turn calls
  224. this library's initSPI() function to initialize pins.
  225. */
  226. #if defined(ESP8266) // See notes below
  227. Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, int8_t cs,
  228. int8_t dc, int8_t rst) : Adafruit_GFX(w, h),
  229. connection(TFT_HARD_SPI), _rst(rst), _cs(cs), _dc(dc) {
  230. hwspi._spi = &SPI;
  231. }
  232. #else // !ESP8266
  233. Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, int8_t cs,
  234. int8_t dc, int8_t rst) : Adafruit_SPITFT(w, h, &SPI, cs, dc, rst) {
  235. // This just invokes the hardware SPI constructor below,
  236. // passing the default SPI device (&SPI).
  237. }
  238. #endif // end !ESP8266
  239. #if !defined(ESP8266)
  240. // ESP8266 compiler freaks out at this constructor -- it can't disambiguate
  241. // beteween the SPIClass pointer (argument #3) and a regular integer.
  242. // Solution here it to just not offer this variant on the ESP8266. You can
  243. // use the default hardware SPI peripheral, or you can use software SPI,
  244. // but if there's any library out there that creates a 'virtual' SPIClass
  245. // peripheral and drives it with software bitbanging, that's not supported.
  246. /*!
  247. @brief Adafruit_SPITFT constructor for hardware SPI using a specific
  248. SPI peripheral.
  249. @param w Display width in pixels at default rotation (0).
  250. @param h Display height in pixels at default rotation (0).
  251. @param spiClass Pointer to SPIClass type (e.g. &SPI or &SPI1).
  252. @param cs Arduino pin # for chip-select (-1 if unused, tie CS low).
  253. @param dc Arduino pin # for data/command select (required).
  254. @param rst Arduino pin # for display reset (optional, display reset
  255. can be tied to MCU reset, default of -1 means unused).
  256. @return Adafruit_SPITFT object.
  257. @note Output pins are not initialized in constructor; application
  258. typically will need to call subclass' begin() function, which
  259. in turn calls this library's initSPI() function to initialize
  260. pins. EXCEPT...if you have built your own SERCOM SPI peripheral
  261. (calling the SPIClass constructor) rather than one of the
  262. built-in SPI devices (e.g. &SPI, &SPI1 and so forth), you will
  263. need to call the begin() function for your object as well as
  264. pinPeripheral() for the MOSI, MISO and SCK pins to configure
  265. GPIO manually. Do this BEFORE calling the display-specific
  266. begin or init function. Unfortunate but unavoidable.
  267. */
  268. Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, SPIClass *spiClass,
  269. int8_t cs, int8_t dc, int8_t rst) : Adafruit_GFX(w, h),
  270. connection(TFT_HARD_SPI), _rst(rst), _cs(cs), _dc(dc) {
  271. hwspi._spi = spiClass;
  272. #if defined(USE_FAST_PINIO)
  273. #if defined(HAS_PORT_SET_CLR)
  274. #if defined(CORE_TEENSY)
  275. #if !defined(KINETISK)
  276. dcPinMask = digitalPinToBitMask(dc);
  277. #endif
  278. dcPortSet = portSetRegister(dc);
  279. dcPortClr = portClearRegister(dc);
  280. if(cs >= 0) {
  281. #if !defined(KINETISK)
  282. csPinMask = digitalPinToBitMask(cs);
  283. #endif
  284. csPortSet = portSetRegister(cs);
  285. csPortClr = portClearRegister(cs);
  286. } else { // see comments below
  287. #if !defined(KINETISK)
  288. csPinMask = 0;
  289. #endif
  290. csPortSet = dcPortSet;
  291. csPortClr = dcPortClr;
  292. }
  293. #else // !CORE_TEENSY
  294. dcPinMask = digitalPinToBitMask(dc);
  295. dcPortSet = &(PORT->Group[g_APinDescription[dc].ulPort].OUTSET.reg);
  296. dcPortClr = &(PORT->Group[g_APinDescription[dc].ulPort].OUTCLR.reg);
  297. if(cs >= 0) {
  298. csPinMask = digitalPinToBitMask(cs);
  299. csPortSet = &(PORT->Group[g_APinDescription[cs].ulPort].OUTSET.reg);
  300. csPortClr = &(PORT->Group[g_APinDescription[cs].ulPort].OUTCLR.reg);
  301. } else {
  302. // No chip-select line defined; might be permanently tied to GND.
  303. // Assign a valid GPIO register (though not used for CS), and an
  304. // empty pin bitmask...the nonsense bit-twiddling might be faster
  305. // than checking _cs and possibly branching.
  306. csPortSet = dcPortSet;
  307. csPortClr = dcPortClr;
  308. csPinMask = 0;
  309. }
  310. #endif // end !CORE_TEENSY
  311. #else // !HAS_PORT_SET_CLR
  312. dcPort = (PORTreg_t)portOutputRegister(digitalPinToPort(dc));
  313. dcPinMaskSet = digitalPinToBitMask(dc);
  314. if(cs >= 0) {
  315. csPort = (PORTreg_t)portOutputRegister(digitalPinToPort(cs));
  316. csPinMaskSet = digitalPinToBitMask(cs);
  317. } else {
  318. // No chip-select line defined; might be permanently tied to GND.
  319. // Assign a valid GPIO register (though not used for CS), and an
  320. // empty pin bitmask...the nonsense bit-twiddling might be faster
  321. // than checking _cs and possibly branching.
  322. csPort = dcPort;
  323. csPinMaskSet = 0;
  324. }
  325. csPinMaskClr = ~csPinMaskSet;
  326. dcPinMaskClr = ~dcPinMaskSet;
  327. #endif // end !HAS_PORT_SET_CLR
  328. #endif // end USE_FAST_PINIO
  329. }
  330. #endif // end !ESP8266
  331. /*!
  332. @brief Adafruit_SPITFT constructor for parallel display connection.
  333. @param w Display width in pixels at default rotation (0).
  334. @param h Display height in pixels at default rotation (0).
  335. @param busWidth If tft16 (enumeration in header file), is a 16-bit
  336. parallel connection, else 8-bit.
  337. 16-bit isn't fully implemented or tested yet so
  338. applications should pass "tft8bitbus" for now...needed to
  339. stick a required enum argument in there to
  340. disambiguate this constructor from the soft-SPI case.
  341. Argument is ignored on 8-bit architectures (no 'wide'
  342. support there since PORTs are 8 bits anyway).
  343. @param d0 Arduino pin # for data bit 0 (1+ are extrapolated).
  344. The 8 (or 16) data bits MUST be contiguous and byte-
  345. aligned (or word-aligned for wide interface) within
  346. the same PORT register (might not correspond to
  347. Arduino pin sequence).
  348. @param wr Arduino pin # for write strobe (required).
  349. @param dc Arduino pin # for data/command select (required).
  350. @param cs Arduino pin # for chip-select (optional, -1 if unused,
  351. tie CS low).
  352. @param rst Arduino pin # for display reset (optional, display reset
  353. can be tied to MCU reset, default of -1 means unused).
  354. @param rd Arduino pin # for read strobe (optional, -1 if unused).
  355. @return Adafruit_SPITFT object.
  356. @note Output pins are not initialized; application typically will need
  357. to call subclass' begin() function, which in turn calls this
  358. library's initSPI() function to initialize pins.
  359. Yes, the name is a misnomer...this library originally handled
  360. only SPI displays, parallel being a recent addition (but not
  361. wanting to break existing code).
  362. */
  363. Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, tftBusWidth busWidth,
  364. int8_t d0, int8_t wr, int8_t dc, int8_t cs, int8_t rst, int8_t rd) :
  365. Adafruit_GFX(w, h), connection(TFT_PARALLEL), _rst(rst), _cs(cs), _dc(dc) {
  366. tft8._d0 = d0;
  367. tft8._wr = wr;
  368. tft8._rd = rd;
  369. tft8.wide = (busWidth == tft16bitbus);
  370. #if defined(USE_FAST_PINIO)
  371. #if defined(HAS_PORT_SET_CLR)
  372. #if defined(CORE_TEENSY)
  373. tft8.wrPortSet = portSetRegister(wr);
  374. tft8.wrPortClr = portClearRegister(wr);
  375. #if !defined(KINETISK)
  376. dcPinMask = digitalPinToBitMask(dc);
  377. #endif
  378. dcPortSet = portSetRegister(dc);
  379. dcPortClr = portClearRegister(dc);
  380. if(cs >= 0) {
  381. #if !defined(KINETISK)
  382. csPinMask = digitalPinToBitMask(cs);
  383. #endif
  384. csPortSet = portSetRegister(cs);
  385. csPortClr = portClearRegister(cs);
  386. } else { // see comments below
  387. #if !defined(KINETISK)
  388. csPinMask = 0;
  389. #endif
  390. csPortSet = dcPortSet;
  391. csPortClr = dcPortClr;
  392. }
  393. if(rd >= 0) { // if read-strobe pin specified...
  394. #if defined(KINETISK)
  395. tft8.rdPinMask = 1;
  396. #else // !KINETISK
  397. tft8.rdPinMask = digitalPinToBitMask(rd);
  398. #endif
  399. tft8.rdPortSet = portSetRegister(rd);
  400. tft8.rdPortClr = portClearRegister(rd);
  401. } else {
  402. tft8.rdPinMask = 0;
  403. tft8.rdPortSet = dcPortSet;
  404. tft8.rdPortClr = dcPortClr;
  405. }
  406. // These are all uint8_t* pointers -- elsewhere they're recast
  407. // as necessary if a 'wide' 16-bit interface is in use.
  408. tft8.writePort = portOutputRegister(d0);
  409. tft8.readPort = portInputRegister(d0);
  410. tft8.dirSet = portModeRegister(d0);
  411. tft8.dirClr = portModeRegister(d0);
  412. #else // !CORE_TEENSY
  413. tft8.wrPinMask = digitalPinToBitMask(wr);
  414. tft8.wrPortSet = &(PORT->Group[g_APinDescription[wr].ulPort].OUTSET.reg);
  415. tft8.wrPortClr = &(PORT->Group[g_APinDescription[wr].ulPort].OUTCLR.reg);
  416. dcPinMask = digitalPinToBitMask(dc);
  417. dcPortSet = &(PORT->Group[g_APinDescription[dc].ulPort].OUTSET.reg);
  418. dcPortClr = &(PORT->Group[g_APinDescription[dc].ulPort].OUTCLR.reg);
  419. if(cs >= 0) {
  420. csPinMask = digitalPinToBitMask(cs);
  421. csPortSet = &(PORT->Group[g_APinDescription[cs].ulPort].OUTSET.reg);
  422. csPortClr = &(PORT->Group[g_APinDescription[cs].ulPort].OUTCLR.reg);
  423. } else {
  424. // No chip-select line defined; might be permanently tied to GND.
  425. // Assign a valid GPIO register (though not used for CS), and an
  426. // empty pin bitmask...the nonsense bit-twiddling might be faster
  427. // than checking _cs and possibly branching.
  428. csPortSet = dcPortSet;
  429. csPortClr = dcPortClr;
  430. csPinMask = 0;
  431. }
  432. if(rd >= 0) { // if read-strobe pin specified...
  433. tft8.rdPinMask =digitalPinToBitMask(rd);
  434. tft8.rdPortSet =&(PORT->Group[g_APinDescription[rd].ulPort].OUTSET.reg);
  435. tft8.rdPortClr =&(PORT->Group[g_APinDescription[rd].ulPort].OUTCLR.reg);
  436. } else {
  437. tft8.rdPinMask = 0;
  438. tft8.rdPortSet = dcPortSet;
  439. tft8.rdPortClr = dcPortClr;
  440. }
  441. // Get pointers to PORT write/read/dir bytes within 32-bit PORT
  442. uint8_t dBit = g_APinDescription[d0].ulPin; // d0 bit # in PORT
  443. PortGroup *p = (&(PORT->Group[g_APinDescription[d0].ulPort]));
  444. uint8_t offset = dBit / 8; // d[7:0] byte # within PORT
  445. if(tft8.wide) offset &= ~1; // d[15:8] byte # within PORT
  446. // These are all uint8_t* pointers -- elsewhere they're recast
  447. // as necessary if a 'wide' 16-bit interface is in use.
  448. tft8.writePort = (volatile uint8_t *)&(p->OUT.reg) + offset;
  449. tft8.readPort = (volatile uint8_t *)&(p->IN.reg) + offset;
  450. tft8.dirSet = (volatile uint8_t *)&(p->DIRSET.reg) + offset;
  451. tft8.dirClr = (volatile uint8_t *)&(p->DIRCLR.reg) + offset;
  452. #endif // end !CORE_TEENSY
  453. #else // !HAS_PORT_SET_CLR
  454. tft8.wrPort = (PORTreg_t)portOutputRegister(digitalPinToPort(wr));
  455. tft8.wrPinMaskSet = digitalPinToBitMask(wr);
  456. dcPort = (PORTreg_t)portOutputRegister(digitalPinToPort(dc));
  457. dcPinMaskSet = digitalPinToBitMask(dc);
  458. if(cs >= 0) {
  459. csPort = (PORTreg_t)portOutputRegister(digitalPinToPort(cs));
  460. csPinMaskSet = digitalPinToBitMask(cs);
  461. } else {
  462. // No chip-select line defined; might be permanently tied to GND.
  463. // Assign a valid GPIO register (though not used for CS), and an
  464. // empty pin bitmask...the nonsense bit-twiddling might be faster
  465. // than checking _cs and possibly branching.
  466. csPort = dcPort;
  467. csPinMaskSet = 0;
  468. }
  469. if(rd >= 0) { // if read-strobe pin specified...
  470. tft8.rdPort =(PORTreg_t)portOutputRegister(digitalPinToPort(rd));
  471. tft8.rdPinMaskSet =digitalPinToBitMask(rd);
  472. } else {
  473. tft8.rdPort = dcPort;
  474. tft8.rdPinMaskSet = 0;
  475. }
  476. csPinMaskClr = ~csPinMaskSet;
  477. dcPinMaskClr = ~dcPinMaskSet;
  478. tft8.wrPinMaskClr = ~tft8.wrPinMaskSet;
  479. tft8.rdPinMaskClr = ~tft8.rdPinMaskSet;
  480. tft8.writePort = (PORTreg_t)portOutputRegister(digitalPinToPort(d0));
  481. tft8.readPort = (PORTreg_t)portInputRegister(digitalPinToPort(d0));
  482. tft8.portDir = (PORTreg_t)portModeRegister(digitalPinToPort(d0));
  483. #endif // end !HAS_PORT_SET_CLR
  484. #endif // end USE_FAST_PINIO
  485. }
  486. // end constructors -------
  487. // CLASS MEMBER FUNCTIONS --------------------------------------------------
  488. // begin() and setAddrWindow() MUST be declared by any subclass.
  489. /*!
  490. @brief Configure microcontroller pins for TFT interfacing. Typically
  491. called by a subclass' begin() function.
  492. @param freq SPI frequency when using hardware SPI. If default (0)
  493. is passed, will fall back on a device-specific value.
  494. Value is ignored when using software SPI or parallel
  495. connection.
  496. @param spiMode SPI mode when using hardware SPI. MUST be one of the
  497. values SPI_MODE0, SPI_MODE1, SPI_MODE2 or SPI_MODE3
  498. defined in SPI.h. Do NOT attempt to pass '0' for
  499. SPI_MODE0 and so forth...the values are NOT the same!
  500. Use ONLY the defines! (Pity it's not an enum.)
  501. @note Another anachronistically-named function; this is called even
  502. when the display connection is parallel (not SPI). Also, this
  503. could probably be made private...quite a few class functions
  504. were generously put in the public section.
  505. */
  506. void Adafruit_SPITFT::initSPI(uint32_t freq, uint8_t spiMode) {
  507. if(!freq) freq = DEFAULT_SPI_FREQ; // If no freq specified, use default
  508. // Init basic control pins common to all connection types
  509. if(_cs >= 0) {
  510. pinMode(_cs, OUTPUT);
  511. digitalWrite(_cs, HIGH); // Deselect
  512. }
  513. pinMode(_dc, OUTPUT);
  514. digitalWrite(_dc, HIGH); // Data mode
  515. if(connection == TFT_HARD_SPI) {
  516. #if defined(SPI_HAS_TRANSACTION)
  517. hwspi.settings = SPISettings(freq, MSBFIRST, spiMode);
  518. #else
  519. hwspi._freq = freq; // Save freq value for later
  520. #endif
  521. hwspi._mode = spiMode; // Save spiMode value for later
  522. // Call hwspi._spi->begin() ONLY if this is among the 'established'
  523. // SPI interfaces in variant.h. For DIY roll-your-own SERCOM SPIs,
  524. // begin() and pinPeripheral() calls MUST be made in one's calling
  525. // code, BEFORE the screen-specific begin/init function is called.
  526. // Reason for this is that SPI::begin() makes its own calls to
  527. // pinPeripheral() based on g_APinDescription[n].ulPinType, which
  528. // on non-established SPI interface pins will always be PIO_DIGITAL
  529. // or similar, while we need PIO_SERCOM or PIO_SERCOM_ALT...it's
  530. // highly unique between devices and variants for each pin or
  531. // SERCOM so we can't make those calls ourselves here. And the SPI
  532. // device needs to be set up before calling this because it's
  533. // immediately followed with initialization commands. Blargh.
  534. if(
  535. #if !defined(SPI_INTERFACES_COUNT)
  536. 1
  537. #endif
  538. #if SPI_INTERFACES_COUNT > 0
  539. (hwspi._spi == &SPI)
  540. #endif
  541. #if SPI_INTERFACES_COUNT > 1
  542. || (hwspi._spi == &SPI1)
  543. #endif
  544. #if SPI_INTERFACES_COUNT > 2
  545. || (hwspi._spi == &SPI2)
  546. #endif
  547. #if SPI_INTERFACES_COUNT > 3
  548. || (hwspi._spi == &SPI3)
  549. #endif
  550. #if SPI_INTERFACES_COUNT > 4
  551. || (hwspi._spi == &SPI4)
  552. #endif
  553. #if SPI_INTERFACES_COUNT > 5
  554. || (hwspi._spi == &SPI5)
  555. #endif
  556. ) {
  557. hwspi._spi->begin();
  558. }
  559. } else if(connection == TFT_SOFT_SPI) {
  560. pinMode(swspi._mosi, OUTPUT);
  561. digitalWrite(swspi._mosi, LOW);
  562. pinMode(swspi._sck, OUTPUT);
  563. digitalWrite(swspi._sck, LOW);
  564. if(swspi._miso >= 0) {
  565. pinMode(swspi._miso, INPUT);
  566. }
  567. } else { // TFT_PARALLEL
  568. // Initialize data pins. We were only passed d0, so scan
  569. // the pin description list looking for the other pins.
  570. // They'll be on the same PORT, and within the next 7 (or 15) bits
  571. // (because we need to write to a contiguous PORT byte or word).
  572. #if defined(__AVR__)
  573. // PORT registers are 8 bits wide, so just need a register match...
  574. for(uint8_t i=0; i<NUM_DIGITAL_PINS; i++) {
  575. if((PORTreg_t)portOutputRegister(digitalPinToPort(i)) ==
  576. tft8.writePort) {
  577. pinMode(i, OUTPUT);
  578. digitalWrite(i, LOW);
  579. }
  580. }
  581. #elif defined(USE_FAST_PINIO)
  582. #if defined(CORE_TEENSY)
  583. if(!tft8.wide) {
  584. *tft8.dirSet = 0xFF; // Set port to output
  585. *tft8.writePort = 0x00; // Write all 0s
  586. } else {
  587. *(volatile uint16_t *)tft8.dirSet = 0xFFFF;
  588. *(volatile uint16_t *)tft8.writePort = 0x0000;
  589. }
  590. #else // !CORE_TEENSY
  591. uint8_t portNum = g_APinDescription[tft8._d0].ulPort, // d0 PORT #
  592. dBit = g_APinDescription[tft8._d0].ulPin, // d0 bit in PORT
  593. lastBit = dBit + (tft8.wide ? 15 : 7);
  594. for(uint8_t i=0; i<PINS_COUNT; i++) {
  595. if((g_APinDescription[i].ulPort == portNum ) &&
  596. (g_APinDescription[i].ulPin >= dBit ) &&
  597. (g_APinDescription[i].ulPin <= (uint32_t)lastBit)) {
  598. pinMode(i, OUTPUT);
  599. digitalWrite(i, LOW);
  600. }
  601. }
  602. #endif // end !CORE_TEENSY
  603. #endif
  604. pinMode(tft8._wr, OUTPUT);
  605. digitalWrite(tft8._wr, HIGH);
  606. if(tft8._rd >= 0) {
  607. pinMode(tft8._rd, OUTPUT);
  608. digitalWrite(tft8._rd, HIGH);
  609. }
  610. }
  611. if(_rst >= 0) {
  612. // Toggle _rst low to reset
  613. pinMode(_rst, OUTPUT);
  614. digitalWrite(_rst, HIGH);
  615. delay(100);
  616. digitalWrite(_rst, LOW);
  617. delay(100);
  618. digitalWrite(_rst, HIGH);
  619. delay(200);
  620. }
  621. #if defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO))
  622. if(((connection == TFT_HARD_SPI) || (connection == TFT_PARALLEL)) &&
  623. (dma.allocate() == DMA_STATUS_OK)) { // Allocate channel
  624. // The DMA library needs to alloc at least one valid descriptor,
  625. // so we do that here. It's not used in the usual sense though,
  626. // just before a transfer we copy descriptor[0] to this address.
  627. if(dptr = dma.addDescriptor(NULL, NULL, 42, DMA_BEAT_SIZE_BYTE,
  628. false, false)) {
  629. // Alloc 2 scanlines worth of pixels on display's major axis,
  630. // whichever that is, rounding each up to 2-pixel boundary.
  631. int major = (WIDTH > HEIGHT) ? WIDTH : HEIGHT;
  632. major += (major & 1); // -> next 2-pixel bound, if needed.
  633. maxFillLen = major * 2; // 2 scanlines
  634. // Note to future self: if you decide to make the pixel buffer
  635. // much larger, remember that DMA transfer descriptors can't
  636. // exceed 65,535 bytes (not 65,536), meaning 32,767 pixels max.
  637. // Not that we have that kind of RAM to throw around right now.
  638. if((pixelBuf[0] =
  639. (uint16_t *)malloc(maxFillLen * sizeof(uint16_t)))) {
  640. // Alloc OK. Get pointer to start of second scanline.
  641. pixelBuf[1] = &pixelBuf[0][major];
  642. // Determine number of DMA descriptors needed to cover
  643. // entire screen when entire 2-line pixelBuf is used
  644. // (round up for fractional last descriptor).
  645. int numDescriptors = (WIDTH * HEIGHT + (maxFillLen - 1)) /
  646. maxFillLen;
  647. // DMA descriptors MUST be 128-bit (16 byte) aligned.
  648. // memalign() is considered obsolete but it's replacements
  649. // (aligned_alloc() or posix_memalign()) are not currently
  650. // available in the version of ARM GCC in use, but this
  651. // is, so here we are.
  652. if((descriptor = (DmacDescriptor *)memalign(16,
  653. numDescriptors * sizeof(DmacDescriptor)))) {
  654. int dmac_id;
  655. volatile uint32_t *data_reg;
  656. if(connection == TFT_HARD_SPI) {
  657. // THIS IS AN AFFRONT TO NATURE, but I don't know
  658. // any "clean" way to get the sercom number from the
  659. // the SPIClass pointer (e.g. &SPI or &SPI1), which
  660. // is all we have to work with. SPIClass does contain
  661. // a SERCOM pointer but it is a PRIVATE member!
  662. // Doing an UNSPEAKABLY HORRIBLE THING here, directly
  663. // accessing the first 32-bit value in the SPIClass
  664. // structure, knowing that's (currently) where the
  665. // SERCOM pointer lives, but this ENTIRELY DEPENDS on
  666. // that structure not changing nor the compiler
  667. // rearranging things. Oh the humanity!
  668. if(*(SERCOM **)hwspi._spi == &sercom0) {
  669. dmac_id = SERCOM0_DMAC_ID_TX;
  670. data_reg = &SERCOM0->SPI.DATA.reg;
  671. #if defined SERCOM1
  672. } else if(*(SERCOM **)hwspi._spi == &sercom1) {
  673. dmac_id = SERCOM1_DMAC_ID_TX;
  674. data_reg = &SERCOM1->SPI.DATA.reg;
  675. #endif
  676. #if defined SERCOM2
  677. } else if(*(SERCOM **)hwspi._spi == &sercom2) {
  678. dmac_id = SERCOM2_DMAC_ID_TX;
  679. data_reg = &SERCOM2->SPI.DATA.reg;
  680. #endif
  681. #if defined SERCOM3
  682. } else if(*(SERCOM **)hwspi._spi == &sercom3) {
  683. dmac_id = SERCOM3_DMAC_ID_TX;
  684. data_reg = &SERCOM3->SPI.DATA.reg;
  685. #endif
  686. #if defined SERCOM4
  687. } else if(*(SERCOM **)hwspi._spi == &sercom4) {
  688. dmac_id = SERCOM4_DMAC_ID_TX;
  689. data_reg = &SERCOM4->SPI.DATA.reg;
  690. #endif
  691. #if defined SERCOM5
  692. } else if(*(SERCOM **)hwspi._spi == &sercom5) {
  693. dmac_id = SERCOM5_DMAC_ID_TX;
  694. data_reg = &SERCOM5->SPI.DATA.reg;
  695. #endif
  696. #if defined SERCOM6
  697. } else if(*(SERCOM **)hwspi._spi == &sercom6) {
  698. dmac_id = SERCOM6_DMAC_ID_TX;
  699. data_reg = &SERCOM6->SPI.DATA.reg;
  700. #endif
  701. #if defined SERCOM7
  702. } else if(*(SERCOM **)hwspi._spi == &sercom7) {
  703. dmac_id = SERCOM7_DMAC_ID_TX;
  704. data_reg = &SERCOM7->SPI.DATA.reg;
  705. #endif
  706. }
  707. dma.setPriority(DMA_PRIORITY_3);
  708. dma.setTrigger(dmac_id);
  709. dma.setAction(DMA_TRIGGER_ACTON_BEAT);
  710. // Initialize descriptor list.
  711. for(int d=0; d<numDescriptors; d++) {
  712. // No need to set SRCADDR, DESCADDR or BTCNT --
  713. // those are done in the pixel-writing functions.
  714. descriptor[d].BTCTRL.bit.VALID = true;
  715. descriptor[d].BTCTRL.bit.EVOSEL =
  716. DMA_EVENT_OUTPUT_DISABLE;
  717. descriptor[d].BTCTRL.bit.BLOCKACT =
  718. DMA_BLOCK_ACTION_NOACT;
  719. descriptor[d].BTCTRL.bit.BEATSIZE =
  720. DMA_BEAT_SIZE_BYTE;
  721. descriptor[d].BTCTRL.bit.DSTINC = 0;
  722. descriptor[d].BTCTRL.bit.STEPSEL =
  723. DMA_STEPSEL_SRC;
  724. descriptor[d].BTCTRL.bit.STEPSIZE =
  725. DMA_ADDRESS_INCREMENT_STEP_SIZE_1;
  726. descriptor[d].DSTADDR.reg =
  727. (uint32_t)data_reg;
  728. }
  729. } else { // Parallel connection
  730. #if defined(__SAMD51__)
  731. int dmaChannel = dma.getChannel();
  732. // Enable event output, use EVOSEL output
  733. DMAC->Channel[dmaChannel].CHEVCTRL.bit.EVOE = 1;
  734. DMAC->Channel[dmaChannel].CHEVCTRL.bit.EVOMODE = 0;
  735. // CONFIGURE TIMER/COUNTER (for write strobe)
  736. Tc *timer = tcList[tcNum].tc; // -> Timer struct
  737. int id = tcList[tcNum].gclk; // Timer GCLK ID
  738. GCLK_PCHCTRL_Type pchctrl;
  739. // Set up timer clock source from GCLK
  740. GCLK->PCHCTRL[id].bit.CHEN = 0; // Stop timer
  741. while(GCLK->PCHCTRL[id].bit.CHEN); // Wait for it
  742. pchctrl.bit.GEN = GCLK_PCHCTRL_GEN_GCLK0_Val;
  743. pchctrl.bit.CHEN = 1; // Enable
  744. GCLK->PCHCTRL[id].reg = pchctrl.reg;
  745. while(!GCLK->PCHCTRL[id].bit.CHEN); // Wait for it
  746. // Disable timer/counter before configuring it
  747. timer->COUNT8.CTRLA.bit.ENABLE = 0;
  748. while(timer->COUNT8.SYNCBUSY.bit.STATUS);
  749. timer->COUNT8.WAVE.bit.WAVEGEN = 2; // NPWM
  750. timer->COUNT8.CTRLA.bit.MODE = 1; // 8-bit
  751. timer->COUNT8.CTRLA.bit.PRESCALER = 0; // 1:1
  752. while(timer->COUNT8.SYNCBUSY.bit.STATUS);
  753. timer->COUNT8.CTRLBCLR.bit.DIR = 1; // Count UP
  754. while(timer->COUNT8.SYNCBUSY.bit.CTRLB);
  755. timer->COUNT8.CTRLBSET.bit.ONESHOT = 1; // One-shot
  756. while(timer->COUNT8.SYNCBUSY.bit.CTRLB);
  757. timer->COUNT8.PER.reg = 6; // PWM top
  758. while(timer->COUNT8.SYNCBUSY.bit.PER);
  759. timer->COUNT8.CC[0].reg = 2; // Compare
  760. while(timer->COUNT8.SYNCBUSY.bit.CC0);
  761. // Enable async input events,
  762. // event action = restart.
  763. timer->COUNT8.EVCTRL.bit.TCEI = 1;
  764. timer->COUNT8.EVCTRL.bit.EVACT = 1;
  765. // Enable timer
  766. timer->COUNT8.CTRLA.reg |= TC_CTRLA_ENABLE;
  767. while(timer->COUNT8.SYNCBUSY.bit.STATUS);
  768. #if(wrPeripheral == PIO_CCL)
  769. // CONFIGURE CCL (inverts timer/counter output)
  770. MCLK->APBCMASK.bit.CCL_ = 1; // Enable CCL clock
  771. CCL->CTRL.bit.ENABLE = 0; // Disable to config
  772. CCL->CTRL.bit.SWRST = 1; // Reset CCL registers
  773. CCL->LUTCTRL[tcNum].bit.ENABLE = 0; // Disable LUT
  774. CCL->LUTCTRL[tcNum].bit.FILTSEL = 0; // No filter
  775. CCL->LUTCTRL[tcNum].bit.INSEL0 = 6; // TC input
  776. CCL->LUTCTRL[tcNum].bit.INSEL1 = 0; // MASK
  777. CCL->LUTCTRL[tcNum].bit.INSEL2 = 0; // MASK
  778. CCL->LUTCTRL[tcNum].bit.TRUTH = 1; // Invert in 0
  779. CCL->LUTCTRL[tcNum].bit.ENABLE = 1; // Enable LUT
  780. CCL->CTRL.bit.ENABLE = 1; // Enable CCL
  781. #endif
  782. // CONFIGURE EVENT SYSTEM
  783. // Set up event system clock source from GCLK...
  784. // Disable EVSYS, wait for disable
  785. GCLK->PCHCTRL[EVSYS_GCLK_ID_0].bit.CHEN = 0;
  786. while(GCLK->PCHCTRL[EVSYS_GCLK_ID_0].bit.CHEN);
  787. pchctrl.bit.GEN = GCLK_PCHCTRL_GEN_GCLK0_Val;
  788. pchctrl.bit.CHEN = 1; // Re-enable
  789. GCLK->PCHCTRL[EVSYS_GCLK_ID_0].reg = pchctrl.reg;
  790. // Wait for it, then enable EVSYS clock
  791. while(!GCLK->PCHCTRL[EVSYS_GCLK_ID_0].bit.CHEN);
  792. MCLK->APBBMASK.bit.EVSYS_ = 1;
  793. // Connect Timer EVU to ch 0
  794. EVSYS->USER[tcList[tcNum].evu].reg = 1;
  795. // Datasheet recommends single write operation;
  796. // reg instead of bit. Also datasheet: PATH bits
  797. // must be zero when using async!
  798. EVSYS_CHANNEL_Type ev;
  799. ev.reg = 0;
  800. ev.bit.PATH = 2; // Asynchronous
  801. ev.bit.EVGEN = 0x22 + dmaChannel; // DMA channel 0+
  802. EVSYS->Channel[0].CHANNEL.reg = ev.reg;
  803. // Initialize descriptor list.
  804. for(int d=0; d<numDescriptors; d++) {
  805. // No need to set SRCADDR, DESCADDR or BTCNT --
  806. // those are done in the pixel-writing functions.
  807. descriptor[d].BTCTRL.bit.VALID = true;
  808. // Event strobe on beat xfer:
  809. descriptor[d].BTCTRL.bit.EVOSEL = 0x3;
  810. descriptor[d].BTCTRL.bit.BLOCKACT =
  811. DMA_BLOCK_ACTION_NOACT;
  812. descriptor[d].BTCTRL.bit.BEATSIZE = tft8.wide ?
  813. DMA_BEAT_SIZE_HWORD : DMA_BEAT_SIZE_BYTE;
  814. descriptor[d].BTCTRL.bit.SRCINC = 1;
  815. descriptor[d].BTCTRL.bit.DSTINC = 0;
  816. descriptor[d].BTCTRL.bit.STEPSEL =
  817. DMA_STEPSEL_SRC;
  818. descriptor[d].BTCTRL.bit.STEPSIZE =
  819. DMA_ADDRESS_INCREMENT_STEP_SIZE_1;
  820. descriptor[d].DSTADDR.reg =
  821. (uint32_t)tft8.writePort;
  822. }
  823. #endif // __SAMD51
  824. } // end parallel-specific DMA setup
  825. lastFillColor = 0x0000;
  826. lastFillLen = 0;
  827. dma.setCallback(dma_callback);
  828. return; // Success!
  829. // else clean up any partial allocation...
  830. } // end descriptor memalign()
  831. free(pixelBuf[0]);
  832. pixelBuf[0] = pixelBuf[1] = NULL;
  833. } // end pixelBuf malloc()
  834. // Don't currently have a descriptor delete function in
  835. // ZeroDMA lib, but if we did, it would be called here.
  836. } // end addDescriptor()
  837. dma.free(); // Deallocate DMA channel
  838. }
  839. #endif // end USE_SPI_DMA
  840. }
  841. /*!
  842. @brief Allow changing the SPI clock speed after initialization
  843. @param freq Desired frequency of SPI clock, may not be the
  844. end frequency you get based on what the chip can do!
  845. */
  846. void Adafruit_SPITFT::setSPISpeed(uint32_t freq) {
  847. #if defined(SPI_HAS_TRANSACTION)
  848. hwspi.settings = SPISettings(freq, MSBFIRST, hwspi._mode);
  849. #else
  850. hwspi._freq = freq; // Save freq value for later
  851. #endif
  852. }
  853. /*!
  854. @brief Call before issuing command(s) or data to display. Performs
  855. chip-select (if required) and starts an SPI transaction (if
  856. using hardware SPI and transactions are supported). Required
  857. for all display types; not an SPI-specific function.
  858. */
  859. void Adafruit_SPITFT::startWrite(void) {
  860. SPI_BEGIN_TRANSACTION();
  861. if(_cs >= 0) SPI_CS_LOW();
  862. }
  863. /*!
  864. @brief Call after issuing command(s) or data to display. Performs
  865. chip-deselect (if required) and ends an SPI transaction (if
  866. using hardware SPI and transactions are supported). Required
  867. for all display types; not an SPI-specific function.
  868. */
  869. void Adafruit_SPITFT::endWrite(void) {
  870. if(_cs >= 0) SPI_CS_HIGH();
  871. SPI_END_TRANSACTION();
  872. }
  873. // -------------------------------------------------------------------------
  874. // Lower-level graphics operations. These functions require a chip-select
  875. // and/or SPI transaction around them (via startWrite(), endWrite() above).
  876. // Higher-level graphics primitives might start a single transaction and
  877. // then make multiple calls to these functions (e.g. circle or text
  878. // rendering might make repeated lines or rects) before ending the
  879. // transaction. It's more efficient than starting a transaction every time.
  880. /*!
  881. @brief Draw a single pixel to the display at requested coordinates.
  882. Not self-contained; should follow a startWrite() call.
  883. @param x Horizontal position (0 = left).
  884. @param y Vertical position (0 = top).
  885. @param color 16-bit pixel color in '565' RGB format.
  886. */
  887. void Adafruit_SPITFT::writePixel(int16_t x, int16_t y, uint16_t color) {
  888. if((x >= 0) && (x < _width) && (y >= 0) && (y < _height)) {
  889. setAddrWindow(x, y, 1, 1);
  890. SPI_WRITE16(color);
  891. }
  892. }
  893. /*!
  894. @brief Issue a series of pixels from memory to the display. Not self-
  895. contained; should follow startWrite() and setAddrWindow() calls.
  896. @param colors Pointer to array of 16-bit pixel values in '565' RGB
  897. format.
  898. @param len Number of elements in 'colors' array.
  899. @param block If true (default case if unspecified), function blocks
  900. until DMA transfer is complete. This is simply IGNORED
  901. if DMA is not enabled. If false, the function returns
  902. immediately after the last DMA transfer is started,
  903. and one should use the dmaWait() function before
  904. doing ANY other display-related activities (or even
  905. any SPI-related activities, if using an SPI display
  906. that shares the bus with other devices).
  907. @param bigEndian If using DMA, and if set true, bitmap in memory is in
  908. big-endian order (most significant byte first). By
  909. default this is false, as most microcontrollers seem
  910. to be little-endian and 16-bit pixel values must be
  911. byte-swapped before issuing to the display (which tend
  912. to be big-endian when using SPI or 8-bit parallel).
  913. If an application can optimize around this -- for
  914. example, a bitmap in a uint16_t array having the byte
  915. values already reordered big-endian, this can save
  916. some processing time here, ESPECIALLY if using this
  917. function's non-blocking DMA mode. Not all cases are
  918. covered...this is really here only for SAMD DMA and
  919. much forethought on the application side.
  920. */
  921. void Adafruit_SPITFT::writePixels(uint16_t *colors, uint32_t len,
  922. bool block, bool bigEndian) {
  923. if(!len) return; // Avoid 0-byte transfers
  924. #if defined(ESP32) // ESP32 has a special SPI pixel-writing function...
  925. if(connection == TFT_HARD_SPI) {
  926. hwspi._spi->writePixels(colors, len * 2);
  927. return;
  928. }
  929. #elif defined(ARDUINO_NRF52_ADAFRUIT) && defined(NRF52840_XXAA)// Adafruit nRF52 use SPIM3 DMA at 32Mhz
  930. // TFT and SPI DMA endian is different we need to swap bytes
  931. if (!bigEndian) {
  932. for(uint32_t i=0; i<len; i++) {
  933. colors[i] = __builtin_bswap16(colors[i]);
  934. }
  935. }
  936. // use the separate tx, rx buf variant to prevent overwrite the buffer
  937. hwspi._spi->transfer(colors, NULL, 2*len);
  938. // swap back color buffer
  939. if (!bigEndian) {
  940. for(uint32_t i=0; i<len; i++) {
  941. colors[i] = __builtin_bswap16(colors[i]);
  942. }
  943. }
  944. return;
  945. #elif defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO))
  946. if((connection == TFT_HARD_SPI) || (connection == TFT_PARALLEL)) {
  947. int maxSpan = maxFillLen / 2; // One scanline max
  948. uint8_t pixelBufIdx = 0; // Active pixel buffer number
  949. #if defined(__SAMD51__)
  950. if(connection == TFT_PARALLEL) {
  951. // Switch WR pin to PWM or CCL
  952. pinPeripheral(tft8._wr, wrPeripheral);
  953. }
  954. #endif // end __SAMD51__
  955. if(!bigEndian) { // Normal little-endian situation...
  956. while(len) {
  957. int count = (len < maxSpan) ? len : maxSpan;
  958. // Because TFT and SAMD endianisms are different, must swap
  959. // bytes from the 'colors' array passed into a DMA working
  960. // buffer. This can take place while the prior DMA transfer
  961. // is in progress, hence the need for two pixelBufs.
  962. for(int i=0; i<count; i++) {
  963. pixelBuf[pixelBufIdx][i] = __builtin_bswap16(*colors++);
  964. }
  965. // The transfers themselves are relatively small, so we don't
  966. // need a long descriptor list. We just alternate between the
  967. // first two, sharing pixelBufIdx for that purpose.
  968. descriptor[pixelBufIdx].SRCADDR.reg =
  969. (uint32_t)pixelBuf[pixelBufIdx] + count * 2;
  970. descriptor[pixelBufIdx].BTCTRL.bit.SRCINC = 1;
  971. descriptor[pixelBufIdx].BTCNT.reg = count * 2;
  972. descriptor[pixelBufIdx].DESCADDR.reg = 0;
  973. while(dma_busy); // Wait for prior line to finish
  974. // Move new descriptor into place...
  975. memcpy(dptr, &descriptor[pixelBufIdx], sizeof(DmacDescriptor));
  976. dma_busy = true;
  977. dma.startJob(); // Trigger SPI DMA transfer
  978. if(connection == TFT_PARALLEL) dma.trigger();
  979. pixelBufIdx = 1 - pixelBufIdx; // Swap DMA pixel buffers
  980. len -= count;
  981. }
  982. } else { // bigEndian == true
  983. // With big-endian pixel data, this can be handled as a single
  984. // DMA transfer using chained descriptors. Even full screen, this
  985. // needs only a relatively short descriptor list, each
  986. // transferring a max of 32,767 (not 32,768) pixels. The list
  987. // was allocated large enough to accommodate a full screen's
  988. // worth of data, so this won't run past the end of the list.
  989. int d, numDescriptors = (len + 32766) / 32767;
  990. for(d=0; d<numDescriptors; d++) {
  991. int count = (len < 32767) ? len : 32767;
  992. descriptor[d].SRCADDR.reg = (uint32_t)colors + count * 2;
  993. descriptor[d].BTCTRL.bit.SRCINC = 1;
  994. descriptor[d].BTCNT.reg = count * 2;
  995. descriptor[d].DESCADDR.reg = (uint32_t)&descriptor[d+1];
  996. len -= count;
  997. colors += count;
  998. }
  999. descriptor[d-1].DESCADDR.reg = 0;
  1000. while(dma_busy); // Wait for prior transfer (if any) to finish
  1001. // Move first descriptor into place and start transfer...
  1002. memcpy(dptr, &descriptor[0], sizeof(DmacDescriptor));
  1003. dma_busy = true;
  1004. dma.startJob(); // Trigger SPI DMA transfer
  1005. if(connection == TFT_PARALLEL) dma.trigger();
  1006. } // end bigEndian
  1007. lastFillColor = 0x0000; // pixelBuf has been sullied
  1008. lastFillLen = 0;
  1009. if(block) {
  1010. while(dma_busy); // Wait for last line to complete
  1011. #if defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO)
  1012. if(connection == TFT_HARD_SPI) {
  1013. // See SAMD51/21 note in writeColor()
  1014. hwspi._spi->setDataMode(hwspi._mode);
  1015. } else {
  1016. pinPeripheral(tft8._wr, PIO_OUTPUT); // Switch WR back to GPIO
  1017. }
  1018. #endif // end __SAMD51__ || ARDUINO_SAMD_ZERO
  1019. }
  1020. return;
  1021. }
  1022. #endif // end USE_SPI_DMA
  1023. // All other cases (bitbang SPI or non-DMA hard SPI or parallel),
  1024. // use a loop with the normal 16-bit data write function:
  1025. while(len--) {
  1026. SPI_WRITE16(*colors++);
  1027. }
  1028. }
  1029. /*!
  1030. @brief Wait for the last DMA transfer in a prior non-blocking
  1031. writePixels() call to complete. This does nothing if DMA
  1032. is not enabled, and is not needed if blocking writePixels()
  1033. was used (as is the default case).
  1034. */
  1035. void Adafruit_SPITFT::dmaWait(void) {
  1036. #if defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO))
  1037. while(dma_busy);
  1038. #if defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO)
  1039. if(connection == TFT_HARD_SPI) {
  1040. // See SAMD51/21 note in writeColor()
  1041. hwspi._spi->setDataMode(hwspi._mode);
  1042. } else {
  1043. pinPeripheral(tft8._wr, PIO_OUTPUT); // Switch WR back to GPIO
  1044. }
  1045. #endif // end __SAMD51__ || ARDUINO_SAMD_ZERO
  1046. #endif
  1047. }
  1048. /*!
  1049. @brief Issue a series of pixels, all the same color. Not self-
  1050. contained; should follow startWrite() and setAddrWindow() calls.
  1051. @param color 16-bit pixel color in '565' RGB format.
  1052. @param len Number of pixels to draw.
  1053. */
  1054. void Adafruit_SPITFT::writeColor(uint16_t color, uint32_t len) {
  1055. if(!len) return; // Avoid 0-byte transfers
  1056. uint8_t hi = color >> 8, lo = color;
  1057. #if defined(ESP32) // ESP32 has a special SPI pixel-writing function...
  1058. if(connection == TFT_HARD_SPI) {
  1059. #define SPI_MAX_PIXELS_AT_ONCE 32
  1060. #define TMPBUF_LONGWORDS (SPI_MAX_PIXELS_AT_ONCE + 1) / 2
  1061. #define TMPBUF_PIXELS (TMPBUF_LONGWORDS * 2)
  1062. static uint32_t temp[TMPBUF_LONGWORDS];
  1063. uint32_t c32 = color * 0x00010001;
  1064. uint16_t bufLen = (len < TMPBUF_PIXELS) ? len : TMPBUF_PIXELS,
  1065. xferLen, fillLen;
  1066. // Fill temp buffer 32 bits at a time
  1067. fillLen = (bufLen + 1) / 2; // Round up to next 32-bit boundary
  1068. for(uint32_t t=0; t<fillLen; t++) {
  1069. temp[t] = c32;
  1070. }
  1071. // Issue pixels in blocks from temp buffer
  1072. while(len) { // While pixels remain
  1073. xferLen = (bufLen < len) ? bufLen : len; // How many this pass?
  1074. writePixels((uint16_t *)temp, xferLen);
  1075. len -= xferLen;
  1076. }
  1077. return;
  1078. }
  1079. #elif defined(ARDUINO_NRF52_ADAFRUIT) && defined(NRF52840_XXAA) // Adafruit nRF52840 use SPIM3 DMA at 32Mhz
  1080. // at most 2 scan lines
  1081. uint32_t const pixbufcount = min(len, ((uint32_t) 2*width()));
  1082. uint16_t* pixbuf = (uint16_t*) rtos_malloc(2*pixbufcount);
  1083. // use SPI3 DMA if we could allocate buffer, else fall back to writing each pixel loop below
  1084. if (pixbuf)
  1085. {
  1086. uint16_t const swap_color = __builtin_bswap16(color);
  1087. // fill buffer with color
  1088. for(uint32_t i=0; i<pixbufcount; i++) {
  1089. pixbuf[i] = swap_color;
  1090. }
  1091. while(len) {
  1092. uint32_t const count = min(len, pixbufcount);
  1093. writePixels(pixbuf, count, true, true);
  1094. len -= count;
  1095. }
  1096. rtos_free(pixbuf);
  1097. return;
  1098. }
  1099. #else // !ESP32
  1100. #if defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO))
  1101. if(((connection == TFT_HARD_SPI) || (connection == TFT_PARALLEL)) &&
  1102. (len >= 16)) { // Don't bother with DMA on short pixel runs
  1103. int i, d, numDescriptors;
  1104. if(hi == lo) { // If high & low bytes are same...
  1105. onePixelBuf = color;
  1106. // Can do this with a relatively short descriptor list,
  1107. // each transferring a max of 32,767 (not 32,768) pixels.
  1108. // This won't run off the end of the allocated descriptor list,
  1109. // since we're using much larger chunks per descriptor here.
  1110. numDescriptors = (len + 32766) / 32767;
  1111. for(d=0; d<numDescriptors; d++) {
  1112. int count = (len < 32767) ? len : 32767;
  1113. descriptor[d].SRCADDR.reg = (uint32_t)&onePixelBuf;
  1114. descriptor[d].BTCTRL.bit.SRCINC = 0;
  1115. descriptor[d].BTCNT.reg = count * 2;
  1116. descriptor[d].DESCADDR.reg = (uint32_t)&descriptor[d+1];
  1117. len -= count;
  1118. }
  1119. descriptor[d-1].DESCADDR.reg = 0;
  1120. } else {
  1121. // If high and low bytes are distinct, it's necessary to fill
  1122. // a buffer with pixel data (swapping high and low bytes because
  1123. // TFT and SAMD are different endianisms) and create a longer
  1124. // descriptor list pointing repeatedly to this data. We can do
  1125. // this slightly faster working 2 pixels (32 bits) at a time.
  1126. uint32_t *pixelPtr = (uint32_t *)pixelBuf[0],
  1127. twoPixels = __builtin_bswap16(color) * 0x00010001;
  1128. // We can avoid some or all of the buffer-filling if the color
  1129. // is the same as last time...
  1130. if(color == lastFillColor) {
  1131. // If length is longer than prior instance, fill only the
  1132. // additional pixels in the buffer and update lastFillLen.
  1133. if(len > lastFillLen) {
  1134. int fillStart = lastFillLen / 2,
  1135. fillEnd = (((len < maxFillLen) ?
  1136. len : maxFillLen) + 1) / 2;
  1137. for(i=fillStart; i<fillEnd; i++) pixelPtr[i] = twoPixels;
  1138. lastFillLen = fillEnd * 2;
  1139. } // else do nothing, don't set pixels or change lastFillLen
  1140. } else {
  1141. int fillEnd = (((len < maxFillLen) ?
  1142. len : maxFillLen) + 1) / 2;
  1143. for(i=0; i<fillEnd; i++) pixelPtr[i] = twoPixels;
  1144. lastFillLen = fillEnd * 2;
  1145. lastFillColor = color;
  1146. }
  1147. numDescriptors = (len + maxFillLen - 1) / maxFillLen;
  1148. for(d=0; d<numDescriptors; d++) {
  1149. int pixels = (len < maxFillLen) ? len : maxFillLen,
  1150. bytes = pixels * 2;
  1151. descriptor[d].SRCADDR.reg = (uint32_t)pixelPtr + bytes;
  1152. descriptor[d].BTCTRL.bit.SRCINC = 1;
  1153. descriptor[d].BTCNT.reg = bytes;
  1154. descriptor[d].DESCADDR.reg = (uint32_t)&descriptor[d+1];
  1155. len -= pixels;
  1156. }
  1157. descriptor[d-1].DESCADDR.reg = 0;
  1158. }
  1159. memcpy(dptr, &descriptor[0], sizeof(DmacDescriptor));
  1160. #if defined(__SAMD51__)
  1161. if(connection == TFT_PARALLEL) {
  1162. // Switch WR pin to PWM or CCL
  1163. pinPeripheral(tft8._wr, wrPeripheral);
  1164. }
  1165. #endif // end __SAMD51__
  1166. dma_busy = true;
  1167. dma.startJob();
  1168. if(connection == TFT_PARALLEL) dma.trigger();
  1169. while(dma_busy); // Wait for completion
  1170. // Unfortunately blocking is necessary. An earlier version returned
  1171. // immediately and checked dma_busy on startWrite() instead, but it
  1172. // turns out to be MUCH slower on many graphics operations (as when
  1173. // drawing lines, pixel-by-pixel), perhaps because it's a volatile
  1174. // type and doesn't cache. Working on this.
  1175. #if defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO)
  1176. if(connection == TFT_HARD_SPI) {
  1177. // SAMD51: SPI DMA seems to leave the SPI peripheral in a freaky
  1178. // state on completion. Workaround is to explicitly set it back...
  1179. // (5/17/2019: apparently SAMD21 too, in certain cases, observed
  1180. // with ST7789 display.)
  1181. hwspi._spi->setDataMode(hwspi._mode);
  1182. } else {
  1183. pinPeripheral(tft8._wr, PIO_OUTPUT); // Switch WR back to GPIO
  1184. }
  1185. #endif // end __SAMD51__
  1186. return;
  1187. }
  1188. #endif // end USE_SPI_DMA
  1189. #endif // end !ESP32
  1190. // All other cases (non-DMA hard SPI, bitbang SPI, parallel)...
  1191. if(connection == TFT_HARD_SPI) {
  1192. #if defined(ESP8266)
  1193. do {
  1194. uint32_t pixelsThisPass = len;
  1195. if(pixelsThisPass > 50000) pixelsThisPass = 50000;
  1196. len -= pixelsThisPass;
  1197. yield(); // Periodic yield() on long fills
  1198. while(pixelsThisPass--) {
  1199. hwspi._spi->write(hi);
  1200. hwspi._spi->write(lo);
  1201. }
  1202. } while(len);
  1203. #else // !ESP8266
  1204. while(len--) {
  1205. #if defined(__AVR__)
  1206. AVR_WRITESPI(hi);
  1207. AVR_WRITESPI(lo);
  1208. #elif defined(ESP32)
  1209. hwspi._spi->write(hi);
  1210. hwspi._spi->write(lo);
  1211. #else
  1212. hwspi._spi->transfer(hi);
  1213. hwspi._spi->transfer(lo);
  1214. #endif
  1215. }
  1216. #endif // end !ESP8266
  1217. } else if(connection == TFT_SOFT_SPI) {
  1218. #if defined(ESP8266)
  1219. do {
  1220. uint32_t pixelsThisPass = len;
  1221. if(pixelsThisPass > 20000) pixelsThisPass = 20000;
  1222. len -= pixelsThisPass;
  1223. yield(); // Periodic yield() on long fills
  1224. while(pixelsThisPass--) {
  1225. for(uint16_t bit=0, x=color; bit<16; bit++) {
  1226. if(x & 0x8000) SPI_MOSI_HIGH();
  1227. else SPI_MOSI_LOW();
  1228. SPI_SCK_HIGH();
  1229. SPI_SCK_LOW();
  1230. x <<= 1;
  1231. }
  1232. }
  1233. } while(len);
  1234. #else // !ESP8266
  1235. while(len--) {
  1236. #if defined(__AVR__)
  1237. for(uint8_t bit=0, x=hi; bit<8; bit++) {
  1238. if(x & 0x80) SPI_MOSI_HIGH();
  1239. else SPI_MOSI_LOW();
  1240. SPI_SCK_HIGH();
  1241. SPI_SCK_LOW();
  1242. x <<= 1;
  1243. }
  1244. for(uint8_t bit=0, x=lo; bit<8; bit++) {
  1245. if(x & 0x80) SPI_MOSI_HIGH();
  1246. else SPI_MOSI_LOW();
  1247. SPI_SCK_HIGH();
  1248. SPI_SCK_LOW();
  1249. x <<= 1;
  1250. }
  1251. #else // !__AVR__
  1252. for(uint16_t bit=0, x=color; bit<16; bit++) {
  1253. if(x & 0x8000) SPI_MOSI_HIGH();
  1254. else SPI_MOSI_LOW();
  1255. SPI_SCK_HIGH();
  1256. x <<= 1;
  1257. SPI_SCK_LOW();
  1258. }
  1259. #endif // end !__AVR__
  1260. }
  1261. #endif // end !ESP8266
  1262. } else { // PARALLEL
  1263. if(hi == lo) {
  1264. #if defined(__AVR__)
  1265. len *= 2;
  1266. *tft8.writePort = hi;
  1267. while(len--) {
  1268. TFT_WR_STROBE();
  1269. }
  1270. #elif defined(USE_FAST_PINIO)
  1271. if(!tft8.wide) {
  1272. len *= 2;
  1273. *tft8.writePort = hi;
  1274. } else {
  1275. *(volatile uint16_t *)tft8.writePort = color;
  1276. }
  1277. while(len--) {
  1278. TFT_WR_STROBE();
  1279. }
  1280. #endif
  1281. } else {
  1282. while(len--) {
  1283. #if defined(__AVR__)
  1284. *tft8.writePort = hi;
  1285. TFT_WR_STROBE();
  1286. *tft8.writePort = lo;
  1287. #elif defined(USE_FAST_PINIO)
  1288. if(!tft8.wide) {
  1289. *tft8.writePort = hi;
  1290. TFT_WR_STROBE();
  1291. *tft8.writePort = lo;
  1292. } else {
  1293. *(volatile uint16_t *)tft8.writePort = color;
  1294. }
  1295. #endif
  1296. TFT_WR_STROBE();
  1297. }
  1298. }
  1299. }
  1300. }
  1301. /*!
  1302. @brief Draw a filled rectangle to the display. Not self-contained;
  1303. should follow startWrite(). Typically used by higher-level
  1304. graphics primitives; user code shouldn't need to call this and
  1305. is likely to use the self-contained fillRect() instead.
  1306. writeFillRect() performs its own edge clipping and rejection;
  1307. see writeFillRectPreclipped() for a more 'raw' implementation.
  1308. @param x Horizontal position of first corner.
  1309. @param y Vertical position of first corner.
  1310. @param w Rectangle width in pixels (positive = right of first
  1311. corner, negative = left of first corner).
  1312. @param h Rectangle height in pixels (positive = below first
  1313. corner, negative = above first corner).
  1314. @param color 16-bit fill color in '565' RGB format.
  1315. @note Written in this deep-nested way because C by definition will
  1316. optimize for the 'if' case, not the 'else' -- avoids branches
  1317. and rejects clipped rectangles at the least-work possibility.
  1318. */
  1319. void Adafruit_SPITFT::writeFillRect(int16_t x, int16_t y,
  1320. int16_t w, int16_t h, uint16_t color) {
  1321. if(w && h) { // Nonzero width and height?
  1322. if(w < 0) { // If negative width...
  1323. x += w + 1; // Move X to left edge
  1324. w = -w; // Use positive width
  1325. }
  1326. if(x < _width) { // Not off right
  1327. if(h < 0) { // If negative height...
  1328. y += h + 1; // Move Y to top edge
  1329. h = -h; // Use positive height
  1330. }
  1331. if(y < _height) { // Not off bottom
  1332. int16_t x2 = x + w - 1;
  1333. if(x2 >= 0) { // Not off left
  1334. int16_t y2 = y + h - 1;
  1335. if(y2 >= 0) { // Not off top
  1336. // Rectangle partly or fully overlaps screen
  1337. if(x < 0) { x = 0; w = x2 + 1; } // Clip left
  1338. if(y < 0) { y = 0; h = y2 + 1; } // Clip top
  1339. if(x2 >= _width) { w = _width - x; } // Clip right
  1340. if(y2 >= _height) { h = _height - y; } // Clip bottom
  1341. writeFillRectPreclipped(x, y, w, h, color);
  1342. }
  1343. }
  1344. }
  1345. }
  1346. }
  1347. }
  1348. /*!
  1349. @brief Draw a horizontal line on the display. Performs edge clipping
  1350. and rejection. Not self-contained; should follow startWrite().
  1351. Typically used by higher-level graphics primitives; user code
  1352. shouldn't need to call this and is likely to use the self-
  1353. contained drawFastHLine() instead.
  1354. @param x Horizontal position of first point.
  1355. @param y Vertical position of first point.
  1356. @param w Line width in pixels (positive = right of first point,
  1357. negative = point of first corner).
  1358. @param color 16-bit line color in '565' RGB format.
  1359. */
  1360. void inline Adafruit_SPITFT::writeFastHLine(int16_t x, int16_t y, int16_t w,
  1361. uint16_t color) {
  1362. if((y >= 0) && (y < _height) && w) { // Y on screen, nonzero width
  1363. if(w < 0) { // If negative width...
  1364. x += w + 1; // Move X to left edge
  1365. w = -w; // Use positive width
  1366. }
  1367. if(x < _width) { // Not off right
  1368. int16_t x2 = x + w - 1;
  1369. if(x2 >= 0) { // Not off left
  1370. // Line partly or fully overlaps screen
  1371. if(x < 0) { x = 0; w = x2 + 1; } // Clip left
  1372. if(x2 >= _width) { w = _width - x; } // Clip right
  1373. writeFillRectPreclipped(x, y, w, 1, color);
  1374. }
  1375. }
  1376. }
  1377. }
  1378. /*!
  1379. @brief Draw a vertical line on the display. Performs edge clipping and
  1380. rejection. Not self-contained; should follow startWrite().
  1381. Typically used by higher-level graphics primitives; user code
  1382. shouldn't need to call this and is likely to use the self-
  1383. contained drawFastVLine() instead.
  1384. @param x Horizontal position of first point.
  1385. @param y Vertical position of first point.
  1386. @param h Line height in pixels (positive = below first point,
  1387. negative = above first point).
  1388. @param color 16-bit line color in '565' RGB format.
  1389. */
  1390. void inline Adafruit_SPITFT::writeFastVLine(int16_t x, int16_t y, int16_t h,
  1391. uint16_t color) {
  1392. if((x >= 0) && (x < _width) && h) { // X on screen, nonzero height
  1393. if(h < 0) { // If negative height...
  1394. y += h + 1; // Move Y to top edge
  1395. h = -h; // Use positive height
  1396. }
  1397. if(y < _height) { // Not off bottom
  1398. int16_t y2 = y + h - 1;
  1399. if(y2 >= 0) { // Not off top
  1400. // Line partly or fully overlaps screen
  1401. if(y < 0) { y = 0; h = y2 + 1; } // Clip top
  1402. if(y2 >= _height) { h = _height - y; } // Clip bottom
  1403. writeFillRectPreclipped(x, y, 1, h, color);
  1404. }
  1405. }
  1406. }
  1407. }
  1408. /*!
  1409. @brief A lower-level version of writeFillRect(). This version requires
  1410. all inputs are in-bounds, that width and height are positive,
  1411. and no part extends offscreen. NO EDGE CLIPPING OR REJECTION IS
  1412. PERFORMED. If higher-level graphics primitives are written to
  1413. handle their own clipping earlier in the drawing process, this
  1414. can avoid unnecessary function calls and repeated clipping
  1415. operations in the lower-level functions.
  1416. @param x Horizontal position of first corner. MUST BE WITHIN
  1417. SCREEN BOUNDS.
  1418. @param y Vertical position of first corner. MUST BE WITHIN SCREEN
  1419. BOUNDS.
  1420. @param w Rectangle width in pixels. MUST BE POSITIVE AND NOT
  1421. EXTEND OFF SCREEN.
  1422. @param h Rectangle height in pixels. MUST BE POSITIVE AND NOT
  1423. EXTEND OFF SCREEN.
  1424. @param color 16-bit fill color in '565' RGB format.
  1425. @note This is a new function, no graphics primitives besides rects
  1426. and horizontal/vertical lines are written to best use this yet.
  1427. */
  1428. inline void Adafruit_SPITFT::writeFillRectPreclipped(int16_t x, int16_t y,
  1429. int16_t w, int16_t h, uint16_t color) {
  1430. setAddrWindow(x, y, w, h);
  1431. writeColor(color, (uint32_t)w * h);
  1432. }
  1433. // -------------------------------------------------------------------------
  1434. // Ever-so-slightly higher-level graphics operations. Similar to the 'write'
  1435. // functions above, but these contain their own chip-select and SPI
  1436. // transactions as needed (via startWrite(), endWrite()). They're typically
  1437. // used solo -- as graphics primitives in themselves, not invoked by higher-
  1438. // level primitives (which should use the functions above for better
  1439. // performance).
  1440. /*!
  1441. @brief Draw a single pixel to the display at requested coordinates.
  1442. Self-contained and provides its own transaction as needed
  1443. (see writePixel(x,y,color) for a lower-level variant).
  1444. Edge clipping is performed here.
  1445. @param x Horizontal position (0 = left).
  1446. @param y Vertical position (0 = top).
  1447. @param color 16-bit pixel color in '565' RGB format.
  1448. */
  1449. void Adafruit_SPITFT::drawPixel(int16_t x, int16_t y, uint16_t color) {
  1450. // Clip first...
  1451. if((x >= 0) && (x < _width) && (y >= 0) && (y < _height)) {
  1452. // THEN set up transaction (if needed) and draw...
  1453. startWrite();
  1454. setAddrWindow(x, y, 1, 1);
  1455. SPI_WRITE16(color);
  1456. endWrite();
  1457. }
  1458. }
  1459. /*!
  1460. @brief Draw a filled rectangle to the display. Self-contained and
  1461. provides its own transaction as needed (see writeFillRect() or
  1462. writeFillRectPreclipped() for lower-level variants). Edge
  1463. clipping and rejection is performed here.
  1464. @param x Horizontal position of first corner.
  1465. @param y Vertical position of first corner.
  1466. @param w Rectangle width in pixels (positive = right of first
  1467. corner, negative = left of first corner).
  1468. @param h Rectangle height in pixels (positive = below first
  1469. corner, negative = above first corner).
  1470. @param color 16-bit fill color in '565' RGB format.
  1471. @note This repeats the writeFillRect() function almost in its entirety,
  1472. with the addition of a transaction start/end. It's done this way
  1473. (rather than starting the transaction and calling writeFillRect()
  1474. to handle clipping and so forth) so that the transaction isn't
  1475. performed at all if the rectangle is rejected. It's really not
  1476. that much code.
  1477. */
  1478. void Adafruit_SPITFT::fillRect(int16_t x, int16_t y, int16_t w, int16_t h,
  1479. uint16_t color) {
  1480. if(w && h) { // Nonzero width and height?
  1481. if(w < 0) { // If negative width...
  1482. x += w + 1; // Move X to left edge
  1483. w = -w; // Use positive width
  1484. }
  1485. if(x < _width) { // Not off right
  1486. if(h < 0) { // If negative height...
  1487. y += h + 1; // Move Y to top edge
  1488. h = -h; // Use positive height
  1489. }
  1490. if(y < _height) { // Not off bottom
  1491. int16_t x2 = x + w - 1;
  1492. if(x2 >= 0) { // Not off left
  1493. int16_t y2 = y + h - 1;
  1494. if(y2 >= 0) { // Not off top
  1495. // Rectangle partly or fully overlaps screen
  1496. if(x < 0) { x = 0; w = x2 + 1; } // Clip left
  1497. if(y < 0) { y = 0; h = y2 + 1; } // Clip top
  1498. if(x2 >= _width) { w = _width - x; } // Clip right
  1499. if(y2 >= _height) { h = _height - y; } // Clip bottom
  1500. startWrite();
  1501. writeFillRectPreclipped(x, y, w, h, color);
  1502. endWrite();
  1503. }
  1504. }
  1505. }
  1506. }
  1507. }
  1508. }
  1509. /*!
  1510. @brief Draw a horizontal line on the display. Self-contained and
  1511. provides its own transaction as needed (see writeFastHLine() for
  1512. a lower-level variant). Edge clipping and rejection is performed
  1513. here.
  1514. @param x Horizontal position of first point.
  1515. @param y Vertical position of first point.
  1516. @param w Line width in pixels (positive = right of first point,
  1517. negative = point of first corner).
  1518. @param color 16-bit line color in '565' RGB format.
  1519. @note This repeats the writeFastHLine() function almost in its
  1520. entirety, with the addition of a transaction start/end. It's
  1521. done this way (rather than starting the transaction and calling
  1522. writeFastHLine() to handle clipping and so forth) so that the
  1523. transaction isn't performed at all if the line is rejected.
  1524. */
  1525. void Adafruit_SPITFT::drawFastHLine(int16_t x, int16_t y, int16_t w,
  1526. uint16_t color) {
  1527. if((y >= 0) && (y < _height) && w) { // Y on screen, nonzero width
  1528. if(w < 0) { // If negative width...
  1529. x += w + 1; // Move X to left edge
  1530. w = -w; // Use positive width
  1531. }
  1532. if(x < _width) { // Not off right
  1533. int16_t x2 = x + w - 1;
  1534. if(x2 >= 0) { // Not off left
  1535. // Line partly or fully overlaps screen
  1536. if(x < 0) { x = 0; w = x2 + 1; } // Clip left
  1537. if(x2 >= _width) { w = _width - x; } // Clip right
  1538. startWrite();
  1539. writeFillRectPreclipped(x, y, w, 1, color);
  1540. endWrite();
  1541. }
  1542. }
  1543. }
  1544. }
  1545. /*!
  1546. @brief Draw a vertical line on the display. Self-contained and provides
  1547. its own transaction as needed (see writeFastHLine() for a lower-
  1548. level variant). Edge clipping and rejection is performed here.
  1549. @param x Horizontal position of first point.
  1550. @param y Vertical position of first point.
  1551. @param h Line height in pixels (positive = below first point,
  1552. negative = above first point).
  1553. @param color 16-bit line color in '565' RGB format.
  1554. @note This repeats the writeFastVLine() function almost in its
  1555. entirety, with the addition of a transaction start/end. It's
  1556. done this way (rather than starting the transaction and calling
  1557. writeFastVLine() to handle clipping and so forth) so that the
  1558. transaction isn't performed at all if the line is rejected.
  1559. */
  1560. void Adafruit_SPITFT::drawFastVLine(int16_t x, int16_t y, int16_t h,
  1561. uint16_t color) {
  1562. if((x >= 0) && (x < _width) && h) { // X on screen, nonzero height
  1563. if(h < 0) { // If negative height...
  1564. y += h + 1; // Move Y to top edge
  1565. h = -h; // Use positive height
  1566. }
  1567. if(y < _height) { // Not off bottom
  1568. int16_t y2 = y + h - 1;
  1569. if(y2 >= 0) { // Not off top
  1570. // Line partly or fully overlaps screen
  1571. if(y < 0) { y = 0; h = y2 + 1; } // Clip top
  1572. if(y2 >= _height) { h = _height - y; } // Clip bottom
  1573. startWrite();
  1574. writeFillRectPreclipped(x, y, 1, h, color);
  1575. endWrite();
  1576. }
  1577. }
  1578. }
  1579. }
  1580. /*!
  1581. @brief Essentially writePixel() with a transaction around it. I don't
  1582. think this is in use by any of our code anymore (believe it was
  1583. for some older BMP-reading examples), but is kept here in case
  1584. any user code relies on it. Consider it DEPRECATED.
  1585. @param color 16-bit pixel color in '565' RGB format.
  1586. */
  1587. void Adafruit_SPITFT::pushColor(uint16_t color) {
  1588. startWrite();
  1589. SPI_WRITE16(color);
  1590. endWrite();
  1591. }
  1592. /*!
  1593. @brief Draw a 16-bit image (565 RGB) at the specified (x,y) position.
  1594. For 16-bit display devices; no color reduction performed.
  1595. Adapted from https://github.com/PaulStoffregen/ILI9341_t3
  1596. by Marc MERLIN. See examples/pictureEmbed to use this.
  1597. 5/6/2017: function name and arguments have changed for
  1598. compatibility with current GFX library and to avoid naming
  1599. problems in prior implementation. Formerly drawBitmap() with
  1600. arguments in different order. Handles its own transaction and
  1601. edge clipping/rejection.
  1602. @param x Top left corner horizontal coordinate.
  1603. @param y Top left corner vertical coordinate.
  1604. @param pcolors Pointer to 16-bit array of pixel values.
  1605. @param w Width of bitmap in pixels.
  1606. @param h Height of bitmap in pixels.
  1607. */
  1608. void Adafruit_SPITFT::drawRGBBitmap(int16_t x, int16_t y,
  1609. uint16_t *pcolors, int16_t w, int16_t h) {
  1610. int16_t x2, y2; // Lower-right coord
  1611. if(( x >= _width ) || // Off-edge right
  1612. ( y >= _height) || // " top
  1613. ((x2 = (x+w-1)) < 0 ) || // " left
  1614. ((y2 = (y+h-1)) < 0) ) return; // " bottom
  1615. int16_t bx1=0, by1=0, // Clipped top-left within bitmap
  1616. saveW=w; // Save original bitmap width value
  1617. if(x < 0) { // Clip left
  1618. w += x;
  1619. bx1 = -x;
  1620. x = 0;
  1621. }
  1622. if(y < 0) { // Clip top
  1623. h += y;
  1624. by1 = -y;
  1625. y = 0;
  1626. }
  1627. if(x2 >= _width ) w = _width - x; // Clip right
  1628. if(y2 >= _height) h = _height - y; // Clip bottom
  1629. pcolors += by1 * saveW + bx1; // Offset bitmap ptr to clipped top-left
  1630. startWrite();
  1631. setAddrWindow(x, y, w, h); // Clipped area
  1632. while(h--) { // For each (clipped) scanline...
  1633. writePixels(pcolors, w); // Push one (clipped) row
  1634. pcolors += saveW; // Advance pointer by one full (unclipped) line
  1635. }
  1636. endWrite();
  1637. }
  1638. // -------------------------------------------------------------------------
  1639. // Miscellaneous class member functions that don't draw anything.
  1640. /*!
  1641. @brief Invert the colors of the display (if supported by hardware).
  1642. Self-contained, no transaction setup required.
  1643. @param i true = inverted display, false = normal display.
  1644. */
  1645. void Adafruit_SPITFT::invertDisplay(bool i) {
  1646. startWrite();
  1647. writeCommand(i ? invertOnCommand : invertOffCommand);
  1648. endWrite();
  1649. }
  1650. /*!
  1651. @brief Given 8-bit red, green and blue values, return a 'packed'
  1652. 16-bit color value in '565' RGB format (5 bits red, 6 bits
  1653. green, 5 bits blue). This is just a mathematical operation,
  1654. no hardware is touched.
  1655. @param red 8-bit red brightnesss (0 = off, 255 = max).
  1656. @param green 8-bit green brightnesss (0 = off, 255 = max).
  1657. @param blue 8-bit blue brightnesss (0 = off, 255 = max).
  1658. @return 'Packed' 16-bit color value (565 format).
  1659. */
  1660. uint16_t Adafruit_SPITFT::color565(uint8_t red, uint8_t green, uint8_t blue) {
  1661. return ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | (blue >> 3);
  1662. }
  1663. /*!
  1664. @brief Adafruit_SPITFT Send Command handles complete sending of commands and data
  1665. @param commandByte The Command Byte
  1666. @param dataBytes A pointer to the Data bytes to send
  1667. @param numDataBytes The number of bytes we should send
  1668. */
  1669. void Adafruit_SPITFT::sendCommand(uint8_t commandByte, uint8_t *dataBytes, uint8_t numDataBytes) {
  1670. SPI_BEGIN_TRANSACTION();
  1671. if(_cs >= 0) SPI_CS_LOW();
  1672. SPI_DC_LOW(); // Command mode
  1673. spiWrite(commandByte); // Send the command byte
  1674. SPI_DC_HIGH();
  1675. for (int i=0; i<numDataBytes; i++) {
  1676. spiWrite(*dataBytes); // Send the data bytes
  1677. dataBytes++;
  1678. }
  1679. if(_cs >= 0) SPI_CS_HIGH();
  1680. SPI_END_TRANSACTION();
  1681. }
  1682. /*!
  1683. @brief Adafruit_SPITFT Send Command handles complete sending of commands and const data
  1684. @param commandByte The Command Byte
  1685. @param dataBytes A pointer to the Data bytes to send
  1686. @param numDataBytes The number of bytes we should send
  1687. */
  1688. void Adafruit_SPITFT::sendCommand(uint8_t commandByte, const uint8_t *dataBytes, uint8_t numDataBytes) {
  1689. SPI_BEGIN_TRANSACTION();
  1690. if(_cs >= 0) SPI_CS_LOW();
  1691. SPI_DC_LOW(); // Command mode
  1692. spiWrite(commandByte); // Send the command byte
  1693. SPI_DC_HIGH();
  1694. for (int i=0; i<numDataBytes; i++) {
  1695. spiWrite(pgm_read_byte(dataBytes++)); // Send the data bytes
  1696. }
  1697. if(_cs >= 0) SPI_CS_HIGH();
  1698. SPI_END_TRANSACTION();
  1699. }
  1700. /*!
  1701. @brief Read 8 bits of data from display configuration memory (not RAM).
  1702. This is highly undocumented/supported and should be avoided,
  1703. function is only included because some of the examples use it.
  1704. @param commandByte
  1705. The command register to read data from.
  1706. @param index
  1707. The byte index into the command to read from.
  1708. @return Unsigned 8-bit data read from display register.
  1709. */
  1710. /**************************************************************************/
  1711. uint8_t Adafruit_SPITFT::readcommand8(uint8_t commandByte, uint8_t index) {
  1712. uint8_t result;
  1713. startWrite();
  1714. SPI_DC_LOW(); // Command mode
  1715. spiWrite(commandByte);
  1716. SPI_DC_HIGH(); // Data mode
  1717. do {
  1718. result = spiRead();
  1719. } while(index--); // Discard bytes up to index'th
  1720. endWrite();
  1721. return result;
  1722. }
  1723. // -------------------------------------------------------------------------
  1724. // Lowest-level hardware-interfacing functions. Many of these are inline and
  1725. // compile to different things based on #defines -- typically just a few
  1726. // instructions. Others, not so much, those are not inlined.
  1727. /*!
  1728. @brief Start an SPI transaction if using the hardware SPI interface to
  1729. the display. If using an earlier version of the Arduino platform
  1730. (before the addition of SPI transactions), this instead attempts
  1731. to set up the SPI clock and mode. No action is taken if the
  1732. connection is not hardware SPI-based. This does NOT include a
  1733. chip-select operation -- see startWrite() for a function that
  1734. encapsulated both actions.
  1735. */
  1736. inline void Adafruit_SPITFT::SPI_BEGIN_TRANSACTION(void) {
  1737. if(connection == TFT_HARD_SPI) {
  1738. #if defined(SPI_HAS_TRANSACTION)
  1739. hwspi._spi->beginTransaction(hwspi.settings);
  1740. #else // No transactions, configure SPI manually...
  1741. #if defined(__AVR__) || defined(TEENSYDUINO) || defined(ARDUINO_ARCH_STM32F1)
  1742. hwspi._spi->setClockDivider(SPI_CLOCK_DIV2);
  1743. #elif defined(__arm__)
  1744. hwspi._spi->setClockDivider(11);
  1745. #elif defined(ESP8266) || defined(ESP32)
  1746. hwspi._spi->setFrequency(hwspi._freq);
  1747. #elif defined(RASPI) || defined(ARDUINO_ARCH_STM32F1)
  1748. hwspi._spi->setClock(hwspi._freq);
  1749. #endif
  1750. hwspi._spi->setBitOrder(MSBFIRST);
  1751. hwspi._spi->setDataMode(hwspi._mode);
  1752. #endif // end !SPI_HAS_TRANSACTION
  1753. }
  1754. }
  1755. /*!
  1756. @brief End an SPI transaction if using the hardware SPI interface to
  1757. the display. No action is taken if the connection is not
  1758. hardware SPI-based or if using an earlier version of the Arduino
  1759. platform (before the addition of SPI transactions). This does
  1760. NOT include a chip-deselect operation -- see endWrite() for a
  1761. function that encapsulated both actions.
  1762. */
  1763. inline void Adafruit_SPITFT::SPI_END_TRANSACTION(void) {
  1764. #if defined(SPI_HAS_TRANSACTION)
  1765. if(connection == TFT_HARD_SPI) {
  1766. hwspi._spi->endTransaction();
  1767. }
  1768. #endif
  1769. }
  1770. /*!
  1771. @brief Issue a single 8-bit value to the display. Chip-select,
  1772. transaction and data/command selection must have been
  1773. previously set -- this ONLY issues the byte. This is another of
  1774. those functions in the library with a now-not-accurate name
  1775. that's being maintained for compatibility with outside code.
  1776. This function is used even if display connection is parallel.
  1777. @param b 8-bit value to write.
  1778. */
  1779. void Adafruit_SPITFT::spiWrite(uint8_t b) {
  1780. if(connection == TFT_HARD_SPI) {
  1781. #if defined(__AVR__)
  1782. AVR_WRITESPI(b);
  1783. #elif defined(ESP8266) || defined(ESP32)
  1784. hwspi._spi->write(b);
  1785. #else
  1786. hwspi._spi->transfer(b);
  1787. #endif
  1788. } else if(connection == TFT_SOFT_SPI) {
  1789. for(uint8_t bit=0; bit<8; bit++) {
  1790. if(b & 0x80) SPI_MOSI_HIGH();
  1791. else SPI_MOSI_LOW();
  1792. SPI_SCK_HIGH();
  1793. b <<= 1;
  1794. SPI_SCK_LOW();
  1795. }
  1796. } else { // TFT_PARALLEL
  1797. #if defined(__AVR__)
  1798. *tft8.writePort = b;
  1799. #elif defined(USE_FAST_PINIO)
  1800. if(!tft8.wide) *tft8.writePort = b;
  1801. else *(volatile uint16_t *)tft8.writePort = b;
  1802. #endif
  1803. TFT_WR_STROBE();
  1804. }
  1805. }
  1806. /*!
  1807. @brief Write a single command byte to the display. Chip-select and
  1808. transaction must have been previously set -- this ONLY sets
  1809. the device to COMMAND mode, issues the byte and then restores
  1810. DATA mode. There is no corresponding explicit writeData()
  1811. function -- just use spiWrite().
  1812. @param cmd 8-bit command to write.
  1813. */
  1814. void Adafruit_SPITFT::writeCommand(uint8_t cmd) {
  1815. SPI_DC_LOW();
  1816. spiWrite(cmd);
  1817. SPI_DC_HIGH();
  1818. }
  1819. /*!
  1820. @brief Read a single 8-bit value from the display. Chip-select and
  1821. transaction must have been previously set -- this ONLY reads
  1822. the byte. This is another of those functions in the library
  1823. with a now-not-accurate name that's being maintained for
  1824. compatibility with outside code. This function is used even if
  1825. display connection is parallel.
  1826. @return Unsigned 8-bit value read (always zero if USE_FAST_PINIO is
  1827. not supported by the MCU architecture).
  1828. */
  1829. uint8_t Adafruit_SPITFT::spiRead(void) {
  1830. uint8_t b = 0;
  1831. uint16_t w = 0;
  1832. if(connection == TFT_HARD_SPI) {
  1833. return hwspi._spi->transfer((uint8_t)0);
  1834. } else if(connection == TFT_SOFT_SPI) {
  1835. if(swspi._miso >= 0) {
  1836. for(uint8_t i=0; i<8; i++) {
  1837. SPI_SCK_HIGH();
  1838. b <<= 1;
  1839. if(SPI_MISO_READ()) b++;
  1840. SPI_SCK_LOW();
  1841. }
  1842. }
  1843. return b;
  1844. } else { // TFT_PARALLEL
  1845. if(tft8._rd >= 0) {
  1846. #if defined(USE_FAST_PINIO)
  1847. TFT_RD_LOW(); // Read line LOW
  1848. #if defined(__AVR__)
  1849. *tft8.portDir = 0x00; // Set port to input state
  1850. w = *tft8.readPort; // Read value from port
  1851. *tft8.portDir = 0xFF; // Restore port to output
  1852. #else // !__AVR__
  1853. if(!tft8.wide) { // 8-bit TFT connection
  1854. #if defined(HAS_PORT_SET_CLR)
  1855. *tft8.dirClr = 0xFF; // Set port to input state
  1856. w = *tft8.readPort; // Read value from port
  1857. *tft8.dirSet = 0xFF; // Restore port to output
  1858. #else // !HAS_PORT_SET_CLR
  1859. *tft8.portDir = 0x00; // Set port to input state
  1860. w = *tft8.readPort; // Read value from port
  1861. *tft8.portDir = 0xFF; // Restore port to output
  1862. #endif // end HAS_PORT_SET_CLR
  1863. } else { // 16-bit TFT connection
  1864. #if defined(HAS_PORT_SET_CLR)
  1865. *(volatile uint16_t *)tft8.dirClr = 0xFFFF; // Input state
  1866. w = *(volatile uint16_t *)tft8.readPort; // 16-bit read
  1867. *(volatile uint16_t *)tft8.dirSet = 0xFFFF; // Output state
  1868. #else // !HAS_PORT_SET_CLR
  1869. *(volatile uint16_t *)tft8.portDir = 0x0000; // Input state
  1870. w = *(volatile uint16_t *)tft8.readPort; // 16-bit read
  1871. *(volatile uint16_t *)tft8.portDir = 0xFFFF; // Output state
  1872. #endif // end !HAS_PORT_SET_CLR
  1873. }
  1874. TFT_RD_HIGH(); // Read line HIGH
  1875. #endif // end !__AVR__
  1876. #else // !USE_FAST_PINIO
  1877. w = 0; // Parallel TFT is NOT SUPPORTED without USE_FAST_PINIO
  1878. #endif // end !USE_FAST_PINIO
  1879. }
  1880. return w;
  1881. }
  1882. }
  1883. /*!
  1884. @brief Set the software (bitbang) SPI MOSI line HIGH.
  1885. */
  1886. inline void Adafruit_SPITFT::SPI_MOSI_HIGH(void) {
  1887. #if defined(USE_FAST_PINIO)
  1888. #if defined(HAS_PORT_SET_CLR)
  1889. #if defined(KINETISK)
  1890. *swspi.mosiPortSet = 1;
  1891. #else // !KINETISK
  1892. *swspi.mosiPortSet = swspi.mosiPinMask;
  1893. #endif
  1894. #else // !HAS_PORT_SET_CLR
  1895. *swspi.mosiPort |= swspi.mosiPinMaskSet;
  1896. #endif // end !HAS_PORT_SET_CLR
  1897. #else // !USE_FAST_PINIO
  1898. digitalWrite(swspi._mosi, HIGH);
  1899. #if defined(ESP32)
  1900. for(volatile uint8_t i=0; i<1; i++);
  1901. #endif // end ESP32
  1902. #endif // end !USE_FAST_PINIO
  1903. }
  1904. /*!
  1905. @brief Set the software (bitbang) SPI MOSI line LOW.
  1906. */
  1907. inline void Adafruit_SPITFT::SPI_MOSI_LOW(void) {
  1908. #if defined(USE_FAST_PINIO)
  1909. #if defined(HAS_PORT_SET_CLR)
  1910. #if defined(KINETISK)
  1911. *swspi.mosiPortClr = 1;
  1912. #else // !KINETISK
  1913. *swspi.mosiPortClr = swspi.mosiPinMask;
  1914. #endif
  1915. #else // !HAS_PORT_SET_CLR
  1916. *swspi.mosiPort &= swspi.mosiPinMaskClr;
  1917. #endif // end !HAS_PORT_SET_CLR
  1918. #else // !USE_FAST_PINIO
  1919. digitalWrite(swspi._mosi, LOW);
  1920. #if defined(ESP32)
  1921. for(volatile uint8_t i=0; i<1; i++);
  1922. #endif // end ESP32
  1923. #endif // end !USE_FAST_PINIO
  1924. }
  1925. /*!
  1926. @brief Set the software (bitbang) SPI SCK line HIGH.
  1927. */
  1928. inline void Adafruit_SPITFT::SPI_SCK_HIGH(void) {
  1929. #if defined(USE_FAST_PINIO)
  1930. #if defined(HAS_PORT_SET_CLR)
  1931. #if defined(KINETISK)
  1932. *swspi.sckPortSet = 1;
  1933. #else // !KINETISK
  1934. *swspi.sckPortSet = swspi.sckPinMask;
  1935. #if defined(__IMXRT1052__) || defined(__IMXRT1062__) // Teensy 4.x
  1936. for(volatile uint8_t i=0; i<1; i++);
  1937. #endif
  1938. #endif
  1939. #else // !HAS_PORT_SET_CLR
  1940. *swspi.sckPort |= swspi.sckPinMaskSet;
  1941. #endif // end !HAS_PORT_SET_CLR
  1942. #else // !USE_FAST_PINIO
  1943. digitalWrite(swspi._sck, HIGH);
  1944. #if defined(ESP32)
  1945. for(volatile uint8_t i=0; i<1; i++);
  1946. #endif // end ESP32
  1947. #endif // end !USE_FAST_PINIO
  1948. }
  1949. /*!
  1950. @brief Set the software (bitbang) SPI SCK line LOW.
  1951. */
  1952. inline void Adafruit_SPITFT::SPI_SCK_LOW(void) {
  1953. #if defined(USE_FAST_PINIO)
  1954. #if defined(HAS_PORT_SET_CLR)
  1955. #if defined(KINETISK)
  1956. *swspi.sckPortClr = 1;
  1957. #else // !KINETISK
  1958. *swspi.sckPortClr = swspi.sckPinMask;
  1959. #if defined(__IMXRT1052__) || defined(__IMXRT1062__) // Teensy 4.x
  1960. for(volatile uint8_t i=0; i<1; i++);
  1961. #endif
  1962. #endif
  1963. #else // !HAS_PORT_SET_CLR
  1964. *swspi.sckPort &= swspi.sckPinMaskClr;
  1965. #endif // end !HAS_PORT_SET_CLR
  1966. #else // !USE_FAST_PINIO
  1967. digitalWrite(swspi._sck, LOW);
  1968. #if defined(ESP32)
  1969. for(volatile uint8_t i=0; i<1; i++);
  1970. #endif // end ESP32
  1971. #endif // end !USE_FAST_PINIO
  1972. }
  1973. /*!
  1974. @brief Read the state of the software (bitbang) SPI MISO line.
  1975. @return true if HIGH, false if LOW.
  1976. */
  1977. inline bool Adafruit_SPITFT::SPI_MISO_READ(void) {
  1978. #if defined(USE_FAST_PINIO)
  1979. #if defined(KINETISK)
  1980. return *swspi.misoPort;
  1981. #else // !KINETISK
  1982. return *swspi.misoPort & swspi.misoPinMask;
  1983. #endif // end !KINETISK
  1984. #else // !USE_FAST_PINIO
  1985. return digitalRead(swspi._miso);
  1986. #endif // end !USE_FAST_PINIO
  1987. }
  1988. /*!
  1989. @brief Issue a single 16-bit value to the display. Chip-select,
  1990. transaction and data/command selection must have been
  1991. previously set -- this ONLY issues the word. Despite the name,
  1992. this function is used even if display connection is parallel;
  1993. name was maintaned for backward compatibility. Naming is also
  1994. not consistent with the 8-bit version, spiWrite(). Sorry about
  1995. that. Again, staying compatible with outside code.
  1996. @param w 16-bit value to write.
  1997. */
  1998. void Adafruit_SPITFT::SPI_WRITE16(uint16_t w) {
  1999. if(connection == TFT_HARD_SPI) {
  2000. #if defined(__AVR__)
  2001. AVR_WRITESPI(w >> 8);
  2002. AVR_WRITESPI(w);
  2003. #elif defined(ESP8266) || defined(ESP32)
  2004. hwspi._spi->write16(w);
  2005. #else
  2006. hwspi._spi->transfer(w >> 8);
  2007. hwspi._spi->transfer(w);
  2008. #endif
  2009. } else if(connection == TFT_SOFT_SPI) {
  2010. for(uint8_t bit=0; bit<16; bit++) {
  2011. if(w & 0x8000) SPI_MOSI_HIGH();
  2012. else SPI_MOSI_LOW();
  2013. SPI_SCK_HIGH();
  2014. SPI_SCK_LOW();
  2015. w <<= 1;
  2016. }
  2017. } else { // TFT_PARALLEL
  2018. #if defined(__AVR__)
  2019. *tft8.writePort = w >> 8;
  2020. TFT_WR_STROBE();
  2021. *tft8.writePort = w;
  2022. #elif defined(USE_FAST_PINIO)
  2023. if(!tft8.wide) {
  2024. *tft8.writePort = w >> 8;
  2025. TFT_WR_STROBE();
  2026. *tft8.writePort = w;
  2027. } else {
  2028. *(volatile uint16_t *)tft8.writePort = w;
  2029. }
  2030. #endif
  2031. TFT_WR_STROBE();
  2032. }
  2033. }
  2034. /*!
  2035. @brief Issue a single 32-bit value to the display. Chip-select,
  2036. transaction and data/command selection must have been
  2037. previously set -- this ONLY issues the longword. Despite the
  2038. name, this function is used even if display connection is
  2039. parallel; name was maintaned for backward compatibility. Naming
  2040. is also not consistent with the 8-bit version, spiWrite().
  2041. Sorry about that. Again, staying compatible with outside code.
  2042. @param l 32-bit value to write.
  2043. */
  2044. void Adafruit_SPITFT::SPI_WRITE32(uint32_t l) {
  2045. if(connection == TFT_HARD_SPI) {
  2046. #if defined(__AVR__)
  2047. AVR_WRITESPI(l >> 24);
  2048. AVR_WRITESPI(l >> 16);
  2049. AVR_WRITESPI(l >> 8);
  2050. AVR_WRITESPI(l );
  2051. #elif defined(ESP8266) || defined(ESP32)
  2052. hwspi._spi->write32(l);
  2053. #else
  2054. hwspi._spi->transfer(l >> 24);
  2055. hwspi._spi->transfer(l >> 16);
  2056. hwspi._spi->transfer(l >> 8);
  2057. hwspi._spi->transfer(l);
  2058. #endif
  2059. } else if(connection == TFT_SOFT_SPI) {
  2060. for(uint8_t bit=0; bit<32; bit++) {
  2061. if(l & 0x80000000) SPI_MOSI_HIGH();
  2062. else SPI_MOSI_LOW();
  2063. SPI_SCK_HIGH();
  2064. SPI_SCK_LOW();
  2065. l <<= 1;
  2066. }
  2067. } else { // TFT_PARALLEL
  2068. #if defined(__AVR__)
  2069. *tft8.writePort = l >> 24;
  2070. TFT_WR_STROBE();
  2071. *tft8.writePort = l >> 16;
  2072. TFT_WR_STROBE();
  2073. *tft8.writePort = l >> 8;
  2074. TFT_WR_STROBE();
  2075. *tft8.writePort = l;
  2076. #elif defined(USE_FAST_PINIO)
  2077. if(!tft8.wide) {
  2078. *tft8.writePort = l >> 24;
  2079. TFT_WR_STROBE();
  2080. *tft8.writePort = l >> 16;
  2081. TFT_WR_STROBE();
  2082. *tft8.writePort = l >> 8;
  2083. TFT_WR_STROBE();
  2084. *tft8.writePort = l;
  2085. } else {
  2086. *(volatile uint16_t *)tft8.writePort = l >> 16;
  2087. TFT_WR_STROBE();
  2088. *(volatile uint16_t *)tft8.writePort = l;
  2089. }
  2090. #endif
  2091. TFT_WR_STROBE();
  2092. }
  2093. }
  2094. /*!
  2095. @brief Set the WR line LOW, then HIGH. Used for parallel-connected
  2096. interfaces when writing data.
  2097. */
  2098. inline void Adafruit_SPITFT::TFT_WR_STROBE(void) {
  2099. #if defined(USE_FAST_PINIO)
  2100. #if defined(HAS_PORT_SET_CLR)
  2101. #if defined(KINETISK)
  2102. *tft8.wrPortClr = 1;
  2103. *tft8.wrPortSet = 1;
  2104. #else // !KINETISK
  2105. *tft8.wrPortClr = tft8.wrPinMask;
  2106. *tft8.wrPortSet = tft8.wrPinMask;
  2107. #endif // end !KINETISK
  2108. #else // !HAS_PORT_SET_CLR
  2109. *tft8.wrPort &= tft8.wrPinMaskClr;
  2110. *tft8.wrPort |= tft8.wrPinMaskSet;
  2111. #endif // end !HAS_PORT_SET_CLR
  2112. #else // !USE_FAST_PINIO
  2113. digitalWrite(tft8._wr, LOW);
  2114. digitalWrite(tft8._wr, HIGH);
  2115. #endif // end !USE_FAST_PINIO
  2116. }
  2117. /*!
  2118. @brief Set the RD line HIGH. Used for parallel-connected interfaces
  2119. when reading data.
  2120. */
  2121. inline void Adafruit_SPITFT::TFT_RD_HIGH(void) {
  2122. #if defined(USE_FAST_PINIO)
  2123. #if defined(HAS_PORT_SET_CLR)
  2124. *tft8.rdPortSet = tft8.rdPinMask;
  2125. #else // !HAS_PORT_SET_CLR
  2126. *tft8.rdPort |= tft8.rdPinMaskSet;
  2127. #endif // end !HAS_PORT_SET_CLR
  2128. #else // !USE_FAST_PINIO
  2129. digitalWrite(tft8._rd, HIGH);
  2130. #endif // end !USE_FAST_PINIO
  2131. }
  2132. /*!
  2133. @brief Set the RD line LOW. Used for parallel-connected interfaces
  2134. when reading data.
  2135. */
  2136. inline void Adafruit_SPITFT::TFT_RD_LOW(void) {
  2137. #if defined(USE_FAST_PINIO)
  2138. #if defined(HAS_PORT_SET_CLR)
  2139. *tft8.rdPortClr = tft8.rdPinMask;
  2140. #else // !HAS_PORT_SET_CLR
  2141. *tft8.rdPort &= tft8.rdPinMaskClr;
  2142. #endif // end !HAS_PORT_SET_CLR
  2143. #else // !USE_FAST_PINIO
  2144. digitalWrite(tft8._rd, LOW);
  2145. #endif // end !USE_FAST_PINIO
  2146. }
  2147. #endif // end __AVR_ATtiny85__