I'm trying to use VSPI port of ESP32-WROVER with "Adafruit_SPIFlash.h" library https://github.com/adafruit/Adafruit_SPIFlash
This question is similar to How to use SPI with ESP32 and Arduino , but I'm using "Adafruit_SPIFlash.h" library.
This library seems to be using ESP32-WROVER "internal" SPI port, where WROVER SPI FLASH chip is connected, as a default. I have another SPI FLASH chip connected to VSPI port which I'm trying to use to store some sensor data.
I tried changing CUSTOM_SPI statement, but code doesn't compile
#define CUSTOM_SPI SPI //tried changing SPI to: VSPI, &VSPI, SPI1, SPI2, &SPI2
I asked this from Adafruit forum and got answer: "Create a Adafruit_FlashTransport_SPI object for the secondary SPI interface, then feed that to the Adafruit_SPIFlash object when you create it." Unfortunately I'm so nooby on FW things that this didn't help me and my follow up question is not answered.
For example how would I need to modify sketch below to use VSPI?
// The MIT License (MIT)
// Copyright (c) 2019 Ha Thach for Adafruit Industries
#include "SdFat.h"
#include "Adafruit_SPIFlash.h"
// Uncomment to run example with custom SPI and SS e.g with FRAM breakout
// #define CUSTOM_CS A5
// #define CUSTOM_SPI SPI
#if defined(CUSTOM_CS) && defined(CUSTOM_SPI)
Adafruit_FlashTransport_SPI flashTransport(CUSTOM_CS, CUSTOM_SPI);
#elif defined(ARDUINO_ARCH_ESP32)
// ESP32 use same flash device that store code.
// SPIFlash can use partition table to detect fatfs partition
// Therefore there is no need to specify the SPI and SS
Adafruit_FlashTransport_ESP32 flashTransport;
#elif defined(ARDUINO_ARCH_RP2040)
// RP2040 use same flash device that store code.
// Therefore there is no need to specify the SPI and SS
// Use default (no-args) constructor to be compatible with CircuitPython partition scheme
Adafruit_FlashTransport_RP2040 flashTransport;
// For generic usage: Adafruit_FlashTransport_RP2040(start_address, size)
// If start_address and size are both 0, value that match filesystem setting in
// 'Tools->Flash Size' menu selection will be used
#else
// On-board external flash (QSPI or SPI) macros should already
// defined in your board variant if supported
// - EXTERNAL_FLASH_USE_QSPI
// - EXTERNAL_FLASH_USE_CS/EXTERNAL_FLASH_USE_SPI
#if defined(EXTERNAL_FLASH_USE_QSPI)
Adafruit_FlashTransport_QSPI flashTransport;
#elif defined(EXTERNAL_FLASH_USE_SPI)
Adafruit_FlashTransport_SPI flashTransport(EXTERNAL_FLASH_USE_CS, EXTERNAL_FLASH_USE_SPI);
#else
#error No QSPI/SPI flash are defined on your board variant.h !
#endif
#endif
Adafruit_SPIFlash flash(&flashTransport);
/* If you want to use a specific flash device, for example for a custom built board, first look for it in Adafruit_SPIFlash\src\flash_devices.h
* If it isn't in there you need to create your own definition like the W25Q80DLX_EXAMPLE example below.
* These definitions need to be edited to match information on the data sheet of the flash device that you want to use.
* If you are not sure what the manufacture ID, memory type and capacity values should be, try running the sketch anyway and look at the serial output
* The flash device will report these values to you as a single hexadecimal value (the JDEC ID)
* For example, the first device on the list - the W25Q80DLX - will report its JDEC ID as 0xef4014, which is made of these three values:
* manufacturer_id = 0xef
* memory_type = 0x40
* capacity = 0x14
* With this macro properly defined you can then create an array of device definitions as shown below, this can include any from the list of devices in flash_devices.h, and any you define yourself here
* You need to update the variable on line 71 to reflect the number of items in the array
* You also need to uncomment line 84 and comment out line 81 so this array will be passed to the flash memory driver.
*
* Example of a user defined flash memory device:
#define W25Q80DLX_EXAMPLE \
{ \
.total_size = 1*1024*1024, \
.start_up_time_us = 5000, .manufacturer_id = 0xef, \
.memory_type = 0x40, .capacity = 0x14, .max_clock_speed_mhz = 80, \
.quad_enable_bit_mask = 0x02, .has_sector_protection = false, \
.supports_fast_read = true, .supports_qspi = true, \
.supports_qspi_writes = false, .write_status_register_split = false, \
.single_status_byte = false, .is_fram = false, \
}
*/
/*
* Create an array of data structures and fill it with the settings we defined above.
* We are using two devices, but more can be added if you want.
*/
//static const SPIFlash_Device_t my_flash_devices[] = {
// W25Q80DLX_EXAMPLE,
//};
/*
* Specify the number of different devices that are listed in the array we just created. If you add more devices to the array, update this value to match.
*/
//const int flashDevices = 1;
// the setup function runs once when you press reset or power the board
void setup()
{
Serial.begin(115200);
while ( !Serial ) delay(100); // wait for native usb
Serial.println("Adafruit Serial Flash Info example");
flash.begin();
//Using a flash device not already listed? Start the flash memory by passing it the array of device settings defined above, and the number of elements in the array.
//flash.begin(my_flash_devices, flashDevices);
Serial.print("JEDEC ID: 0x"); Serial.println(flash.getJEDECID(), HEX);
Serial.print("Flash size: "); Serial.print(flash.size() / 1024); Serial.println(" KB");
}
void loop()
{
// nothing to do
}
Related
I´m totally new to coding, this is even my first post here. Im tryng this because nobody sells what I want/need ;-).
I achived already quite a bit, but at this moment I´m getting lost with a lot of things (I read a lot about coding in general and in special with Arduino the last 8 dayas)... but let me explain first what my intention on this project is:
I want to build a "Stomp Box" to mute a Behringer X32 Rack (wireless) Channels/Mutegroups/Buses, just Mute On/Off.. nothing else.
This Box should have 4-6 "stompers" (buttons), each of this buttons should have a different Mute function.
Also the current state of the Channel/Mutegroup/Bus should be indicated by LED´s green if unmuted or red if muted.
Therfore the box needs to evaulate the current state of the designated Channel/Mutegroup/Bus, because it could change also from other remote devices.
And then switch to the opposite state when pressing/stomping on designated button.
I´d like to have code where I can easily change the action of a button, Like:
button1 = /ch/01/mix/on ,i 1
button2 = /config/mute/1 ,i 1
button3 = /dca/1/on ,i 1
so in case I need a differnt Channel/Mutegroup/Bus for another event simply edit and recode my ESP32 Node Kit
So here is my code I already have:
#include "WiFi.h"
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <SPI.h>
#include <OSCMessage.h> //https://github.com/CNMAT/OSC
#define WIFI_NETWORK "xxxxxxxxxx" //SSID of you Wifi
#define WIFI_PASSWORD "xxxxxxxxxxx" //Your Wifi Password
#define WIFI_TIMEOUT_MS 20000 // 20 second WiFi connection timeout
#define WIFI_RECOVER_TIME_MS 30000 // Wait 30 seconds after a failed connection attempt
int muteOn = 0;// 0=Mute
int muteOff = 1;// 1=Unmute
int input;
WiFiUDP Udp;
const IPAddress outIp (192, 168, 10, 129); //Mixers IP
const unsigned int outPort = 10023; //X32 Port
//variables for blinking an LED with Millis
const int led = 2; // ESP32 Pin to which onboard LED is connected
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 300; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED
void connectToWiFi(){
Serial.print("Zu WLAN verbinden...");
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_NETWORK, WIFI_PASSWORD);
unsigned long startAttemptTime = millis();
while(WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < WIFI_TIMEOUT_MS){
Serial.println(".");
delay(100);
}
if(WiFi.status() != WL_CONNECTED){
Serial.println("Nicht Verbunden!");
//optional take action
}else{
Serial.print("WLAN Verbunden mit ");
Serial.println(WIFI_NETWORK);
Serial.println(WiFi.localIP( ));
}
}
void setup() {
Serial.begin(115200);
connectToWiFi();
Udp.begin(8888);
pinMode(led, OUTPUT);
// Port defaults to 3232
// ArduinoOTA.setPort(3232);
// Hostname defaults to esp3232-[MAC]
// ArduinoOTA.setHostname("myesp32");
// No authentication by default
// ArduinoOTA.setPassword("admin");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
ArduinoOTA.handle();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
ledState = not(ledState);
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
}
input=Serial.read();
if (input=='0'){
// welcher status hat der kanal?
// wenn Kanal gemutet dann unmute und umgekehrt
Serial.println("Mute!");
delay(100);
sendMute(); //send Mute to Mixer
Serial.println("...");
}
if (input=='1'){
Serial.println("UnMute!");
delay(100);
sendUnMute();
Serial.println("...");
}
}
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg("/ch/01/mix/on");
msg.add(muteOn);
Udp.beginPacket(outIp, outPort);
msg.send(Udp); // send the bytes to the SLIP stream
Udp.endPacket(); // mark the end of the OSC Packet
msg.empty(); // free space occupied by message
delay(20);
}
void sendUnMute() {
//the message wants an OSC address as first argument
OSCMessage msg("/ch/01/mix/on");
msg.add(muteOff);
Udp.beginPacket(outIp, outPort);
msg.send(Udp); // send the bytes to the SLIP stream
Udp.endPacket(); // mark the end of the OSC Packet
msg.empty(); // free space occupied by message
delay(20);
}
So I testet this via serial Monitor, when I input "0" and click send, the mixer mutes channel 1 and on input "1" channel 1 becomes unmuted, so far so good... (OSCMessage msg("/ch/01/mix/on"); ... section.
What bothers me here in special is, I had to hardcode the command "/ch/01/mix/on", because I am not able to declare a variable? for this string? I am already so confused that I don´t know if I even have the terms right :-(
BTW: There are a lot solutions out there how to do it with MIDI, but MIDI is not wireles and I think for my project overkill. I also did some some research on github.com/CNMAT/OSC but I don´t get it... (crying)...
I found also a post here, but this didn´t helped either... :-(
Any advice on that how I can reach my goal?--
Any help is much apprceiated... even in German (my native language... )
PS: Yes I´m a begginner and I admit it. But at least I managed how to connect and flash this thing even via OTA in the last 8 days, so please be easy on me.
Not wanting to hardcode your commands is a good instinct.
The Arduino language is C++, which is (mostly) a superset of C. C and C++ use a preprocessor which lets you define constants and test for their presence.
For instance, you could write:
#define CHAN01_MIX_ON_COMMAND "/ch/01/mix/on"
and then use CHAN01_MIX_ON_COMMAND anywhere you want to use that constant, like so:
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg(CHAN01_MIX_ON_COMMAND);
Then if you ever need to change the string "/ch/01/mix/on" you can just change it in one location and not worry about finding every instance of it in your code.
Writing the names in #define statements is a convention people usually follow in order to make it more clear that they're constants.
You have to write the #define line before you use the constant you defined, so putting it at the start of the file (after any #include lines and before your first function) is a good practice. Or if you have several you might put them all in their own file called something like commands.h (the .h means header file)and then include that at the start of any file that needs it like so:
#include "commands.h"
This #include statement would insert the contents of the file commands.h into the file that the statement is in.
When you have several #define statements, keeping them all together in one place (whether it's at the top of the file or in their own file) is also a good practice so that you have one central place to find them and update them if you need to.
Some people will assign the string constant to a variable like so:
char *channel01_mix_on_cmd = "/ch/01/mix/on";
Here char means "a character" - like one letter or number or symbol. The * means pointer to, which lets you use an array of characters. Simple strings in C and C++ are just arrays of characters (or a pointer to the first character), with a special hidden character at the end set to numeric value 0 (not the character '0'). C++ also has a string datatype called std::string and Arduino programs have String but those are both overkill here. They all let you work with strings; String is much easier to use than char * but both have strengths and weaknesses.
Like the #define, you'd also place that outside a function near the start of the file. It defines a global variable that would be available to any function that references it.
You'd also use the variable anywhere they want the string. It's the same idea as using #define, just done slightly differently. For instance:
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg(channel01_mix_on_cmd);
Using a variable here is an attempt to save storage by not having multiple copies of the string. It's not necessary; C/C++ compilers have for a very long time detected this and stored only one copy of the string. It might save space if your code is split into multiple files.
Saving space on CPUs like the ESP32 and ESP8266 is important because they have so little memory. #define is fine here because the compiler does it automatically for you.
You can create the command string with sprintf.
so for example:
#define CHANNELON "on"
#define CHANNELOFF "off"
int channel;
int mute;
char messageString[100];
// some code that calculates the channel number and the mute state:
channel = 1;
mute = 1;
// then check the mute state and create the command string:
if (mute)
{
// to turn off a channel:
sprintf(messageString,"/ch/%02d/mix/%s",channel,CHANNELOFF);
}
else
{
// to turn on a channel:
sprintf(messageString,"/ch/%02d/mix/%s",channel,CHANNELON);
}
// send the command:
OSCMessage msg(messageString);
the %02d will substitute an integer with a zero in front,
if it's smaller than 10 and that is always 2 characters long.
so if channel is 1, the result would be 01
I try original O-Scope project (PigOScope) without touchscreen based on STM32F103C8T6 Bluepill board, but got some problem:
I used newest rogerclarkmelbourne/Arduino_STM32 Core and downloaded
pingumacpenguin/STM32-O-Scope sketch. I compiled and uploaded it to the device via UART from 0x08000000 address. Then I started the device. The grid and coordinate lines were displayed on the screen. Also on the screen were displayed inscriptions below 0.0 uS/Sample etc... But any noise or pulse signal from PB1 on my Probe. Why the chart is not drawn?
Also I tried to log my steps in Usart in DMA activation code function:
void takeSamples()
{
// This loop uses dual interleaved mode to get the best performance out of
the ADCs
Serial.println("Init DMA");
dma_init(DMA1);
dma_attach_interrupt(DMA1, DMA_CH1, DMA1_CH1_Event);
Serial.println("Enable DMA for ADC");
adc_dma_enable(ADC1);
dma_setup_transfer(DMA1, DMA_CH1, &ADC1->regs->DR, DMA_SIZE_32BITS,
dataPoints32, DMA_SIZE_32BITS, (DMA_MINC_MODE |
DMA_TRNS_CMPLT));// Receive buffer
Serial.println("Set DMA transfer");
Serial.println(maxSamples / 2);
dma_set_num_transfers(DMA1, DMA_CH1, maxSamples / 2);
dma1_ch1_Active = 1;
Serial.println("Enable the channel and start the transfer");
dma_enable(DMA1, DMA_CH1); // Enable the channel and start the transfer.
samplingTime = micros();
Serial.println(samplingTime);
while (dma1_ch1_Active); // SOME BUG OR WHAT.... PROGRAM STOP HERE!!!
samplingTime = (micros() - samplingTime);
Serial.println("Disable DMA");
dma_disable(DMA1, DMA_CH1); //End of trasfer, disable DMA and Continuous
mode.
}
Event handler for stop interrupt
static void DMA1_CH1_Event()
{
dma1_ch1_Active = 0;
}
Volatile flag to stop routine
volatile static bool dma1_ch1_Active = 0;
Program keep crushing on while loop i think... And program does't work beyond takeSamples() function.
Why program does't exit the loop?
Overview:
I'm trying to program a microbit with Ada using the Ada Drivers Library and I can't understand how to use the i2c functions to establish communications with another chip. I'd like to establish a simple demo so I can understand what's happening because the demos in the components directory of the Ada Drivers Library are going over my head (I'm pretty new to Ada too and that doesn't help matters).
The simplest i2c demo in the Ada Drivers Library appears to be for the AK8963 three axis compass (located in /components/src/motion/ak8963/). But that's still going over my head and I don't have the chip to run and debug the code.
Here's what I've tried:
I've created two different demos with arduinos. In both demos the transmitter sends an 'A' and then a 'B' all the way to 'Z' and then loops back to 'A'. In the first demo the master transmits the next character every 500 ms and the slave receives it. And in the second demo the master requests the next character every 500 ms and the slave transmits it.
My demos are adapted from the arduino Wire examples found here and here.
I figured it out.
Let's start with the two Arduino programs to prove that the Arduino code works.
Arduino Slave transmit:
/*
Sends the next letter of the alphabet with each
request for data from master.
Watch the serial monitor to see what's happening.
*/
#include <avr/wdt.h>
#include <Wire.h>
// A note about I2C addresses.
// The Ada program is looking for the slave on address 16
// but this code says the slave is on 8.
// What's happening? As best as I can tell it works
// like this:
// 16 in binary is 10000. But arduino strips the read/write bit
// (which is the last bit) off of the address so it becomes
// 1000 in binary. And 1000 in binary is 8.
const int SLAVE_ADDRESS = 8;
byte letter = 65; // letter A
unsigned long counter = 0;
void setup()
{
wdt_reset();
wdt_enable(WDTO_8S);
Serial.begin(9600);
Serial.println("beginning");
Wire.begin(SLAVE_ADDRESS); // join i2c bus
Wire.onRequest(requestEvent); // register event
}
void loop()
{
wdt_reset();
counter++;
if(counter % 1000 == 0)
{
// Display a heart beat so we know the arduino has not hung.
Serial.print("looping: ");
Serial.println(counter);
}
delay(5);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
// send the current letter on I2C
Wire.write(letter);
Serial.print("transmitting: ");
Serial.println(char(letter));
letter++;
if(letter > 90) // if greater than Z
{
letter = 65; // reset to A
}
}
Arduino Master receive:
/*
Requests a character from the slave every 500 ms and prints it
to the serial monitor.
*/
#include <avr/wdt.h>
#include <Wire.h>
const int SLAVE_ADDRESS = 8;
void setup()
{
wdt_reset();
wdt_enable(WDTO_8S);
Wire.begin(); // join i2c bus
Serial.begin(9600);
}
void loop()
{
// reset the watchdog timer
wdt_reset();
// request one byte from the slave
Wire.requestFrom(SLAVE_ADDRESS, 1);
while(Wire.available()) // slave may send less than requested
{
// receive a byte as character
char c = Wire.read();
Serial.println(c);
}
delay(500);
}
These two Arduino sketches will happily pass characters all day. Now replace the Arduino master receiver with the Ada version below and physically disconnect the Arduino master receiver.
Ada master receiver (main.abd):
-- Request a character from the I2C slave and
-- display it on the 5x5 display in a loop.
with HAL.I2C; use HAL.I2C;
with MicroBit.Display; use MicroBit.Display;
with MicroBit.I2C;
with MicroBit.Time;
procedure Main is
Ctrl : constant Any_I2C_Port := MicroBit.I2C.Controller;
Addr : constant I2C_Address := 16;
Data : I2C_Data (0 .. 0);
Status : I2C_Status;
begin
MicroBit.I2C.Initialize (MicroBit.I2C.S100kbps);
if MicroBit.I2C.Initialized then
-- Successfully initialized I2C
Display ('I');
else
-- Error initializing I2C
Display ('E');
end if;
MicroBit.Time.Delay_Ms (2000);
MicroBit.Display.Clear;
loop
-- Request a character
Ctrl.Master_Receive (Addr => Addr, Data => Data, Status => Status);
-- Display the character or the error
if Status = Ok then
Display (Character'Val (Data (0)));
else
MicroBit.Display.Display (Status'Image);
end if;
-- Give the user time to read the display
MicroBit.Time.Delay_Ms (1000);
MicroBit.Display.Clear;
MicroBit.Time.Delay_Ms (250);
end loop;
end Main;
And here is the Ada project file for completeness:
with "..\..\Ada_Drivers_Library\boards\MicroBit\microbit_zfp.gpr";
project I2C_Master_Receive_Demo is
for Runtime ("ada") use Microbit_Zfp'Runtime ("Ada");
for Target use "arm-eabi";
for Main use ("main.adb");
for Languages use ("Ada");
for Source_Dirs use ("src");
for Object_Dir use "obj";
for Create_Missing_Dirs use "True";
package Compiler renames Microbit_Zfp.Compiler;
package Linker is
for Default_Switches ("ada") use Microbit_Zfp.Linker_Switches & ("-Wl,--print-memory-usage", "-Wl,--gc-sections", "-U__gnat_irq_trap");
end Linker;
package Ide is
for Program_Host use ":1234";
for Communication_Protocol use "remote";
for Connection_Tool use "pyocd";
end Ide;
end I2C_Master_Receive_Demo;
Tips:
you need to observe the I2C address offsets (16 in Ada = 8 on Arduino in my case). See the explanation in the comments of the slave transmit arduino code above. It took me a long time to figure that out.
nothing worked with three devices connected to the I2C bus, even if one of them was not powered. I don't know exactly what's happening there but I suspect its related to documentation stating that the I2C bus cannot pull its lines back to HIGH. Some documentation recommends placing a resistor on both I2C lines connected to your source voltage so the line voltages return to HIGH after the devices pulls them low.
this work would be easier with an oscilloscope. I could have figured out this problem much more quickly if I had had one.
I have not been able to test the code below, but it should at least give you some direction. Please note that the micro:bit acts as a master. I don't think the micro:bit can act as a slave on a I2C bus (but I might be wrong here). Also note that you may have to change the path to the microbit_zfp.gpr in the project file.
default.gpr
with "../Ada_Drivers_Library/boards/MicroBit/microbit_zfp.gpr";
project Default is
for Runtime ("ada") use MicroBit_ZFP'Runtime ("Ada");
for Target use "arm-eabi";
for Main use ("main.adb");
for Languages use ("Ada");
for Source_Dirs use ("src");
for Object_Dir use "obj";
for Create_Missing_Dirs use "True";
package Compiler renames MicroBit_ZFP.Compiler;
package Linker is
for Default_Switches ("Ada") use
MicroBit_ZFP.Linker_Switches &
("-Wl,--print-memory-usage",
"-Wl,--gc-sections",
"-U__gnat_irq_trap");
end Linker;
end Default;
main.adb
with MicroBit.Display; use MicroBit.Display;
with MicroBit.Time; use MicroBit.Time;
with MicroBit.I2C; use MicroBit.I2C;
with HAL.I2C; use HAL.I2C;
procedure Main is
begin
MicroBit.I2C.Initialize (S400kbps); -- Change to desired speed.
declare
Ctrl : constant Any_I2C_Port := MicroBit.I2C.Controller;
Addr : constant I2C_Address := 16#08#; -- Change to correct address.
Data : I2C_Data (0 .. 0);
Status : I2C_Status;
begin
loop
-- Data to be send (here: character 'x').
Data (0) := Character'Pos ('x');
-- Display a dot to indicate where we are.
Display ('.');
-- Send 1 byte of data (length of Data array is 1).
Ctrl.Master_Transmit (Addr, Data, Status);
-- Additional status checking could be done here....
-- Display a colon to indicate where we are.
Display (':');
-- Wait for response (1 byte as the length of the Data array is 1).
Ctrl.Master_Receive (Addr, Data, Status);
-- Check status, and display character if OK.
if Status = Ok then
Display (Character'Val (Data (0)));
else
Display ('!');
end if;
-- Take a short nap (time in milliseconds).
Sleep (250);
end loop;
end;
end Main;
I have a current interest in the BBC micro:bit and i2c and tried the program, having earlier got a program to build and upload successfully. Building with these two files have should have easier, still not got it to build, struggling with GPS ... I'll try again soon...
I'm having issues displaying the serial monitor on an lcd. I am not getting any error and the LCD is lit up so I don't think I wired it wrong. I am able to open up the serial monitor/plotter and see in information changing so my other component is also working so the problem must be in the code...
#include <LiquidCrystal.h>
/**
* LIDARLite I2C Example
* Author: Garmin
* Modified by: Shawn Hymel (SparkFun Electronics)
* Date: June 29, 2017
*
* Read distance from LIDAR-Lite v3 over I2C
*
* See the Operation Manual for wiring diagrams and more information:
* http://static.garmin.com/pumac/LIDAR_Lite_v3_Operation_Manual_and_Technical_Specifications.pdf
*/
#include <Wire.h>
#include <LIDARLite.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// Globals
LIDARLite lidarLite;
int cal_cnt = 0;
void setup()
{
Serial.begin(9600); // Initialize serial connection to display distance readings
lidarLite.begin(0, true); // Set configuration to default and I2C to 400 kHz
lidarLite.configure(0); // Change this number to try out alternate configurations
lcd.begin(16, 2);
// initialize the serial communications:
}
void loop()
{
int dist;
// At the beginning of every 100 readings,
// take a measurement with receiver bias correction
if ( cal_cnt == 0 ) {
dist = lidarLite.distance(); // With bias correction
} else {
dist = lidarLite.distance(false); // Without bias correction
}
// Increment reading counter
cal_cnt++;
cal_cnt = cal_cnt % 100;
// Display distance
Serial.print(dist);
Serial.println(" cm");
delay(10);
// when characters arrive over the serial port...
if (Serial.available()) {
// wait a bit for the entire message to arrive
delay(100);
// clear the screen
lcd.clear();
// read all the available characters
while (Serial.available() > 0) {
// display each character to the LCD
lcd.write(Serial.read());
}
}
}
The LCD should be displaying the changing measurements
The LCD is lit up and I can adjust the back light but I can't get anything to show up.
Just because the LCD is "lit" doesn't mean it's wired correctly. In fact, the backlighting circuit is usually totally separate from the data and control signals circuits. I would start by checking the assumption that it's wired correctly with a simple command to print a known value to the LCD:
lcd.clear();
lcd.println("TEST");
If this works, then you know the LCD is working and can look elsewhere for the problem.
If this doesn't work, I'd question your assumption that it's hooked up correctly, but if you still get nothing but "blue blocks" then it might be something as simple as your contrast is not correct. It can be tricky getting the contrast and brightness to a good combination for readability. See if your display has a small potentiometer (usually adjustable with a very small Philips-head driver) on the back and carefully adjust the contrast.
Brightness is often changeable through software commands but most LCDs default to high brightness when first booted up.
If changing contrast doesn't work, you may have a real wiring problem and then it really is off-topic for this forum. In that case you should sketch a schematic and post on Electrical Engineering stack.
I have one Arduino with 4 Pots. The other Arduino receives these 4 values via i2c and prints them on a Display. The problem is that I don't know how to send these 4 values that the Slave is able to know which value belongs to which Pot.
Slave Code:
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup()
{
Wire.begin(5);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
lcd.begin(16,2);
}
void loop()
{
}
void receiveEvent(int)
{
while(Wire.available())
{
//How to create this part? How does the Slave know which value belongs to which pot?
}
}
Master Code:
#include <Wire.h>
void setup()
{
Serial.begin(9600);
Wire.begin();
delay(2000);
}
void loop()
{
int sensor1 = analogRead(A1);
Wire.beginTransmission(5);
Wire.write(sensor1);
Serial.print(sensor1);
Wire.endTransmission();
delay(100);
int sensor2 = analogRead(A2);
Wire.beginTransmission(5);
Wire.write(sensor2);
Serial.print(sensor2);
Wire.endTransmission();
delay(500);
}
Ahh what we have here is a basic question on how to design I2C communication. Unfortunately Examples for I2C master and slave included in Arduino IDE are IMO too limited to provide clear guidance on this matter.
First of all in your examples the master and slaves roles are exchanged and should be switched. Slave should read values from analog inputs and master should request them. Why? Because it's master which should decide when to request values and properly decode the request. Slave should provide proper answer to a given request eliminating the problem of data interpretation.
I2C communication is based on requestFunction-(wait)-requestResponse sequence controlled by the master.
Plese refer to the range finder example on arduino page. In a nutshell:
First: master requests a function to measure distance:
// step 3: instruct sensor to return a particular echo reading
Wire.beginTransmission(112); // transmit to device #112
Wire.write(byte(0x02)); // sets register pointer to echo #1 register (0x02)
Wire.endTransmission(); // stop transmitting
(sometimes slaves need some time e.g. 10 - 50 ms to process requests but in the example I'm refering to master doesn't delay read)
Second: master requests response:
// step 4: request reading from sensor
Wire.requestFrom(112, 2); // request 2 bytes from slave device #112
Third: master tries to read and analyze response.
You should design reliable I2C communication in a similar way.
Here is how I do it; you can follow my pattern and get extensible slave implementation which will support one function: read analog inputs but can be easily extended by adding additional function codes and required processing implementation to the slave main loop
Initial remarks
some kind of a simple protocol is needed to control slave - e.g. it should support requesting functions. Supporting functions requests is not absolutely needed in such simmple scenario as reading four analog inputs but what I'm describing is a more general pattern you may use in other projects.
Slave should not perform any additional actions (like reading inputs) on request response as I2C communication may break (due to delays) and you will get partial responses etc. This is very important requirement which affect the slave design.
response (and also request if needed) can contain CRC as if master waits not long enough it may get empty response. If nobody else is going to use your code such countermeasures are not needed and will not be described here. Other important thing is Wire library buffer limitation which is 32 bytes and implementing CRC checksum without modifying the buffer length limits the available data length by two bytes (if crc16 is used).
slave:
#include <WSWire.h> // look on the web for an improved wire library which improves reliability by performing re-init on lockups
// >> put this into a header file you include at the beginning for better clarity
enum {
I2C_CMD_GET_ANALOGS = 1
};
enum {
I2C_MSG_ARGS_MAX = 32,
I2C_RESP_LEN_MAX = 32
};
#define I2C_ADDR 0
#define TWI_FREQ_SETTING 400000L // 400KHz for I2C
#define CPU_FREQ 16000000L // 16MHz
extern const byte supportedI2Ccmd[] = {
1
};
// << put this into a header file you include at the beginning for better clarity
int argsCnt = 0; // how many arguments were passed with given command
int requestedCmd = 0; // which command was requested (if any)
byte i2cArgs[I2C_MSG_ARGS_MAX]; // array to store args received from master
int i2cArgsLen = 0; // how many args passed by master to given command
uint8_t i2cResponse[I2C_RESP_LEN_MAX]; // array to store response
int i2cResponseLen = 0; // response length
void setup()
{
// >> starting i2c
TWBR = ((CPU_FREQ / TWI_FREQ_SETTING) - 16) / 2;
Wire.begin(I2C_ADDR); // join i2c bus
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent);
// << starting i2c
}
void loop()
{
if(requestedCmd == I2C_CMD_GET_ANALOGS){
// read inputs and save to response array; example (not tested) below
i2cResponseLen = 0;
// analog readings should be averaged and not read one-by-one to reduce noise which is not done in this example
i2cResponseLen++;
i2cResponse[i2cResponseLen -1] = analogRead(A0);
i2cResponseLen++;
i2cResponse[i2cResponseLen -1] = analogRead(A1);
i2cResponseLen++;
i2cResponse[i2cResponseLen -1] = analogRead(A2);
i2cResponseLen++;
i2cResponse[i2cResponseLen -1] = analogRead(A3);
// now slave is ready to send back four bytes each holding analog reading from a specific analog input; you can improve robustness of the protocol by including e.g. crc16 at the end or instead of returning just 4 bytes return 8 where odd bytes indicate analog input indexes and even bytes their values; change master implementation accordingly
requestedCmd = 0; // set requestd cmd to 0 disabling processing in next loop
}
else if (requestedCmd != 0){
// log the requested function is unsupported (e.g. by writing to serial port or soft serial
requestedCmd = 0; // set requestd cmd to 0 disabling processing in next loop
}
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent(){
Wire.write(i2cResponse, i2cResponseLen);
}
// function that executes when master sends data (begin-end transmission)
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
//digitalWrite(13,HIGH);
int cmdRcvd = -1;
int argIndex = -1;
argsCnt = 0;
if (Wire.available()){
cmdRcvd = Wire.read(); // receive first byte - command assumed
while(Wire.available()){ // receive rest of tramsmission from master assuming arguments to the command
if (argIndex < I2C_MSG_ARGS_MAX){
argIndex++;
i2cArgs[argIndex] = Wire.read();
}
else{
; // implement logging error: "too many arguments"
}
argsCnt = argIndex+1;
}
}
else{
// implement logging error: "empty request"
return;
}
// validating command is supported by slave
int fcnt = -1;
for (int i = 0; i < sizeof(supportedI2Ccmd); i++) {
if (supportedI2Ccmd[i] == cmdRcvd) {
fcnt = i;
}
}
if (fcnt<0){
// implement logging error: "command not supported"
return;
}
requestedCmd = cmdRcvd;
// now main loop code should pick up a command to execute and prepare required response when master waits before requesting response
}
master:
#include <WSWire.h>
#define I2C_REQ_DELAY_MS 2 // used for IO reads - from node's memory (fast)
#define I2C_REQ_LONG_DELAY_MS 5 //used for configuration etc.
#define TWI_FREQ_SETTING 400000L
#define CPU_FREQ 16000000L
enum {
I2C_CMD_GET_ANALOGS = 1
};
int i2cSlaveAddr = 0;
void setup(){
// joining i2c as a master
TWBR = ((CPU_FREQ / TWI_FREQ_SETTING) - 16) / 2;
Wire.begin();
}
void loop(){
//requesting analogs read:
Wire.beginTransmission(i2cSlaveAddr);
Wire.write((uint8_t)I2C_CMD_GET_ANALOGS);
Wire.endTransmission();
delay(I2C_REQ_DELAY_MS);
// master knows slave should return 4 bytes to the I2C_CMD_GET_ANALOGS command
int respVals[4];
Wire.requestFrom(i2cSlaveAddr, 4);
uint8_t respIoIndex = 0;
if(Wire.available())
for (byte r = 0; r < 4; r++)
if(Wire.available()){
respVals[respIoIndex] = (uint8_t)Wire.read();
respIoIndex++;
}
else{
// log or handle error: "missing read"; if you are not going to do so use r index instead of respIoIndex and delete respoIoIndex from this for loop
break;
}
// now the respVals array should contain analog values for each analog input in the same order as defined in slave (respVals[0] - A0, respVals[1] - A1 ...)
}
I hope my example will help. It's based on code working for weeks making 40 reads a second from multiple slaves however I have not compiled it to test the function you require.
Please use WSWire library as the Wire (at least as for Arduino 1.0.3) may occasionally freeze your master if for some reason slave will not respond to request.
EDIT: The WSWire lib requires external pull-up resistors for I2C unless you modify the source and enable internal pull-ups like Wire does.
EDIT: instead of creating i2c slave implementation you may try the EasyTransfer library. I haven't tried it but it may be easier to use it if sending four bytes is everything you need.
EDIT[12.2017]: There is a new player on the block - PJON - a library suited for easy multi-master communication ideal to exchange pot values (and much more). It's been around for some time but gained a substantial development speed in recent months. I'm partially involved in its development and switched all field-level and local buses I've used so far (I2C, MODBUS RTU) to PJON over single wire, hardware serial or RF.
Check out GitHub-I2CBus, I've done the exact same thing. Hope it can help