# BME280 interactions with MISO/MOSI LED Matrix

**URL:** <https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840>\
**Category:** Networking, Protocols, and Devices\
**Created:** [April 14, 2022, 5:58am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840 "2022-04-14T05:58:44Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 5:58am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/1 "2022-04-14T05:58:44Z")

</div>

Got a major project with lotsa libraries. (See it on my projects here - talking alarm clock) Got a BME280 in today and wired it up I2C. Test program worked with a little tinkering. Running on Mega 2560. When I try to port to the main program it stops working. Ditto for the MP3 player. I can get both to work stand alone but when I try to meld them in to the big program things fall apart and won't compile.  
I'm sure its an include issue as the test program uses Wire.h and my main program does MOSI/MISO with SPI.h and the two seem to fight.

My main program talks fine to most of the stuff without Wire.h.

Any suggestions welcome. The code is a mile long (over 2500 lines) but the BME logic is small

```cpp
// #include <Wire.h> //I2C Driver
// #include <LiquidCrystal_I2C.h> //I2C LCD display driver for all LCD's
//
#include <LG_Matrix_Print.h> // LED matrix - test works
//
// microSD card device
//
#include <SPI.h> // SPI interface
#include <SD.h> // SD Card
//
#include <Bme280.h>
...
Bme280TwoWire sensor;
... Setup()
  //
  // BME280 init
  //
// None of this will compile
// sensor.begin(21, &SPI);
// sensor.begin(D1, &SPI); // What IO?
// sensor.setSettings(Bme280Settings::indoor());

... Sub is called in loop()

void readBME280()
{
//
auto temperature = String(sensor.getTemperature()) + " °C";
auto pressure = String(sensor.getPressure() / 100.0) + " hPa";
auto humidity = String(sensor.getHumidity()) + " %";
//
String measurements = temperature + ", " + pressure + ", " + humidity;
Serial.println(measurements);
//
}

```

---

<div class="post-metadata">

**Author:** ![groundFungus](https://avatars.discourse-cdn.com/v4/letter/g/73ab20/32.png) [@groundFungus](https://forum.arduino.cc/u/groundFungus)\
**Post date:** [April 14, 2022, 6:08am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/2 "2022-04-14T06:08:20Z")

</div>

> [@madmark2150](#):
>
> things fall apart and won't compile.

Please include the entire error message. It is easy to do. There is a button (lower right of the IDE window) called "copy error message". Copy the error and paste into a post in code tags. Paraphrasing the error message leaves out important information.

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 6:30am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/3 "2022-04-14T06:30:51Z")

</div>

Well this line:

```cpp
sensor.begin(21, &SPI);

```

gives this error:

```cpp
no matching function for call to 'Bme280TwoWire::begin(int, SPIClass*)'

```

Once everything is decommented it compiles but won't run. The LED matrix scrolls ONCE, it beeps twice (exiting setup) and STOPS. No heartbeat LED, nada.

---

<div class="post-metadata">

**Author:** ![PaulRB](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/paulrb/32/216330_2.png) [@PaulRB](https://forum.arduino.cc/u/PaulRB)\
**Post date:** [April 14, 2022, 6:39am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/4 "2022-04-14T06:39:19Z")

</div>

"TwoWire" means i²c, not SPI.

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 7:44am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/5 "2022-04-14T07:44:47Z")

</div>

Can I use BOTH at the same time?  
I tried FourWire and that choked

```cpp
sensor.begin(21, &SPI);

```

This, from TwoWire, works:

```cpp
// #include <Arduino.h>
#include <Wire.h>
#include <Bme280.h>

Bme280TwoWire sensor;

void setup() {
  Serial.begin(115200);
  Wire.begin();

  Serial.println("Setup Start");

  sensor.begin(Bme280TwoWireAddress::Primary);
  sensor.setSettings(Bme280Settings::indoor());
  Serial.println("Setup End");
}

void loop() {
  Serial.println("Loop top");
  auto temperature = String(sensor.getTemperature()) + " °C";
  auto pressure = String(sensor.getPressure() / 100.0) + " hPa";
  auto humidity = String(sensor.getHumidity()) + " %";

  String measurements = temperature + ", " + pressure + ", " + humidity;
  Serial.println(measurements);
  Serial.println("Test!");
  delay(5000);
}

```

But when I try to incorporate it into my sketch that ALREADY uses SPI to talk to the SD card and MOSO/MISO to chat with the LED matrix.  
I've got an FM radio module in parallel with the BME280 that seems to work.  
I've got a MEGA 2560 with terminal shield and the following active devices:  
RTC  
32Gb SD card  
32Gb Serial MP3 Player (that also will run the diag but not in the main program)  
Dual DHT's (indoor/outdoor)  
A 8x32 LED matrix display  
38kHz IR remote  
FM Radio I2C  
BME280 with SDA/SCL markings  
Both buzzer and speaker (selectable)  
LDR with both A & D outputs wired  
RGB LED (4 pin, CA)  
Traffic LED (R/Y/G) (4 pin, CC)  
Analog 5k pot for input  
Ack Button and Reset button

All of this is wired correctly and tested and aside from the MP3 player and the new BME280, everything is running like a top.

---

<div class="post-metadata">

**Author:** ![PaulRB](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/paulrb/32/216330_2.png) [@PaulRB](https://forum.arduino.cc/u/PaulRB)\
**Post date:** [April 14, 2022, 7:52am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/6 "2022-04-14T07:52:37Z")

</div>

> [@madmark2150](#):
>
> Can I use BOTH at the same time?

With the BME280 sensor? No.

Please read the forum guide in the sticky post. You can no longer claim to be new here.

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 8:16am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/7 "2022-04-14T08:16:21Z")

</div>

What did I do wrong? I'm using code tags.

---

<div class="post-metadata">

**Author:** ![GolamMostafa](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/golammostafa/32/239011_2.png) [@GolamMostafa](https://forum.arduino.cc/u/GolamMostafa)\
**Post date:** [April 14, 2022, 9:40am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/8 "2022-04-14T09:40:42Z")

</div>

> [@madmark2150](#):
>
> Got a BME280 in today and wired it up I2C.

Please, post the picture of your BME280; as, there are many types of breakout boards (Fig-1, 2, 3).

 ![bme280pic](https://europe1.discourse-cdn.com/arduino/original/4X/2/7/6/276ebcce124c43858ed860cb2e93665b2925cb22.png)

---

<div class="post-metadata">

**Author:** ![Idahowalker](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/idahowalker/32/238858_2.png) [@Idahowalker](https://forum.arduino.cc/u/Idahowalker)\
**Post date:** [April 14, 2022, 9:53am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/9 "2022-04-14T09:53:29Z")

</div>

funny thing

The posted code does not show this:

> [@madmark2150](#):
>
> I've got an FM radio module in parallel with the BME280 that seems to work.  
> I've got a MEGA 2560 with terminal shield and the following active devices:  
> RTC  
> 32Gb SD card  
> 32Gb Serial MP3 Player (that also will run the diag but not in the main program)  
> Dual DHT's (indoor/outdoor)  
> A 8x32 LED matrix display  
> 38kHz IR remote  
> FM Radio I2C  
> BME280 with SDA/SCL markings  
> Both buzzer and speaker (selectable)  
> LDR with both A & D outputs wired  
> RGB LED (4 pin, CA)  
> Traffic LED (R/Y/G) (4 pin, CC)  
> Analog 5k pot for input  
> Ack Button and Reset button
> 
> All of this is wired correctly and tested and aside from the MP3 player and the new BME280, everything is running like a top.

We are troubleshooting 2 different things.

Pick one. A BME280 wired on a breadboard all by itself, then use only the BME code. Or a complete project with all the code then post all your code.

Next pick a BME library and post the github site of the BME library you are using so we can see how to properly setup and the library. If you are just going to try to get the BME working just use the library example code.

Post an image of the BME module you are trying to use. Post an image of your project all wired up and not working.

---

<div class="post-metadata">

**Author:** ![PaulRB](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/paulrb/32/216330_2.png) [@PaulRB](https://forum.arduino.cc/u/PaulRB)\
**Post date:** [April 14, 2022, 11:13am UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/10 "2022-04-14T11:13:56Z")

</div>

> [@madmark2150](#):
>
> What did I do wrong? I'm using code tags

If the only thing you remember from the forum guide is about using code tags, please read it again.

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 1:56pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/11 "2022-04-14T13:56:11Z")

</div>

I did, dont be cryptic. I have the complete project on my project page as i already said. The code, wiring, construction, schematics, 3D print files, etc are all there.

[Major project link](https://create.arduino.cc/projecthub/madmark2150/talking-alarm-clock-with-8x8x4-matrix-display-2ae9f6?ref=user&ref_id=2067802&offset=0)

---

<div class="post-metadata">

**Author:** ![GolamMostafa](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/golammostafa/32/239011_2.png) [@GolamMostafa](https://forum.arduino.cc/u/GolamMostafa)\
**Post date:** [April 14, 2022, 2:01pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/12 "2022-04-14T14:01:06Z")

</div>

> [@madmark2150](#):
>
> I have the complete project on my project page as i already said.

Give a link to your project page or post the image of your BME280 sensor.

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 2:04pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/13 "2022-04-14T14:04:50Z")

</div>

I am trying to add a BME280 to a major project. The BME280 is the small (tiny really, about 1 cm sq) module with one mounting hole in the corner, it was the left module in the pics shown in post #8 but 5v. It is correctly wired as the TWOWIRE sketch works flawlessly by itself.  
Lifting the demo code and dropping it into my BIG sketch fails on the SAME hardware.  
I think its a driver issue.  
The BME280 has SDA/SDC pins, these are wired in parallel with another, functioning, device, the **SD card** - WRONG Is in parallel with FM Radio module using I2C. Sorry abiout the confusion.

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 2:09pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/14 "2022-04-14T14:09:30Z")

</div>

Here you go:  
[Major project link](https://create.arduino.cc/projecthub/madmark2150/talking-alarm-clock-with-8x8x4-matrix-display-2ae9f6?ref=user&ref_id=2067802&offset=0)

Wiring:

 ![1649789511768](https://europe1.discourse-cdn.com/arduino/original/4X/7/6/d/76d5ef65297390a8ad2dc3e2b1986d990a068e6a.jpeg)

The device is getting power from the terminal shield via a 25W @ 5VDC medical grade, Mean Well brand PS pulling a peak of about 600mA according to the ammeter shown.

 ![1649956116465](https://europe1.discourse-cdn.com/arduino/original/4X/8/8/2/8827455d3a456fbc5b29d07bbeb8c8353bdcca18.jpeg)

 ![1649956157538](https://europe1.discourse-cdn.com/arduino/original/4X/2/2/e/22eefdee5066000fac26e882c2d1ef2a605f0b51.jpeg)

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 2:12pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/15 "2022-04-14T14:12:32Z")

</div>

The full code, as mentioned, is 2500+ lines. Do you REALLY want to dig thru that to find less than a dozen lines of active code? I posted what crashes the project to the point loop() stops running (heartbeat LED stops).

I can .ZIP it and send it to you if you want. The full current code won't post on the project hub, it runs out of space about 1800 lines in.

```cpp
//
// Cindy's alarm clock - By Mark M. Lambert on February 20th, 2022
// Copyright Mark M. Lambert - All Rights Reserved
// May be used or excerpted with attribution
//
const float Version = 7.04;
//
// V7.04 - 13Apr22 - MML - Tighten, saved 10% of RAM!
// V7.03 - 11Apr22 - MML - Refine
// V7.02 - 10Apr22 - MML - Add Stopwatch
// V7.01 - 07Apr22 - MML - Clean up
// V7.00 - 05Apr22 - MML - Add new features and get sound working
// V6.24 - 30Mar22 - MML - Cut down the verbosity
// V6.23 - 28Mar22 - MML - Display weather Hi/lo
// V6.22 - 25Mar22 - MML - Remote dims LEDs - override pot
// V6.21 - 24Mar22 - MML - Use pot for matrix brightness
// V6.20 - Omitted to prevent being mistaken for a large rev
// V6.19 - 18Mar22 - MML - Add radio code per original buttons
// V6.18 - 17Mar22 - MML - Try I2C FM module with antenna! :D
// V6.17 - 16Mar22 - MML - Swap alarm set and relay on LED's
// V6.16 - 11Mar22 - MML - Work on MP3 player
// V6.15 - 10Mar22 - MML - Fix bug in alarm on
// V6.14 - 08Mar22 - MML - Turn off log dump & clean up auto off logic
// V6.13 - 06Mar22 - MML - Invert Colon
// V6.12 - 04Mar22 - MML - Install SD card - read data on first compile! :D
// V6.11 - 03Mar22 - MML - Lint
// V6.10 - Omitted to prevent being mistaken for a large rev
// V6.09 - 01Mar22 - MML - Tweak display timing
// V6.08 - 28Feb22 - MML - Indicate power relay state
// V6.07 - 27Feb22 - MML - Resequence 420 & 840, simplify setting
// V6.06 - 26Feb22 - MML - Add clock set (after glitching the RTC)
// V6.05 - 25Feb22 - MML - Wire & rough out radio code - polish
// V6.04 - 24Feb22 - MML - Cleanup & tweak functionality
// V6.03 - 23Feb22 - MML - Add four digit 7 segment display & RTC
// V6.02 - 22Feb22 - MML - Rough out command framework. RTC module due today
// V6.01 - 21Feb22 - MML - LCD, DHT working, 8x8x4 matrix & buzzer up, time displaying
// V6.00 - 20Feb22 - MML - Subset/superset of Rick Box to be custom alarm clock
// V5.18 - 18Feb22 - MML - Fork from RTC project. See for 'tween versions
// V1.00 - 06Dec21 - MML - Baseline with LCD - Mega 2650 has built in pullups
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
//
// Device Master List
// ==================
// Mega 2560 Processor - Works
// Screw terminal shield - Works
// 8x8x4 dot matrix display module MOSI/MISO - Works
// R/Y/G Traffic Light w/ traffic signal shroud - Works
// RGB 10mm LED - Works
// LDR - Works, no idea what to make it do
// IR remote command in & remote - Works - Use wide FOV mount
// RTC - Works
// Indoor DHT11 Temp/Humidity - Works
// Outdoor DHT11 Temp/Humidity - Works, remote wiring issue
// MP3 player - Serial Control - for rude wake up messages - Sorta works
// Coffee Pot Relay - Works great!
// SD Card with MISO/MOSI - Works - No installed in unit #2 yet, on order
// Reset Button - Works
// Ack Button (also Select) - Works
// Analog pot for random input - Works
// I2C FM radio module - Works, post amp issues, needs +12
// 5-to-12 Converter - Works, not tested for max output
// Buzzer - Works, obnoxious
// 1" Piezo speaker - Works, soft
//
// ==================================
// Start of Pin Constants
// ==================================
//
// Analogs first
//
int xx = 0; // Placeholder value
//
const int Vnoise = A2; // Random number seed is open AI
const int Vin = A3; // Power supply direct output monitor - NOT USED
//
const int I2C_A4 = A4; // RESERVED
const int I2C_A5 = A5; // RESERVED
//
// A6-A13 - SPARE
//
const int LDR_AI = A14; // LDR analog See D34
//
// Variable input device
//
const int Wiper = A15; // Wiper from 5k pot for data entry
//
// Float constants for wiper
//
const float aiSteps = 1024.0; // 10 bit ADC
const float VoltsPerBit = (5.0 / aiSteps); // Compute bit weight based on +5 Vin max
const float stepsPerHr = aiSteps / 24.0; // Hours input
const float stepsPerMin = aiSteps / 60.0; // Minutes input
const float stepsPerYr = aiSteps / 100.0; // Year input, 20xx presumed
const float stepsPerMon = aiSteps / 12.0; // Months input
const float stepsPerDt = aiSteps / 31.0; // Date input
const float stepsPerDoW = aiSteps / 7.0; // Day input, sat = 1, fri = 7
const float stepsPerYN = aiSteps / 2.0; // 0/1
//
// Analogs end
// -----------
// Now digitals 
//
// D0 and D1 are rx/tx for serial programming
//
// 2-10 sorta spare
//
// D11 & 12 reserved for MOSI/MISO
// D13 is LED_BUILTIN and is used (maybe) by MOSI/MISO devices
//
// Comm channel I/O's
//
const int S3_TX = 14; // ESP-01 WiFi - not wired
const int S3_RX = 15;
//
const int S2_TX = 16; // Knob radio - OUT - See I2C
const int S2_RX = 17;
//
const int S1_TX = 18; // MP3 player
const int S1_RX = 19;
//
// I2C was brought out to buss bars for mass connections - wasn't needed
// Actually the one I2C device (FM radio) connected thru the SDA/SCL pins up by D13
//
const int I2C_SDA = 20; // These are attached to the matching buss bars for bussing to all I2C devices
const int I2C_SCL = 21; // Pullups are internal to Mega 2560
//
// 22-25 free
//
// RTC I/O pins - Working fine - Use SET_CLOCK project to preset time
//
const int kCePin = 26; // Chip Enable - grn
const int kIoPin = 27; // Input/Output - yel
const int kSclkPin = 28; // Serial Clock - orn
//
const int ledR = 29; // RGB LED red - ACTIVE LOW - these might move to PWM's for dimming.
const int ledG = 30; // RGB LED green
const int ledB = 31; // RGB LED blue
//
// 32-33 free
//
const int LDR_DI = 34; // LDR Digital - See A14
//
// Humidity/temp sensors - working great
//
const int DHTPIN2 = 35; // Digital pin connected to the outdoor DHT sensor
const int DHTPIN = 36; // Digital pin connected to the indoor DHT sensor
//
// IR remote control input - noisy - doesn't like LED lighting
// Increased FOV and operatoin is more reliable
//
const int RECV_PIN = 37; //IR Receiver input pin
//
// On the remote there are seven rows of three buttons each. 
// Each has a unique code. 
// We're going to define the button codes here instead
// of scattering them in a massive SWITCH.
//
// ----------------------
// _00 = _RC, 0 indexed
//
// All the little IR remotes appear to use the same set of codes
// Determined empirically:
//
const int Btn_00 = 23971; // Top Row, left button - Row 0, Col 0
const int Btn_01 = 25245; // Row 0, Col 1 - 
const int Btn_02 = 7651; // Top Row, right button - Row 0, Col 2
//
const int Btn_10 = 8925; // Row 1, col 0 - (red)
const int Btn_11 = 765;
const int Btn_12 = 15811;
//
const int Btn_20 = 8161;
const int Btn_21 = 22441;
const int Btn_22 = 28561;
//
const int Btn_30 = 26775;
const int Btn_31 = 26521;
const int Btn_32 = 20401;
//
const int Btn_40 = 12495;
const int Btn_41 = 6375;
const int Btn_42 = 31365;
//
const int Btn_50 = 4335;
const int Btn_51 = 14535;
const int Btn_52 = 23205;
//
const int Btn_60 = 17085;
const int Btn_61 = 19125;
const int Btn_62 = 21165; // Bottom Row, right button
//
// Ordered a different brand of IR remote that has a DIFFERENT set of codes!
// Haven't sussed everything out yet but there is at least SOME overlap
// I've got half a dozen of these little remotes and this is the first
// one that isn't a clone. Stay tuned - more to come
//
// ----------------------
//
// 38, 39 - SPARE
//
// Relay pin
//
const int K2 = 40; // Coffee Pot
//
// 41-42 SPARE
//
const int Buzzer = 43; // Annunciator
const int Speaker = 44; // Speaker - tone command
//
const int AckBtn = 45; // Acknowledge button to silence alarn
//
// Traffic lights are near top end of DOs
//
const int TL_R = 46; // Alarm On
const int TL_Y = 47; // Follows AckBtn
const int TL_G = 48; // Heartbeat
//
// SD card is MOSI/MISO, needs its own CS line
//
const int sdSel = 49; // SD card Chip Select
//
// 50-53 reserved for MOSI/MISO
// SPI:
// 50/25/11 (MISO) <<== not needed for output only
// Needed for SD card
// 51/24/12 (MOSI)
// 52/23/13 (SCK)z 
// 53/22/10 (SS) <<== Device Select
//
// 11, 12 & 13 Are MISO/MOSI - AKA SPI on UNO
// 22-25 reserved for MOSI/MISO SP1 devices
// this conflicts with other docs or it may be
// uno vs mega 2560
//
// Initializes the SD library and card. 
// This begins use of the SPI bus 
// pins 11, 12, and 13 on Arduino UNO boards; 
// pins 50, 51, and 52 on the Mega
// and the chip select pin, 
// which defaults to the hardware SS pin 
// pin 10 on Arduino UNO boards, 
// pin 53 on the Mega 
//
// Got dot matrix and 4 digit readouts in
// The matrix needs MOSI and I think the readouts
// are I2C, but I won't be sure until they arrive
// Modules arrived, waiting on cables
//
// Mega 2560 pinout is correct - worked on first try
//
const int MISOLED = 50; // Needed for 8X8 LED matrix comms
const int MOSILED = 51;
const int SCKLED = 52; // builtin LED & SPI clock
const int CSLED = 53; // 8x8 x4 LED matrix CS line
//
// End of Digitals
//
// ==================================
// End of Pin Constants
// ==================================
//
// Device Constants
//
const unsigned interval = 1200; // Don't overpoll
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
//
// EEPROM image - we need pointers, not variables
//
const int promTempFC = 0; // Flag - EEPROM BASE - ONLY ADD AT END
const int promAlarmSet = 1; // Flag
const int promMatrixBright = 2; // Int, 0-15
const int promClockMode12 = 3; // Flag
const int promScrollRateMs = 4; // Int 50 to 100 typical
const int promAlarmHr = 5; // Int - 0-23
const int promAlarmMin = 6; // Int - 0-59
const int promFrequency = 7; // Int - 889-1079, two BYTES
const int promChimeOnHr = 9; // Int - 0-23 - Chime start this hour
const int promChimeOffHr = 10; // Int - 0-23 - Chime stop this hour
// const int promRGBled = 11; // Int as bitmask, neg logic
const int promBingBong = 12; // Flag - 1 buzzer, 0 speaker
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
//
// Includes - DO NOT REORDER
//
#include <EEPROM.h> // EEPROM support for tables
#include <stdio.h>
#include <DHT.h> // Digital Humidity/Temp sensor library
#include <DS1302.h> // RTC library
#include <IRremote.h> // IR Remote Library
//
// These three includes MUST be in this order or weird "Error compiling for board Arduino Mega or Mega 2560." error
// Wire.h must load first
//
// #include <Wire.h> //I2C Driver
// #include <LiquidCrystal_I2C.h> //I2C LCD display driver for all LCD's
//
#include <LG_Matrix_Print.h> // LED matrix - test works
//
// microSD card device
//
#include <SPI.h> // SPI interface
#include <SD.h> // SD Card
//
// #include <Bme280.h>
//
File LogFile; // File object
// ----------------------------------------------------------------------------
//
// #include <SoftwareSerial.h> // MEGA has real ports
//
// Define the RX and TX pins to establish UART communication with the MP3 Player Module.
//
static int8_t loud[] = {0x31, 0x1E, 0x01}; // 1E (max) volume, Play song 03
static int8_t wake[] = {0x35, 0x02}; // Wake up device
static int8_t Reset[] = {0x35, 0x05}; // Reset device
//
// ----------------------------------------------------------------------------
//
// I2C FM radio - test says it works - must be below WIRE.H
//
#include <radio.h> // Generic
#include <TEA5767.h> // Specific - defines terms like RADIO_BAND_FM, etc./
//
// The band that will be tuned by this sketch is FM.
//
#define FIX_BAND RADIO_BAND_FM // US
//
// Station 107.9 FM
//
// #define FIX_STATION 1079
#define FIX_STATION 1029
//
TEA5767 radio; // Create an instance of Class for TEA5767 Chip
//
// ----------------------------------------------------------------------------
//
// Start building objects
//
// Create 8x8x4 Matrix LED object
// Number of 8x8 segments
//
const int segments = 4;
//
LG_Matrix_Print lmd(segments, CSLED);
//
// Create a DS1302 RTC object.
//
DS1302 rtc(kCePin, kIoPin, kSclkPin);
//
// Create humidity/temp object
//
//#define DHTTYPE DHT11 // DHT 11
//DHT dht(DHTPIN, DHTTYPE); // Create Object
//
// Indoor will be upgraded to DHT-22 when it arrives
//
DHT dht(DHTPIN, DHT11); // Create Object for indoor
DHT dhtO(DHTPIN2, DHT11); // Create Object for outdoors
//
// IR Remote control object
//
IRrecv irrecv(RECV_PIN); // Build IR receiver object
//
// This next line throws a compiler warning about being depreciated
// but I've not found what to replace it with that compiles, runs
// and actually works.
//
decode_results results; // Not sure about this, but it works
//
// BME280 Temp/humidity/Baro
//
// TwoWire sensor;
// Bme280TwoWire sensor;
// -------------------------
// Objects built
// -------------------------
//
// Global state flags need to come from EEPROM
//
// We have to manually, byte by byte figure out what goes where
// in the EEPROM. We've got 4k to tinker with and are limited to 
// ~100k write operations on any given memory location. Rears
// are unlimited. So you want to check and only write changes
//
// 0000 - 0FFF - EEPROM range. Everything runs on bytes
//
int BaseAddr = 0;
int TopAddr = 4095;
//
// ******************************
// Stare of EEPROM address pointers
//
// define start of each object in EEPROM - ONLY ADD ITEMS AT END
//
// Declare stuff from EEPROM
//
int clockMode12 = false;
int AlarmSet = false;
int tempFC = false;
int MatrixBright = false;
int scrollRateMs = false;
int K2State = false;
int alarmHr = 11; //Default to 11:00a
int alarmMin = 00;
int onbyAlarm = false;
int RGBstate = 0b00001000; // Default to all off
int bingBong = true; // Default to buzzer
//
// Time & date setting vars - might not need all
//
int clockDoW; //Day of week
int clockHr;
int clockMin;
int clockDt;
int clockMon;
int clockYr;
//
int aborted = false; //Return flag from sloChime and Chime
//
const int MatrixMax = 15; // Max intensity value
//
// Temp/Humidity
//
float h, f, c; // Humidity, TempF, TempC - inside
float hO, fO, cO; // Humidity, TempF, TempC - outside
//
int valx = 0; // variable to store the value read
//
int MSH; // Pull TWO bytes for numbers > 255 from EEPROM
int LSH;
//
int Frequency; // Radio station 889-1079
//
int lastLDR = false; // LDR state presumed off
// ============================================
// SETUP
// ============================================
//
// Globalize
//
// End of EEPROM address pointers
// ******************************
//
String logName = "logmm-yy.txt\0"; //Template
//
// Stopwatch start
//
unsigned long startTime = 0;
//
float tmpF; // Working float
//
// Peak and low temp/humidity vars - start with defaults
//
float dailyPeakF = -100.0;
float dailyLowF = 200.0;
int dailyPeakH = 0;
int dailyLowH = 100;
//
float dailyPeakFO = -100.0;
float dailyLowFO = 200.0;
int dailyPeakHO = 0;
int dailyLowHO = 100;
//
// Time holders for F
//
int peakFHr;
int peakFMin;
int lowFHr;
int lowFMin;
//
int peakFHrO;
int peakFMinO;
int lowFHrO;
int lowFMinO;
//
// Time holders for H
//
int peakHHr;
int peakHMin;
int lowHHr;
int lowHMin;
//
int peakHHrO;
int peakHMinO;
int lowHHrO;
int lowHMinO;
//
// Dim by remote or knob
int dimMode = true; // Knob /Remote
//
int chimeOnHr = 11; // First chime time
int chimeOffHr = 22; // Last chime time
//
const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
const char *dows[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
//
// Time t; // Device data type - read RTC
//
String MatrixText; // Indeterminate display string
// =================================================
//
// SETUP BEGINS
//
void setup()
{
  //
  // serial is 0/1, s1 is 18/19 - MP3, s2 is 16/17 - radio
  //
  Serial.begin(115200); // Warm up comm ports
  Serial1.begin(9600); // MP3 player example shows 9600
  // Serial2.begin(9600); // SPARE / FM radio
  //
  // Pull config
  //
  clockMode12 = EEPROM.read(promClockMode12 ); // Default to 12 hr time, false for 24, 
  AlarmSet = EEPROM.read(promAlarmSet ); // Alarm Set/not, save in EEPROM
  tempFC = EEPROM.read(promTempFC ); // Farenheit/not celcius
  MatrixBright = EEPROM.read(promMatrixBright); // Start near dim
  scrollRateMs = EEPROM.read(promScrollRateMs); // scroll rate, lower is faster
  alarmHr = EEPROM.read(promAlarmHr ); // Hour
  alarmMin = EEPROM.read(promAlarmMin ); // Minute
  LSH = EEPROM.read(promFrequency ); // 889 to 1079 for FM radio
  MSH = EEPROM.read(promFrequency +1); // 889 to 1079 for FM radio
  Frequency = word(MSH, LSH);
  chimeOnHr = EEPROM.read(promChimeOnHr ); // Hour chime starts
  chimeOffHr = EEPROM.read(promChimeOffHr ); // Hour chime ends
  // RGBstate = EEPROM.read(promRGBled ); // Last RGB state
  if ( (RGBstate <= 0b00000000) || (RGBstate > 0b00001000)) RGBstate = 0b00001000; // Uninitialized maps to all off
  //
  bingBong = EEPROM.read(promBingBong ); // Last Annunciator State
  //
  // Send this to SD card too
  //
  Serial.println(F("Stored config:") );
  Serial.println(F("==============") );
  Serial.print(F("Version: ") );
  Serial.println( String( Version) );
  //
  Serial.print(F("AM/PM-24: ") );
  Serial.println( String( clockMode12) );
  //
  Serial.print(F("Alarm Set: ") );
  Serial.println( String( AlarmSet) );
  //
  Serial.print(F("Temp FC: ") );
  Serial.println( String( tempFC) );
  //
  Serial.print(F("Matrix Bright: ") );
  Serial.println( String(MatrixBright) );
  //
  Serial.print(F("Scroll Rate (ms): ") );
  Serial.println( String(scrollRateMs) );
  //
  Serial.print(F("Alarm Hr: ") );
  Serial.println( String( alarmHr) );
  //
  Serial.print(F("Alarm Min: ") );
  Serial.println( String( alarmMin) );
  //
  Serial.print(F("FM Radio Preset: ") );
  Serial.println( String( Frequency) );
  //
  Serial.print(F("Chime On Hr: ") );
  Serial.println( String( chimeOnHr) );
  //
  Serial.print(F("Chime Off Hr: ") );
  Serial.println( String( chimeOffHr) );
  //
  Serial.print(F("RGB LED state: ") );
  Serial.println( String(RGBstate, BIN) );
  //
  Serial.print(F("Speaker/Buzzer: ") );
  Serial.println( String(bingBong ) );
  //
  // Sanity check for uninitialized EEPROM
  //
  if (clockMode12 != false ) clockMode12 = true;
  if (AlarmSet != false ) AlarmSet = true;
  if (tempFC != false ) tempFC = true;
  if ((MatrixBright > 15) || (MatrixBright < 0)) MatrixBright = 2;
  //
  if ((scrollRateMs > 200) || (scrollRateMs < 25)) 
    {
    scrollRateMs = 50;
    logProm(promScrollRateMs, scrollRateMs);
    }
  //
  // Default alarm
  //
  if ((alarmHr > 23) || (alarmHr < 0) ) alarmHr = 11;
  if ((alarmMin > 59) || (alarmMin < 0) ) alarmMin = 00;
  //
  if ((Frequency < 889) || (Frequency > 1079) ) 
    {
    Serial.println(F("Frequency defaulted"));
    Frequency = 1029; // Yes, force local preset
    }
  //
  tweakFreq(Frequency);
  //
  // Interesting hardware note. If unpowered, the serial port
  // BEGIN statement will bring up the digital portion of the knob FM card
  // just from the serial line - VERY STRANGE
  // But at least it tells me that I'm wired to the right port
  //
  // Fire up RTC
  //
  rtc.writeProtect(false); //Gotta unlock before letting it run
  rtc.halt(false); //Let clock run
  Time t = rtc.time(); // Device data type - read RTC
  //
  //
  // INPUT is default but we need to make sure they don't float with INPUT_PULLUP
  // Declare all inputs as pullups
  //
  pinMode(AckBtn, INPUT_PULLUP); // Alarm acknowledge
  pinMode(LDR_DI, INPUT_PULLUP); // LDR input sense
  //
  // Relay
  //
  pinMode(K2, OUTPUT); // Coffee pot
  digitalWrite(K2, false); // Coffee pot, default off
  //
  pinMode(Buzzer, OUTPUT); // Harsh
  pinMode(Speaker, OUTPUT); // Low volume
  //
  // Traffic lights
  //
  pinMode(TL_G, OUTPUT); // Heartbeat
  pinMode(TL_Y, OUTPUT); // Silent
  pinMode(TL_R, OUTPUT); // Alarm set
  //
  digitalWrite(TL_G, LOW); //Turn off  
  digitalWrite(TL_Y, LOW); //Turn off  
  digitalWrite(TL_R, LOW); //Turn off  
  //
  // RGB LED
  //
  pinMode(ledR, OUTPUT);
  pinMode(ledG, OUTPUT);
  pinMode(ledB, OUTPUT);
  //
  // Restore state from prom - only one on at a time
  //
  setRGB();
  //
  // Pins all set, anything not listed is a hi-Z input
  //
  // ============
  //
  // 8x8x4 LED matrix is cool, readable display
  //
  lmd.setEnabled(true);
  lmd.setIntensity(MatrixBright); // 0 = low, 15 = high - set via pot or LDR or command
  lmd.clear();
  lmd.stopTicker(); //Stop any old message
  //
  chime(1);
  waitTicker("Cindy's Alarm Clock-V" + String(Version));
  //
  // Turn on remote
  //
  irrecv.enableIRIn();
  //
  // Crank up humitity/temp sensor
  //
  dht.begin(); // Fire up Inside temp/humidity sensor
  dhtO.begin(); // Fire up Outside temp/humidity sensor
  Read_DHT(); // Read temp/humidity to prime vars
  //
  // Ok fine, we want to test the SD card reader with this code
  //
  String tmpStr = "log";
  //
  if (!SD.begin(sdSel)) // Crank up SD card
    {
    Serial.println(F("SD init failed"));
    }
  else
    {
    if (t.mon < 10) tmpStr = "log0";
    tmpStr += String(t.mon) + "-" + String(t.yr - 2000) + ".txt";
    logName = tmpStr + "\0";
    //
    // DOS FAT 8.3 file names only
    //
    Serial.print(F("Current Log file: ") );
    Serial.println(tmpStr);
  }
  //
  // Special stuff for I2C radio module
  //
  // Initialize the Radio 
  //
  radio.init();
  //
  // Enable information to the Serial port
  //
  radio.debugEnable();
  //
  // Preset to 1079
  //
  radio.setBand(FIX_BAND);
  radio.setFrequency(Frequency);    
  //
  radio.setVolume(10); // 0-15
  radio.setMono(false); // No external indicator
  //
  // End of radio stuff
  //
  append(F("Restart"));
  //
  // We should see updated data
  //
  // readAfile(logName); // Try to read log file & display - takes forever for long file,
  // slows init
  //
  chime(2); // Let em know we're live
  //
  /*
  Serial.println("Wake");
  cmdMP3(wake, 2);
  delay(500);
  //
  Serial.println("Reset");
  cmdMP3(Reset, 2);
  delay(500);
  //
  Serial.println("Loud & play");
  cmdMP3(loud, 3);
  delay(500);
  //
  */
  //
  // Tiny bit of logic to init LDR toggle
  lastLDR = digitalRead(LDR_DI);
  //
  // BME280 init
  //
// sensor.begin(21, &SPI);
// sensor.begin(D1, &SPI); // What IO?
// sensor.setSettings(Bme280Settings::indoor());
  //
}
// ============================================
//
// SETUP ends
//
// ============================================
// ============================================
//
// LOOP BEGINS
//
// ============================================
//
// Declaring vars inside SWITCH blows up
// Globals
//
File aFile; // File handle
//
int tmp; // Working var
int lastSec;
//
String colon = ":"; // Time marker default
//
// Indeterminate strings fluff up the heap.
//
String tmpStr; // Working strings
String IRval; // Reading from remote
String LastIRCmd;
//
//
// Fall into runtime
//
void loop() 
  {
  //
  Time t = rtc.time(); // Poll clock
  // 
  // Let LED matrix running until eom
  // 
  if (!lmd.updateTicker()) lmd.stopTicker(); //Stop at end
  //
  // Fast execution items lead
  //
  // We need to watch the RTC and trigger when the seconds change
  //
  // hard poll IR while waiting
  //
  while (t.sec == lastSec) // Wait for clock to tick
    {
    //
    // Watch for rising edge on LDR and sequence RGB led
    //
    tmp = digitalRead(LDR_DI); // Don't let state change as we rattle thru logic
    //
    if (tmp) // is high
      {
      //
      if (lastLDR != tmp) // Wasn't
        {
        //
        // Rising edge
        //
        lastLDR = tmp; // is now
        //
        // Walk RGB LED thru its paces
        //
        RGBstate = RGBstate << 1; // Shift left once
        if (RGBstate > 0b00001000) RGBstate = 0b00000001;
        //
        setRGB();
        //
        }
      //
      // Is and was or just rose, do nothing
      //
      }
    else
      {
      //
      // Is low, force same for next rising edge
      //
      lastLDR = false;
      //
      }
    //
    t = rtc.time(); // Get latest
    //
    // IR remote code is big switch.
    // There are 21 different buttons with unique responses
    //
    // IR Remote needs to be shielded from other light sources
    // Umm dunno how fast we should poll this. Its fast polling now. 
    // but we might need to slow it down
    //
    // We'll use the pot to control the matrix brightness
    // when not othrewise busy
    //
    if (dimMode) lmd.setIntensity(analogRead(Wiper) / 64);
    //
    CheckIR(); // Does 21 different functions
    //
    // Update status lights in real time
    //
    digitalWrite(TL_R, digitalRead(K2)); // Reminder that power relay is on is RED
    digitalWrite(TL_Y, AlarmSet); // Show amber if alarm is set
    //
    if (!lmd.updateTicker()) lmd.stopTicker(); //Stop at end
    //
    }
  //
  // New second passes
  //
  digitalWrite(TL_G, !digitalRead(TL_G)); //Toggle heartbeat on second
  //
  lastSec = t.sec; // Note this second
  //
  // Alternate : and . as tic-tok on 8x8x4 matrix
  //
  colon == ":" ? colon = "." : colon = ":";
  //
  // Display time
  //
  formTime();
  //
  // Ok, from here on out we have our activities.
  // Each looks at the time and does their thing
  //
  // Check to see if the coffee pot is still on after an hour
  // if so, turn it off
  //
  int tempHr = alarmHr + 1;
  if (tempHr > 23) tempHr = tempHr - 24; //Compensate for past midnight
  //
  if ( ( (tempHr == t.hr) && 
         (alarmMin == t.min) ) && onbyAlarm)
    {
    digitalWrite(K2, LOW); //Turn off
    onbyAlarm = false;
    K2State = false;
    //
    Serial.print(F("K2 Auto off: ") );
    Serial.print(String(tempHr) + " " + String(t.hr) );
    //
    blip(); // Little noise to get you to look
    waitTicker(F("Aux relay auto off")); // Let user know
    formTime(); // Show time
    chime(3); // Different
    }
  //
  // Check for alarm time being set
  //
  if ( (alarmHr == t.hr) && 
        (alarmMin == t.min) && 
        (t.sec == 0) &&
         AlarmSet)
    {
    //
    // Kick on coffee pot relay - we should turn this
    // off automatically after an hour
    //
    blip(); // prealarm noise
    digitalWrite(K2, HIGH); // Load comes on with alarm
    K2State = true; // Internal state flag - Y not read IO?
    onbyAlarm = true; // Alarm turned us on
    dimMode = true; // bring up display
    //
    // Wakey Wakey!
    //
    waitTicker(F("Wakey! Wakey!"));
    formTime(); //Show time
    //
    sloChime(10);
    if (!aborted)
      {
      waitTicker(F("Get up & PEE! The world's on FIRE!"));
      formTime(); //Show time
      //
      sloChime(10);
      if (!aborted) 
        {
        waitTicker(F("Outta bed, sleepy head!"));
        formTime(); //Show time
        sloChime(10);
        }
      //
      }
    //
    }
    //
    // Show temp at 1/4 past minute
    //
    if ( (t.sec == 15) && !lmd.updateTicker() )
      {
      Read_DHT(); // Read temp/humidity
      tempFC ? lmd.ticker(String(f, 1) + "F", scrollRateMs) : 
               lmd.ticker(String(c, 1) + "C", scrollRateMs);
      //
// readBME(); // Lessee
      }
    //
    // Show Date at 30 - add month names
    //
    if ( (t.sec == 30) && !lmd.updateTicker() ) 
          //
          {
          lmd.ticker(String(months[t.mon -1]) + 
          " " + String(t.date) + 
          ", " + String(t.yr), scrollRateMs);
          }
    //
    // Show RH at 3/4 of minute - use reading from :15
    //
    if ( (t.sec == 45) && !lmd.updateTicker() )
          lmd.ticker(String(h, 0) + "% RH", scrollRateMs);
  //
  // Min = 0 & sec = 0 = hour strike
  //
  if ( (t.min == 0) && (t.sec == 0) )
    {
    blip(); //Little noise to make you look
    waitTicker(F("Cuckoo! Cuckoo!"));
    formTime(); // Show time
    //
    tmp = t.hr; // Time from globals
    //
    if ((tmp > 12) && (clockMode12)) tmp = tmp - 12; //Civilian time
    //
    // Start and end times need to be selectable
    if ((t.hr >= chimeOnHr) && (t.hr <= chimeOffHr)) // Only chime 11A-11P per swmbo
      {
      sloChime(tmp); //Change to MP3 "Bong" when I get it installed
      }
    //
    }
  //
  // Later in execution overrides time display above
  //
  if ((t.hr == 16) && (t.min == 20) && (t.sec == 0))
    {
    blip(); //Little noise to make you look
    waitTicker(F("It's 4:20! SMOKE BREAK!"));
    formTime(); // Show time
    sloChime(4);
    //
    waitTicker(F("It's 4:20! Time to roll a fattie!"));
    formTime(); // Show time
    sloChime(2);
    }
  //
  if ((t.hr == 20) && (t.min == 40) && (t.sec == 0))
    {
    blip(); //Little noise to make you look
    waitTicker(F("It's 8:40! TIME TO SMOKE!"));
    formTime(); // Show time
    sloChime(8);
    //
    waitTicker(F("It's 8:40! Time to Relax!"));
    formTime(); // Show time
    sloChime(4);
    }
  //
  // Log data on 1/4 hour
  //
  if ( ((t.min == 0) || 
        (t.min == 15) || 
        (t.min == 30) || 
        (t.min == 45)) && (t.sec == 0) )
        append("@ :" + String(t.min)); // Append to log
  //
  // Midnight data dump and reset, use value as flag in case we miss the moment.
  //
  if ( (t.hr == 0) && (t.min == 0) && (t.sec <= 15) && (dailyLowF != 200.0) )
    {
    logIt(); // Make log entry with days data
    }
  //
  } // End of LOOP
// =============================================================================
// =============================================================================
// Functions
// =============================================================================
// =============================================================================
//
// Function to read and display Temp Humidity from sensor
//
void Read_DHT()
  {
  Time t = rtc.time(); // Device data type - read RTC
  //
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  //
  h = dht.readHumidity(); // Get humidity
  c = dht.readTemperature(false); // Read temperature as Celsius (the default)
  f = dht.readTemperature(true); // Read temperature as Fahrenheit (isFahrenheit = true)
  //
  hO = dhtO.readHumidity(); // Get humidity
  cO = dhtO.readTemperature(false); // Read temperature as Celsius (the default)
  fO = dhtO.readTemperature(true); // Read temperature as Fahrenheit (isFahrenheit = true)
  //
  if (f < dailyLowF) 
    {
    dailyLowF = f;
    lowFHr = t.hr;
    lowFMin = t.min;
    showF(F(" New F Lo "), f);
    }
  //
  if (f > dailyPeakF) 
    {
    dailyPeakF = f;
    peakFHr = t.hr;
    peakFMin = t.min;
    showF(F(" New F Hi "), f);
    }
  //
  // Repeat for humidity
  //
  if (h < dailyLowH) 
    {
    dailyLowH = h;
    lowHHr = t.hr;
    lowHMin = t.min;
    showH(F(" New H Lo "), h);
    }
  //
  if (h > dailyPeakH) 
    {
    dailyPeakH = h;
    peakHHr = t.hr;
    peakHMin = t.min;
    showH(F(" New H Hi "), h);
    }
  //
  // outside
  //
  if (fO < dailyLowFO) 
    {
    dailyLowFO = fO;
    lowFHrO = t.hr;
    lowFMinO = t.min;
    showF(F(" New Outside F Lo "), fO);
    }
  //
  if (fO > dailyPeakFO) 
    {
    dailyPeakFO = fO;
    peakFHrO = t.hr;
    peakFMinO = t.min;
    showF(F(" New Outside F Hi "), fO);
    }
  //
  // Repeat for humidity
  //
  if (hO < dailyLowHO) 
    {
    dailyLowHO = hO;
    lowHHrO = t.hr;
    lowHMinO = t.min;
    showH(F(" New Outside H Lo "), hO);
    }
  //
  if (hO > dailyPeakHO) 
    {
    dailyPeakHO = hO;
    peakHHrO = t.hr;
    peakHMinO = t.min;
    showH(F(" New Outside H Hi "), hO);
    }
  //
  }
//
// ==================================================
//
// Ring the bell very short
//
// Bing activates buzzer, Bong uses speaker
//
void blip()
{
if (bingBong)
  {
  digitalWrite(Buzzer, true);
  delay(20);
  digitalWrite(Buzzer, false);
  }
else
  {
  tone(Speaker, 2500, 50);
  }
//
}
// ==================================================
//
// Ring the bell rings times with .1 sec between beeps
//
void chime(int rings)
{
if (rings > 12) rings = rings - 12; //Fudge for midnight rollover
//
for (int i = 0; i < rings; i++)
  {
  if (!digitalRead(AckBtn)) break;
  //
  if (bingBong)
    {
    digitalWrite(Buzzer, true);
    delay(100);
    digitalWrite(Buzzer, false);
    if (!digitalRead(AckBtn)) break;
    //
    delay(100);
    //
    }
  else
    {
    tone(Speaker, 2000, 200); // Alternate output
    if (!digitalRead(AckBtn)) break;
    //
    delay(200);
    }
  //
  }
//
}
// ==================================================
//
// Ring the bell rings times with 1 sec between beeps
//
void sloChime(int rings)
{
aborted = false;
//
if (rings > 12) rings = rings - 12; //Fudge for midnight rollover
//
for (int i = 0; i < rings; i++)
  {
  if (!digitalRead(AckBtn))
    {
    aborted = true;
    break;
    }
  //
  if (bingBong)
    {
    //
    // Don't abort in middle of pulse, sound stays on forever
    //
    digitalWrite(Buzzer, true);
    delay(200);
    digitalWrite(Buzzer, false);
    }
  else
    {
    tone(Speaker, 1750, 250); // Alternate output
    delay(250);
    tone(Speaker, 2250, 250); // Alternate output
    }
//
  if (!digitalRead(AckBtn))
    {
    aborted = true;
    break;
    }
  //
  delay(500);
  }
//
}
// ==================================================
//
void CheckIR()
{
Time t = rtc.time(); // Device data type - read RTC
//
// This is the master remote control switch. 
// See discussion on button structure near front
//
// Serial.println(F("CheckIR"));
if (irrecv.decode(&results))
  {
  // Display what we got
  //
  valx = abs(results.value); // no negatives
  IRval = String( abs(valx) ); // no negatives
  IRval.trim(); //Strange Syntax
  LastIRCmd.trim();
  //
  // Catch value
  //
// Serial.println("Raw: " + IRval);
  if ( (valx > 1) && (LastIRCmd != IRval))
    {
    if (IRval != "")
      {
      LastIRCmd = IRval;
      LastIRCmd.trim();
      }
    //
    }
  //
  // Live command when received
  //
  valx = abs(valx);
// if (valx >1)
// {
// Serial.print(F("RXD: = "));
// Serial.println(valx);
// }
  //
  // Ok, No silly negatives, Each button sends a code, both remotes send
  // the same code for the same physical button
  //
  // =============================
  // =============================
  // Main control switch on remote command
  // =============================
  // =============================
  //   
  if (valx >= 1) // Triple filter out negs
      {
      //
      // At this point all 21 buttons have an
      // assigned (if not yet fully implemented) function
      //        
      // ======================
      // Chime Alarm AM/PM
      // Hours Device 24 hr
      // ----------------------
      // Temp Full F/C
      // Humidity Date  
      // ----------------------
      // Daily Daily Set
      // Temp Humid Clock
      // ----------------------
      // Show Toggle Set
      // Alarm Alarm Alarm
      // ----------------------
      // ======================
      //
      switch (valx) //Needs integer for switch
        {
        //
        // Button codes in table up front - all tested & work
        //
        case Btn_00:
          Serial.println(F("btn 00"));
          chime(1);
          //
          // Ok, set chime start
          //
          waitTicker(F("Chime on Hour:"));
          chimeOnHr = waitForIt(stepsPerHr, "", 0, ":00");
          chime(1);
          //
          waitTicker(F("Chime off Hour:"));
          chimeOffHr = waitForIt(stepsPerHr, "", 0, ":00");
          chime(1);
          delay(250);
          //
          tmpStr = "Chime From: " + String( chimeOnHr);
          tmpStr += " To: " + String(chimeOffHr);
          //
          waitTicker(tmpStr);
          chime(1);
          //
          // Save 
          //
          // Retain state
          //
          logProm(promChimeOnHr, chimeOnHr);
          logProm(promChimeOffHr, chimeOffHr);
          //
          chime(1); // Ack
          //
          //
        break;
        // =================
        case Btn_01:
          Serial.println(F("btn 01"));
          chime(1);
          K2State = !K2State; // Toggle state
          K2State ? MatrixText = "Power ON" : MatrixText = "Power Off";
          //
          onbyAlarm = false; // Manual control, cancel auto flag
          //
          // Save for power blip
          //
          digitalWrite(K2, K2State); // Tell hardware
          lmd.ticker(MatrixText, scrollRateMs);
          //           
        break;
        // =================
        case Btn_02:
          Serial.println(F("btn 02"));
          chime(1);
          //
          // Toggle 12/24 hour
          //
          clockMode12 = !clockMode12;
          clockMode12 ? MatrixText = "AM/PM" : MatrixText = "24 Hour";
          //
          lmd.ticker(MatrixText, scrollRateMs);
          logProm(promClockMode12, clockMode12);
          //
        break;
        // =================
        // 2nd Row
        //
        case Btn_10:
          Serial.println(F("btn 10"));
          chime(1);
          //
          // Display Temperature
          //
          // Check FC flag to show in C or F
          //
          tempFC ? MatrixText = String(f, 1) + "F/" : 
                   MatrixText = String(c, 1) + "C/";
          //
          lmd.ticker(MatrixText + String(h, 0) + "% RH", scrollRateMs);
          //
        break;
        // =================
        case Btn_11:
          Serial.println(F("btn 11"));
          chime(1);
          //
          // Display date - I know there's a smarter way,
          // but my C++ skills aren't that sharp about arrays
          //
          tmpStr = "";
          switch (t.day)
          {
            case 1:
            tmpStr = "Sun";
            break;
            // ==========
            case 2:
            tmpStr = "Mon";
            break;
            // ==========
            case 3:
            tmpStr = "Tues";
            break;
            // ==========
            case 4:
            tmpStr = "Wednes";
            break;
            // ==========
            case 5:
            tmpStr = "Thurs";
            break;
            // ==========
            case 6:
            tmpStr = "Fri";
            break;
            // ==========
            case 7:
            tmpStr = "Satur";
            break;
            // ==========
          }
          //
          lmd.ticker(tmpStr + "day, " + 
                    String(months[t.mon -1]) + " " + 
                    String(t.date) + ", " + 
                    String(t.yr), scrollRateMs);
          //
        break;
        // =================
        case Btn_12:
          Serial.println(F("btn 12"));
          chime(1);
          //
          // Toggle F/C
          //
          tempFC = !tempFC; //Flip flag
          tempFC ? lmd.ticker(String(f, 1) + "F", scrollRateMs) : lmd.ticker(String(c, 1) + "C", scrollRateMs);
          //
          logProm(promTempFC, tempFC);
          //
        break;
        // =================
        //
        // 3rd Row
        //
        case Btn_20:
          Serial.println(F("btn 20"));
          chime(1);
          //
          // Display Temp Hi/lo
          //
          MatrixText = String(f, 1) + "F - Hi " + String(dailyPeakF, 1) + "F-" + String(peakFHr) + ":";
          if (peakFMin < 10) MatrixText += "0";
          MatrixText += String(peakFMin);
// waitTicker(MatrixText);
          //
          MatrixText += " Lo " + String(dailyLowF, 1) + "F-" + String(lowFHr) + ":";
          if (lowFMin < 10) MatrixText += "0";
          MatrixText += String(lowFMin);
          lmd.ticker(MatrixText, scrollRateMs);
          //
        break;
        // =================
        case Btn_21:
          Serial.println(F("btn 21"));
          chime(1);
          //
          // Display humidity Hi/lo
          //
          MatrixText = String(h, 0) + "% - Hi RH " + String(dailyPeakH) + "%-" + String(peakHHr) + ":";
          if (peakHMin < 10) MatrixText += "0";
          MatrixText += String(peakHMin);
          //
          MatrixText += " Lo " + String(dailyLowH) + "%-" + String(lowHHr) + ":";
          if (lowHMin < 10) MatrixText += "0";
          MatrixText += String(lowHMin);
          lmd.ticker(MatrixText, scrollRateMs);
          //
        break;
        // =================
        case Btn_22:
          Serial.println(F("btn 22"));
          chime(1);
          //
          // Need to have a check to prevent going
          // thru this needlessly.
          // Allow bail out after time set
          // don't force date setting
          //
          waitTicker(F("Are You Sure?"));
          tmp = waitForYN();
          delay(250);
          chime(1);
          if (tmp == 1)
            {
            //
            // Ok, set Clock Hour
            //
            chime(1);
            waitTicker(F("Dial Hour:"));
            clockHr = waitForIt(stepsPerHr, "", 0, ":xx" );
            chime(1);
            //
            // Now get minute
            //
            waitTicker(F("Dial Minute:"));
            // M is wider than normal, need to lose the :
            clockMin = waitForIt(stepsPerMin, String(clockHr) + ":", 0, "");
            chime(1);
            //
            // Do they wanna bail?
            waitTicker(F("Set Date?"));
            if (waitForYN() == 1)
              {
              chime(1);
              //
              // Now get month
              //
              delay(250);
              waitTicker(F("Dial Month:"));
              //
              // Hmmm
              //
              clockMon = waitForMon() + 1; // Result is zero offset, calendar starts with 1
              chime(1);
              delay(250);
              //
              // Now get date
              //
              waitTicker(F("Dial Date:"));
              clockDt = waitForDate(); //1-31
              chime(1);
              //
              // Year = error trap
              //
              clockYr = 2021;
              while (clockYr < 2022)
                {
                waitTicker(F("Dial Year:"));
                clockYr = 2000 + waitForYear();
                }
              //
              chime(1);
              //
              // Now get day of week
              //
              waitTicker(F("Dial Day of the Week:"));
              clockDoW = waitForDoW() + 1; // Zero offset, but need 1-7
              }
            else
              {
              //
              // Use current date
              //
              clockYr = t.yr;
              clockMon = t.mon;
              clockDt = t.date;
              clockDoW = t.day;
              }
            //
            // We need to wait for operator to click
            // to sync setting. Need to write data 
            // to RTC after go
            //
            chime(1);
            delay(250);
            waitTicker(F("Press Ack to sync ..."));
            chime(1); // Ack
            lmd.stopTicker();
            lmd.clear();
            // Show set time and hold
            tmpStr = "";
            if (clockHr < 10) tmpStr += " ";
            tmpStr += String(clockHr) + ":";
            if (clockMin < 10) tmpStr += "0";
            tmpStr += String(clockMin);
            lmd.printText(0, tmpStr);            
            lmd.display();
            //
            while (digitalRead(AckBtn))
              {
              delay(100);
              // Wait for press 
              }
            //
            blip();
            //
            // Write time to RTC
            //
            setRTC(clockYr, clockMon, clockDt, clockHr, clockMin, clockDoW);
            //
            chime(2); // Ack
            //
            Serial.print(F("Time Set: ") );
            Serial.println( String( dows[clockDoW -1]) + ", "
                          + String(months[clockMon -1]) + " "
                          + String(clockDt ) + ", "
                          + String(clockYr ) + " "
                          + String(clockHr ) + ":" 
                          + String(clockMin)
                          );
                         //
            append(F("Time Set"));
            //
            }
          //
          //
        break;
        // =================
        // 4th Row
        //
        case Btn_30:
          Serial.println(F("btn 30"));
          chime(1);
          //
          // Alarm show
          //
          MatrixText = "Alarm Time: " + String(alarmHr) + ":";
          if (alarmMin < 10) MatrixText += "0";
          MatrixText += String(alarmMin);
          //
          AlarmSet ? MatrixText += " ON" : MatrixText += " OFF"; 
          //
          lmd.ticker(MatrixText, scrollRateMs);
          //
        break;
        // =================
        case Btn_31:
          Serial.println(F("btn 31"));
          chime(1);
          //
          // Alarm on/off
          //
          AlarmSet = !AlarmSet;
          if (AlarmSet)
            {
            MatrixText = "Alarm Set On: " + String(alarmHr) + ":";
            if (alarmMin < 10) MatrixText += "0";
            MatrixText += String(alarmMin);
            }
          else
            {
            MatrixText = "Alarm Off";
            chime(1); // Twice is off - like car alarm
            }
          //
          onbyAlarm = false;
          lmd.ticker(MatrixText, scrollRateMs);
          logProm(promAlarmSet, AlarmSet);
          //
        break;
        // =================
        case Btn_32:
          Serial.println(F("btn 32"));
          chime(1);
          //
          // Ok, set Alarm Hour
          //
          waitTicker(F("Dial Hour:"));
          alarmHr = waitForIt(stepsPerHr, "", 0, ":xx");
          chime(1);
          //
          // Now get minute
          //
          waitTicker(F("Dial Min:"));
          alarmMin = waitForIt(stepsPerMin, String(alarmHr) + ":", 0, "");
          chime(1);
          delay(250);
          //
          tmpStr = "Alarm On: " + String(alarmHr) + ":";
          if (alarmMin < 10) tmpStr += "0";
          //
          tmpStr += String(alarmMin);
          waitTicker(tmpStr);
          chime(1);
          //
          // Save and turn alarm on automatically
          //
          AlarmSet = true;
          onbyAlarm = false; // Clear old state
          //
          // Retain state
          //
          logProm(promAlarmHr, alarmHr);
          logProm(promAlarmMin, alarmMin);
          logProm(promAlarmSet, AlarmSet);
          //
          chime(2); // Ack
          //
        break;
        // =================
        // 5th Row
        // Originally this was for FM radio control
        // Since I had no luck getting it to run
        // OUT - these buttons can be used for the
        // MP3 or other control functions
        //
        case Btn_40:
          Serial.println(F("btn 40"));
// chime(1);
          //
          // This actually works but isn't needed
          /*
          tmp = radio.getFrequency();
          --tmp; // Dump once
          tweakFreq(tmp);
          */
          // Mkay, lets toggle the annunciator mode
          //
          bingBong = !bingBong;
          logProm(promBingBong, bingBong);
          chime(2); // Make new sound
          //
        break;
        // =================
        case Btn_41:
          Serial.println(F("btn 41"));
          chime(1);
          //
          /*
          tmp = radio.getFrequency();
          ++tmp; // Bump thrice
          ++tmp;
          ++tmp;
          tweakFreq(tmp);
          */
          //            
        break;
        // =================
        case Btn_42:
          Serial.println(F("btn 42"));
          chime(1);
          //
          // Volume Up doesn't work on this
          // particular module. It's a preamp
          // so it's always at full blast or muted
          //
          // Old test function            
          // Test button for MP3 player
          //
// Serial.println("Play 1");
// playSong(1);
          //
          // STOPWATCH
          //
          waitTicker(F("Press Ack to Start/Stop: "));
          lmd.printText(0, "Go:", true); //0 index
          lmd.display();
          //
          while (digitalRead(AckBtn)) // Wait on Press
            {
            delay(100);
            }
          //
          while (!digitalRead(AckBtn)) // Wait on release
            {
            delay(100);
            }
          //
          // Save current moment
          //
          startTime = millis(); // Get start
          chime(1); // Ack release
          //
          lmd.clear();
          //
          while (digitalRead(AckBtn))
            {
            lmd.printText(0, String((millis() - startTime)) + "mS", true); //0 index
            lmd.display();
            }
          //
          tmpStr = String(millis() - startTime) + "mS";
          //          
          while (!digitalRead(AckBtn)) // Wait on release
            {
            delay(100);
            }
          //
          chime(2); //Announce stop
          //
          waitTicker(tmpStr); // Display as scroll
          //
          lmd.printText(0, tmpStr, true); //0 index
          lmd.display();
          //
          while (digitalRead(AckBtn)) // Wait on Press
            {
            delay(100);
            }
          //
          append("ET: " + tmpStr); // Log event
          //
          // a-a-a-nd we're DONE!
          //
        break;
        // =================
        // 6th Row
        //
        case Btn_50:
          Serial.println(F("btn 50"));
          chime(1);
          //
          // Display outside Temp Hi/lo
          //
          MatrixText = String(fO, 1) + "F ";
          MatrixText += "Out Hi " + String(dailyPeakFO, 1) + "F-" + String(peakFHrO) + ":";
          if (peakFMinO < 10) MatrixText += "0";
          MatrixText += String(peakFMinO);
          //
          MatrixText += " Out Lo " + String(dailyLowFO, 1) + "F-" + String(lowFHrO) + ":";
          if (lowFMinO < 10) MatrixText += "0";
          MatrixText += String(lowFMinO);
          //
          lmd.ticker(MatrixText, scrollRateMs);
          //
          break;
        // =================
        case Btn_51:
          Serial.println(F("btn 51"));
          chime(1);
          //
          // Display humidity Hi/lo
          //
          MatrixText = String(hO, 1) + "% ";
          MatrixText += "Out Hi RH " + String(dailyPeakHO) + "%-" + String(peakHHrO) + ":";
          if (peakHMinO < 10) MatrixText += "0";
          MatrixText += String(peakHMin);
          //
          MatrixText += " Out Lo " + String(dailyLowHO) + "%-" + String(lowHHrO) + ":";
          if (lowHMinO < 10) MatrixText += "0";
          MatrixText += String(lowHMinO);
          lmd.ticker(MatrixText, scrollRateMs);
          //
          //
        break;
        // =================
        case Btn_52:
          Serial.println(F("btn 52"));
          chime(1);
          //
          // Walk RGB LED thru its paces
          //
          /*
          RGBstate = RGBstate << 1; // Shift left once
          if (RGBstate > 0b00001000) RGBstate = 0b00000001;
          //
          setRGB();
          //
          logProm(promRGBled, RGBstate);
          */
          //
       break;
        // =================
        // 7th and last Row
        //
        case Btn_60:
          Serial.println(F("btn 60"));
          chime(1);
          //
          // This will allow setting of
          // the station presets selected
          // above at btn_50 and btn_51
          //
          tmp = waitForIt( 1024/200, "F:", 881, "");
          tweakFreq(tmp);
          //
        break;
        // =================
        case Btn_61:
          Serial.println(F("btn 61"));
          chime(1);
          //
          // Toggle matrix
          // Dim/restore display
          //
          if (MatrixBright != 0)
            {
            MatrixBright = 0;
            RGBstate = 0b00001000; // Turn off aux light
            dimMode = false; // remote commands
            //
            }
          else
            {
            MatrixBright = EEPROM.read(promMatrixBright);
// RGBstate = EEPROM.read(promRGBled ); // Last RGB state
            dimMode = true; // knob commands
            }
          //
          lmd.setIntensity(MatrixBright); // 0 = low, 15 = high
          setRGB();
          //
          // Since we didn't update EEPROM the preset
          // brightness will restore on next reset
          //
        break;
        // =================
        case Btn_62:
          Serial.println(F("btn 62"));
          chime(1);
          //
          // Toggle radio Mute & display frequency
          //
          radio.setMute(!radio.getMute() );
          //
          showFM();
          //
        break;
        // =================
        //
        // SWITCH VAL ENDS
        //
        }
      //
    //
    } // If Val ends
  //
  } // Decode ends
//
// Resume IR control - not really sure what this does.
//
irrecv.resume();
irrecv.enableIRIn();
//
}
// ==================================================
//
// Keep marquee spinning - no DELAY's allowed
//
void dillyDally(int mills2wait)
{
//
int rightNow = millis();
//
while (millis() < rightNow + mills2wait)
  {
  if (!lmd.updateTicker()) 
    {
    lmd.stopTicker(); //Stop at end    
    lmd.clear();
    }
    //
  }
//
}
// ==================================================
//
// Spin hard letting ticker run - data from globals
//
void waitTicker(String Msg)
{
lmd.ticker(Msg, scrollRateMs);
//
  while (lmd.updateTicker())
  {
  if (!digitalRead(AckBtn)) 
    {
    aborted = true; //Pass up food chain
    break;
    // =========
    }
  //
  }
//
}
// ==================================================
//
// Waits for input via pot, ended with ackbtn
//
// pot input 0-1023 is scaled by steps
// input is prompted with cue
// 0/1 origin is set with bias
//
// Scaled value returned
//
int waitForIt(float steps, String cue, int bias, String Suffix)
{
//
String tmpCue = cue;
int myTmp; //Return var
//
lmd.stopTicker();
lmd.clear();
//
while (digitalRead(AckBtn))
  {
  tmpCue = ""; // Unpad for next loop
  myTmp = (analogRead(Wiper) / steps);
  if (cue == "")
    {
    // 1st col - pad with blank
    if ((myTmp + bias) < 10) tmpCue = " ";
    lmd.printText(0, tmpCue + String(myTmp + bias) + Suffix, true); //0 index
    }
  else
    {
    // 2nd col - pad with zero
    if (myTmp < 10) tmpCue = "0";
    lmd.printText(0, cue + tmpCue + String(myTmp + bias) + Suffix, true); //0 index
    }
  //
  lmd.display();
  delay(100); //Can't dillydally static display
  lmd.clear();
  }
//
while (!digitalRead(AckBtn)) // Wait on release
  {
  delay(100);
  }
//
chime(1);
return myTmp + bias;
//
}
// ==================================================
//
// Waits for input via pot, ended with ackbtn
//
// pot input 0-1023 is scaled by steps
// input is prompted with cue
// 0/1 origin is set with bias
//
// Scaled value returned
//
int waitForYN()
{
//
int myTmp; //Return var
//
lmd.stopTicker();
lmd.clear();
//
while (digitalRead(AckBtn))
  {
  if (analogRead(Wiper) < stepsPerYN) // Only two states
    {
    lmd.printText(0, "No ", true); // pad for length
    myTmp = 0;
    }
  else
    {
    lmd.printText(0, "Yes", true);
    myTmp = 1;
    }
  //
  lmd.display();
  delay(100); //Can't dillydally static display
  lmd.clear();
  }
//
while (!digitalRead(AckBtn)) // Wait on release
  {
  delay(100);
  }
//
chime(1);
return myTmp;
//
}
// ==================================================
//
// Waits for input via pot, ended with ackbtn
//
// pot input 0-1023 is scaled by steps
// input is prompted with cue
// 0/1 origin is set with bias
//
// Scaled value returned
//
int waitForDoW()
{
//
int myTmp; //Return var
//
lmd.stopTicker();
lmd.clear();
//
while (digitalRead(AckBtn))
  {
  myTmp = (analogRead(Wiper) / stepsPerDoW);
  lmd.printText(0, dows[myTmp], true); //0 index - no padding, all strings same len
  //
  lmd.display();
  delay(100); //Can't dillydally static display
  lmd.clear();
  }
//
while (!digitalRead(AckBtn)) // Wait on release
  {
  delay(100);
  }
//
chime(1);
return myTmp;
//
}
// ==================================================
//
// Waits for input via pot, ended with ackbtn
//
// pot input 0-1023 is scaled by steps
// input is prompted with cue
// 0/1 origin is set with bias
//
// Scaled value returned
//
int waitForMon()
{
//
int myTmp; //Return var
//
lmd.stopTicker();
lmd.clear();
//
while (digitalRead(AckBtn))
  {
  myTmp = (analogRead(Wiper) / stepsPerMon);
  lmd.printText(0, months[myTmp], true); //0 index - no padding, all strings same len
  //
  lmd.display();
  delay(100); //Can't dillydally static display
  lmd.clear();
  }
//
while (!digitalRead(AckBtn)) // Wait on release
  {
  delay(100);
  }
//
chime(1);
return myTmp;
//
}
// ==================================================
//
// Waits for input via pot, ended with ackbtn
//
// pot input 0-1023 is scaled by steps
// input is prompted with cue
// 0/1 origin is set with bias
//
// Scaled value returned
//
int waitForDate()
{
//
int myTmp; //Return var
//
lmd.stopTicker();
lmd.clear();
//
while (digitalRead(AckBtn))
  {
  myTmp = (analogRead(Wiper) / stepsPerDt);
  lmd.printText(0, String(clockMon) + "/" + String(myTmp +1), true);
  //
  lmd.display();
  delay(100); //Can't dillydally static display
  lmd.clear();
  }
//
while (!digitalRead(AckBtn)) // Wait on release
  {
  delay(100);
  }
//
chime(1);
return (myTmp +1);
//
}
// ==================================================
//
// Waits for input via pot, ended with ackbtn
//
// pot input 0-1023 is scaled by steps
// input is prompted with cue
// 0/1 origin is set with bias
//
// Scaled value returned
//
int waitForYear()
{
//
int myTmp; //Return var
//
lmd.stopTicker();
lmd.clear();
//
while (digitalRead(AckBtn))
  {
  myTmp = ( (analogRead(Wiper) / (aiSteps / 78) ) + 22); // Compensate for base year
  lmd.printText(0, "20" + String(myTmp), true);
  //
  lmd.display();
  delay(100); //Can't dillydally static display
  lmd.clear();
  }
//
while (!digitalRead(AckBtn)) // Wait on release
  {
  delay(100);
  }
//
chime(1);
return myTmp;
//
}
// ==================================================
//
void setRTC(int yr, int mo, int dt, int hr, int mn, int dow)
{
rtc.writeProtect(false);
rtc.halt(true); //Shouldn't this be TRUE?
//
// Make a new time object to set the date and time.
// Full spec needs seconds and DoW
//
Time t(yr, mo, dt, hr, mn, 00, dow);
//
// Set the time and date on the chip.
//
rtc.time(t);
//  
rtc.halt(false); //Let clock run
rtc.writeProtect(true); //Only protect AFTER letting it run
//
}
// ==================================================
//
void formTime()
{
Time t = rtc.time(); // Device data type - read RTC
String outStr;
int wrk = t.hr; // Time from globals
//
if (wrk < 1) wrk = 12; // Show midnight as 12:xx
if ((wrk > 12) && (clockMode12)) wrk = wrk - 12; //Civillian time
//
clockMode12 ? outStr = " " : outStr = "0"; // Pad leader
//
if (wrk >= 10) outStr = ""; // No pad needed
//
outStr += String(wrk) + colon; // Tick tock symbol
//
if (t.min < 10) outStr += "0"; // Pad leading zero on minutes
outStr += String(t.min);
//
// Send time to 8X8x4 LED matrix display if not busy
//
if (clockMode12) ((t.hr < 12) ? outStr += "a" : outStr += "p");
//
// Serial.println(outStr);
if (!lmd.updateTicker())
  {
  lmd.stopTicker(); // Kill scrolling msg (pro forma)
  lmd.clear(); // Blank
  lmd.printText(0, outStr, true); // 0 index static text
  lmd.display(); // Display
  }
//
}
// ==================================================
//
// Clean up 
//
void readAfile(String fileName)
{
//
// Crack open file and return file handle
//
int bytes = 0; // Bytes read
//
// filename is being returned as a number?
//
aFile = SD.open(String(fileName)); //Returns handle or false on fail
if (aFile) // Success!
  {
  Serial.print(F("Reading: ") );
  Serial.println(fileName);
  //
  // read from the file until there's nothing else in it:
  //
  while (aFile.available()) // not EOF
    {
    // Byte level copy?
    //
    Serial.write(aFile.read()); // Copy byte to comm port for visibility
    bytes++; // Goose counter
    }
  //
  // close the file
  //
  aFile.close();
  //
  // Summary to serial port
  //
  Serial.println(String(bytes) + " bytes read");
  //
  }
//
}
// ==================================================
//
// Append to log file
//
void append(String lineOtext)
{
// Pass a line of text. Filename is given
//
Time t = rtc.time(); // Device data type - read RTC
//
File aFile;
Serial.print(F("Opening: ") );
Serial.println(logName);
//
aFile = SD.open(logName, FILE_WRITE); //Returns handle or false on fail
if (aFile) // Success!
  {
  //
  String Hr = String(t.hr);
  if (t.hr < 10) Hr = "0" + Hr;
  String Mn = String(t.min);
  if (t.min < 10) Mn = "0" + Mn;
  aFile.println(" D&T: " + String(t.mon) + "/" + String(t.date)
                         + " @ " + Hr + ":" + Mn );
  aFile.println("Temp: " + String(f, 1) + "F");
  aFile.println("RH %: " + String(h, 0)); // Data is integer
  //
  // Only append if not blank
  //
  if (lineOtext != "") 
  {
    // Echo to console and file
    aFile.println("[" + lineOtext + "]");
    Serial.print("[" + lineOtext + "]");
  }
  //
  aFile.close();
  //
  Serial.println(F("Log updated"));
  }
else
  {
  Serial.print(F("Pbbbt! Failed file open of ") );
  Serial.println(logName);
  }
//
}
// ==================================================
//
void logIt()
{
// Pass a line of text. Filename is given
//
Time t = rtc.time(); // Device data type - read RTC
//
Serial.print(F("Opening: ") );
Serial.println(logName);
//
aFile = SD.open(logName, FILE_WRITE); //Returns handle or false on fail
if (aFile) // Success!
  {
  //
  echoBoth("Daily Indoor Data: " + String(t.mon) + "/" + String(t.date) );
  echoBoth("High Temp: " + String(dailyPeakF, 1) + "F at " + String(peakFHr ) + ":" + String(peakFMin ) );
  echoBoth(" Low Temp: " + String(dailyLowF, 1) + "F at " + String(lowFHr ) + ":" + String(lowFMin ) );
  echoBoth("High RH %: " + String(dailyPeakH ) + "% at " + String(peakHHr ) + ":" + String(peakHMin ) );
  echoBoth(" Low RH %: " + String(dailyLowH ) + "% at " + String(lowHHr ) + ":" + String(lowHMin ) );
  echoBoth(F("Daily Outdoor Data:") );
  echoBoth("High Temp: " + String(dailyPeakFO, 1) + "F at " + String(peakFHrO) + ":" + String(peakFMinO) );
  echoBoth(" Low Temp: " + String(dailyLowFO, 1) + "F at " + String(lowFHrO ) + ":" + String(lowFMinO ) );
  echoBoth("High RH %: " + String(dailyPeakHO ) + "% at " + String(peakHHrO) + ":" + String(peakHMinO) );
  echoBoth(" Low RH %: " + String(dailyLowHO ) + "% at " + String(lowHHrO ) + ":" + String(lowHMinO ) );
  //
  aFile.close();
  //
  Serial.println(F("Log updated"));
  }
else
  {
  Serial.print(F("Pbbbt! Failed file open of ") );
  Serial.println(logName);
  }
//
// Reset vars for new day
//
// Indoor
//
dailyPeakF = -100.0; // Impossible extremes trigger log entry at start
dailyLowF = 200.0;
dailyPeakH = 0;
dailyLowH = 100;
//
// Outdoor
//
dailyPeakFO = -100.0; // Impossible extremes trigger log entry at start
dailyLowFO = 200.0;
dailyPeakHO = 0;
dailyLowHO = 100;
//
}
// ==================================================
//
// echoBoth - Send global tmpoStr to aFile and Serial.
//
void echoBoth(String tmpTxt)
{
 aFile.println(tmpTxt);
Serial.println(tmpTxt);
}
// ==================================================
//
// Send random command to player
//
void cmdMP3(int8_t command[], int len)
{
//
// Rewrite to compute length and prefix/suffix automatically
//
 Serial.print(F("7E "));
Serial1.write(0x7E); // Prefix
//
 Serial.print(String(len +1, HEX));
 Serial.print(" "); // Pad with blank for readability
Serial1.write(len +1); // Bytes to follow including suffix
//
for(int i = 0; i < len; i++)
  { 
  //
  Serial1.write(lowByte( command[i] ) ); // Send byte
   Serial.print(String( lowByte( command[i] ), HEX) + " "); // mask LSH to prevent minus extend
  }
//
 Serial.println(F("EF"));
Serial1.write(0xEF); // Suffix
delay(1000); // Wait a second
//  
}
// ==================================================
//
void playSong(int song)
{
//
// Rewrite to compute length and prefix/suffix automatically
//
Serial1.write(0x7E); // Prefix
Serial1.write(0x04); // Bytes to follow including suffix
Serial1.write(0x31); // Set Volume command & play #
Serial1.write(0x1E); // Volume to full
//
Serial1.write(lowByte(song)); // Send song #
//
Serial1.write(0xEF); // Suffix
delay(1000); // Wait a second
//  
}
// ==================================================
//
void tweakFreq(int Freq)
{
//
// Sanity check
//
if (Freq < 889) Freq = 889;
if (Freq > 1079) Freq = 1079;
//
Serial.print(F("Set FM: ") );
Serial.println(String(Freq));
//
radio.setFrequency(Freq); // Tell radio
LogLong(promFrequency, Freq); // Save in EPROM
//
showFM(); // Display freq
//
}
// ==================================================
//
// Display station from radio
//
void showFM()
{
tmpF = radio.getFrequency();
waitTicker("FM " + String(++tmpF / 10, 1) );  
}
// ==================================================
//
void LogLong(int Addr, int Valu)
{
//
EEPROM.update(Addr , lowByte( Valu));
EEPROM.update(Addr + 1, highByte(Valu));
}
// ==================================================
//
// Updates given EEPROM *BYTE* address with value, ints > 255 need TWO!
//
void logProm(int Addr, int Valu)
{
EEPROM.update(Addr, Valu);
}
// ==================================================
//
void setRGB()
{
digitalWrite(ledR, !(RGBstate & 0b001) );
digitalWrite(ledG, !(RGBstate & 0b010) );
digitalWrite(ledB, !(RGBstate & 0b100) );  
}
// ==================================================
//
void showF(String prompt, float datum)
{
Time t = rtc.time();
Serial.print(String(t.hr) + ":" + String(t.min));
Serial.print(prompt);
Serial.println(String(datum, 1) + "F");
}
// ==================================================
//
void showH(String prompt, float datum)
{
Time t = rtc.time();
Serial.print(String(t.hr) + ":" + String(t.min));
Serial.print(prompt);
//Serial.println(String(datum, 0) + "%");
Serial.println(String(datum, 0) + "%");
}
// ==================================================
//
/*
void readBME()
{
//
auto temperature = String(sensor.getTemperature()) + " °C";
auto pressure = String(sensor.getPressure() / 100.0) + " hPa";
auto humidity = String(sensor.getHumidity()) + " %";
//
String measurements = temperature + ", " + pressure + ", " + humidity;
Serial.println(measurements);
//
}
*/
// ==================================================
// ==================================================
// FIN
// ==================================================
// ==================================================

```

---

<div class="post-metadata">

**Author:** ![PaulRB](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/paulrb/32/216330_2.png) [@PaulRB](https://forum.arduino.cc/u/PaulRB)\
**Post date:** [April 14, 2022, 5:16pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/16 "2022-04-14T17:16:18Z")

</div>

> [@madmark2150](#):
>
> . I have the complete project on my project page as i already said.

Yeah, but you didn't post a link to it until post #11. Thankyou for posting it.

> [@madmark2150](#):
>
> The BME280 is the small (tiny really, about 1 cm sq) module with one mounting hole in the corner...  
> The BME280 has SDA/SDC pins, these are wired in parallel with another, functioning, device, the SD card.

I use those bme280 modules. They are i²c only. Your SD card is SPI. You can't wire them in parallel. Different buses!

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 5:19pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/17 "2022-04-14T17:19:12Z")

</div>

Honestly, I thought everyone could just click on my icon and my page would appear.

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 5:28pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/18 "2022-04-14T17:28:05Z")

</div>

Isn't SDA/SCL I2C? I'm confused.

OOPS - Just verified wiring, the other SDA/SCL device is NOT the SD card, but an FM Radio module - that works.

Ok, so then the SPI MOSI/MISO and I2C are both logically and electrically independent.

Hmmm. The project DIES since the heartbeat LED stops. The MOSI/MISO displays **ONE** message and then everything stops. I had _assumed_ (me bad) that it was conflicting with the MOSI/MISO since the display stopped, but THEN I noticed that loop() had stopped so NOTHING was running.

(sigh)

It's NEVER easy. I plugged the BME280 in, ran the test code, it ran PERFECTLY and now copying over to the big program and it gives me _agita_.

---

<div class="post-metadata">

**Author:** ![PaulRB](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/paulrb/32/216330_2.png) [@PaulRB](https://forum.arduino.cc/u/PaulRB)\
**Post date:** [April 14, 2022, 6:53pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/19 "2022-04-14T18:53:34Z")

</div>

> [@madmark2150](#):
>
> Isn't SDA/SCL I2C?

Yes.

> [@madmark2150](#):
>
> the SPI MOSI/MISO and I2C are both logically and electrically independent.

Yes.

Some devices have confusing pin names, like DATA, CLOCK or similar, which could be i²c or SPI. Often they can be either (but not both at the same time). By setting jumpers on the sensor board they can be configured for either i²c or SPI bus, in which case the SDA pin is also the MOSI pin and the SCL pin is also the CLK pin, depending which bus has been selected. But they are not dynamically interchangeable. In a given circuit they will be either i²c or SPI but never both.

---

<div class="post-metadata">

**Author:** ![madmark2150](https://avatars.discourse-cdn.com/v4/letter/m/b487fb/32.png) [@madmark2150](https://forum.arduino.cc/u/madmark2150)\
**Post date:** [April 14, 2022, 7:27pm UTC](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840/20 "2022-04-14T19:27:14Z")

</div>

Good. Now, how do I get it working? The stand alone sketch works. Combined into the master sketch, not so much.

[Next page](https://forum.arduino.cc/t/bme280-interactions-with-miso-mosi-led-matrix/980840.md?page=2)
