Hi all,
I have a simple Arduino code for an ESP32 chip that uses some C++ code, but the delay in the loop()
works only if I define Serial.begin(9600)
in setup()
(but doesn't work with a different baud rate like 115200), I read it here Delay is not working?! - #12 by cmiyc
Well, you might say, just keep the Serial.begin(9600)
, but I can't because I need a different baud-rate.
This is my .ino file:
#include "MyClass.h"
// Define a message
byte msg[4] = {0xAA, 0xBB, 0xCC, 0xDD};
MyClass* myObject = new MyClass();
void setup() {
myObject->init();
Serial.begin(9600); // Needed by Arduino for delay() to work
}
void loop() {
myObject->sendSPI(msg, sizeof(msg));
delay(1000);
}
This is MyClass.h
#ifndef MY_CLASS
#define MY_CLASS
#include <Arduino.h>
#include <SPI.h>
class MyClass {
public:
MyClass();
void init();
void sendSPI(uint8_t* msg, uint8_t msg_len);
};
This is MyClass.cpp
#include "MyClass.h"
#include <Arduino.h>
// SPI pins
#define SPI_SCK 18 // SPI Clock (Master Output)
#define SPI_MOSI 23 // Master Output, Slave Input
#define SPI_MISO 19 // Master Input, Slave Output
static const long spiClk = 2000000; // SPI Clock frequency [Hz]
//Constructor
MyClass::MyClass() {}
MyClass::init() {
// Setup functionality pins
pinMode(32, OUTPUT);
pinMode(33, OUTPUT);
//Setup SPI lines and interface
pinMode(5, OUTPUT);
pinMode(SPI_SCK, OUTPUT);
pinMode(SPI_MOSI, OUTPUT);
pinMode(SPI_MISO, INPUT);
SPI.begin (SPI_SCK, SPI_MISO, SPI_MOSI);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE3);
SPI.setClockDivider(SPI_CLOCK_DIV8); // divide the clock by 8=2 MHz @ESP32
}
void MyClass::sendSPI(uint8_t* msg, uint8_t msg_len) {
digitalWrite(33, LOW); // Toggle some pin
delay(25);
digitalWrite(5, LOW); // Enable SPI Slave Select
for (int i = 0; i < msg_len; i++) {
SPI.transfer((byte) msg[i]); // Write data to MOSI
}
digitalWrite(5, HIGH); // Disable Slave Select
SPI.endTransaction();
delay(30); // Wait
digitalWrite(32, HIGH); // toggle some other pin
}