text:
ISR and multiplexing- time required to execute the code in Arduino
Below is an Arduino sketch for a basic animation, taken from the book Beginning Arduino by Michael McRoberts. Also, the connections have been shown. From what I have read elsewhere, this is the standard kind of code used to drive a LED dot matrix using the 595 shift registry, or the like (for example the MAX7219). Regarding the functioning of the code, I have two questions.

For what percentage of the time will the LED stay lit? In the screenupdate() there are no set delays. Hence, each row will stay lit only for the time it takes for the Arduino to execute the remaining loop and come back with the updated row values. How do we know for what time will the LEDs be lit, and hence predict their brightness, or for what can we do to set a particular value for this?
As I understand from the code, it works assuming that the ISR will fire as the code is running and will include all stages of the led[]. Although in this case it is not much significant, but how do we know that the ISR will fire including all the stages?If say we are updating each row of the matrix, to give a scroll effect, we would need the ISR to fire after each modification. How do we ensure this? If the ISR is too frequent, it may not let the code run. Or if it is too dispersed, the code may skip lines giving a jagged animation. Also, since the code would have some periodicity, is it not possible that some LED rows are always skipped? How do we determine the time of ISR firing perfect for the code or modify the code to ensure these do not happen(except trial and error)?

#include <TimerOne.h>

int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch)
int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock)
int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data)
byte led[8]; // 8 element unsigned integer array to hold the sprite

void setup() {
  // set the 3 digital pins to outputs
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  // Load the binary representation of the image into the array
  led[0] = B11111111;
  led[1] = B10000001;
  led[2] = B10111101;
  led[3] = B10100101;
  led[4] = B10100101;
  led[5] = B10111101;
  led[6] = B10000001;
  led[7] = B11111111;
  // set a timer of length 10000 microseconds (1/100th of a second)
  // and attach the screenUpdate function to the interrupt timer
  Timer1.initialize(10000);
  Timer1.attachInterrupt(screenUpdate);
}

// invert each row of the binary image and wait 1/4 second
void loop() {
  for (int i = 0; i < 8; i++) {
    led[i] = ~led[i];
  }
  delay (250);
}

// Display the image
void screenUpdate() {
  byte row = B10000000; // row 1
  for (byte k = 0; k < 8; k++) {
    shiftOut(dataPin, clockPin, LSBFIRST, led[k] ); // LED array
    shiftOut(dataPin, clockPin, LSBFIRST, ~row); // row binary number (active low)
    // latch low to high to output data
    digitalWrite(latchPin, LOW);
    digitalWrite(latchPin, HIGH);
    // bitshift right
    row = row >> 1;
  }
  // Turn all rows off until next interrupt
  shiftOut(dataPin, clockPin, LSBFIRST, 0);
  shiftOut(dataPin, clockPin, LSBFIRST, ~0);
  // latch low to high to output data
  digitalWrite(latchPin, LOW);
  digitalWrite(latchPin, HIGH);
}

ADDENDUM
In the above code, I tried putting Serial.println(micros()) in the screenUpdate() loop, but I git a very confusing results in which the time displayed seemed to increase and then decrease randomly. I did not understand why. Has it got to do something with ISRs? Sorry for the apparently clumsy question.
I executed the following code (from the same book) out, which includes a MAX7219 driver (with the usual setup) and creates scrollable text. It worked perfectly well. And I just want to understand how this ISR and multiplexing go together, and how do we make sure the frequency is appropriate. More of an academic question rather than a practical one.
#include <avr/pgmspace.h>
#include <TimerOne.h>
int DataPin = 2; // Pin 1 on MAX
int LoadPin = 3; // Pin 12 on MAX
int ClockPin = 4; // Pin 13 on MAX
byte buffer[8];
#define SCAN_LIMIT_REG 0x0B
#define DECODE_MODE_REG 0x09
#define SHUTDOWN_REG 0x0C
#define INTENSITY_REG 0x0A
static byte font[][8] PROGMEM = {
// The printable ASCII characters only (32-126)
}
void clearDisplay() {
for (byte x=0; x<8; x++) {
buffer[x] = B00000000;
}
screenUpdate();
}
void initMAX7219() {
pinMode(DataPin, OUTPUT);
pinMode(LoadPin, OUTPUT);
pinMode(ClockPin, OUTPUT);
clearDisplay();
writeData(SCAN_LIMIT_REG, B00000111); // scan limit set to 0:7
writeData(DECODE_MODE_REG, B00000000); // decode mode off
writeData(SHUTDOWN_REG, B00000001); // Set shutdown register to normal operation
intensity(15); // Values 0 to 15 only (4 bit)
}
void intensity(int intensity) {
writeData(INTENSITY_REG, intensity); //B0001010 is the Intensity Register
}
void writeData(byte msb, byte lsb) {
digitalWrite(LoadPin, LOW); // set loadpin ready to receive data
shiftOut(DataPin, ClockPin, MSBFIRST, (msb));
shiftOut(DataPin, ClockPin, MSBFIRST, (lsb));
digitalWrite(LoadPin, HIGH); // latch the data
}
void scroll(char myString[], int rate) {
byte firstChrRow, secondChrRow;
byte ledOutput;
byte chrIndex = 0; // Initialise the string position index
byte Char1, Char2;
byte scrollBit = 0;
byte strLength = 0;
unsigned long time;
unsigned long counter;
while (myString[strLength]) { // Increment count till we reach the end of the string
strLength++;}
counter = millis();
while (chrIndex < (strLength)) {
time = millis();
if (time > (counter + rate)) {
Char1 = constrain(myString[chrIndex],32,126);
Char2 = constrain(myString[chrIndex+1],32,126);
for (byte y= 0; y<8; y++) {
firstChrRow = pgm_read_byte(&font[Char1 - 32][y]);
secondChrRow = (pgm_read_byte(&font[Char2 - 32][y])) << 1
ledOutput = (firstChrRow << scrollBit)
| (secondChrRow >> (8 - scrollBit) );
buffer[y] = ledOutput;
}
scrollBit++;
if (scrollBit > 6) {
scrollBit = 0;
chrIndex++;
}
counter = millis();
}
}
}
void screenUpdate() {
for (byte row = 0; row < 8; row++) {
writeData(row+1, buffer[row]);
}
}
void setup() {
initMAX7219();
Timer1.initialize(10000); // initialize timer1 and set interrupt period
Timer1.attachInterrupt(screenUpdate);
Serial.begin(9600);
}
void loop() {
clearDisplay();
scroll(" BEGINNING ARDUINO ", 45);
scroll(" Chapter 7 - LED Displays ", 45);
scroll(" HELLO WORLD!!! :) ", 45);
}

You also might want to add some transitors, instead of resistors for the row. Otherwise, the more leds are lid in a single row, the dimmer they appear.

@Gerben, I always hear this advice but I put together a dotmatrix display and yanked out all the LEDs but one for a row and found them to be the same brightness. What I'd suggest is use one resistor per column, and use one transistor per row, which should ensure the LEDs get even power but my multimeter isn't in yet so I'm not sure (I know my LEDs aren't variable brightness though). This actually makes sense when you remember the lights are actually in a parallel circuit, they shouldn't change brightness when you have less lights.

This setup also ensures (because the display isn't all lit at once) that one transistor is active for a row of LEDs, and each LED would still have one resistor limiting current. (I should note I also haven't tested powering an entire row of LEDs on an 8x8 dotmatrix display from just one pin without a transistor as I was afraid of drawing more than 40mA).

@redstarcoder you're suggesting the same thing I was trying (and maybe failing) to say.

@Gerben oh probably! I read your suggestion as saying to not use any resistors are all, which alarmed me :).

(In a comment the asker mentioned they're not sure of the "usual approach", so I've provided this answer to hopefully help clarify)
Here is my code for using a single 595 to drive the columns, and hooking up the rows to the Arduino pins themselves. Here I demonstrate a clear delay in each row update, as well as another delay before the image changes. I hope this helps clear up your confusion, and I apologize for not have a 2 595 setup handy (though I have 2 595s so if this doesn't help you, I'd be more than happy to set it up...), but it should be easy to adapt for a second 595. This supports a variable amount of width and height.
I also answered this assuming you just want the dotmatrix display functioning correctly, and I didn't focus on ISR. On first glance I see no delay in the row updating on the ISR version, or a delay when setting the latch pin and the whole thing seems pretty confusing. Honestly I think it might work in a perfect universe but I'm not sure (it wouldn't, as the other answer said, you'll probably just maybe observe a flicker and one row being lit). If this isn't an X Y problem and you really need ISR, I can answer that too, it just seems like we're getting into a lot of questions at once here...
// Pin connected to ST_CP of 74HC595
const int latchPin = 8;
// Pin connected to SH_CP of 74HC595
const int clockPin = 12;
// Pin connected to DS of 74HC595
const int dataPin = 11;
// The pin of the first row of your display
const int row1Pin = 2; // WARNING: All future rows are assumed to be row1Pin + n
// The amount of rows your display has
const int HEIGHT = 3;
// The amount of columns your display has
const int WIDTH = 2;
// The reset pin of 74HC595 (not required as it isn't used, but this pin is pulled low)
const int resetPin = 9;
// Variable used to keep track of currently lit up row
int currentRow = 0;
// Array of rows
int rows[] = {0b11,
              0b01,
              0b11};
unsigned long lastChange = 0;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin, LOW);
}

/* I don't think this works, but it might with a much higher delay.
void reset() {
  pinMode(resetPin, INPUT);
  delayMicroseconds(1);
  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin, LOW);
}
*/

// enableRow changes the currently enabled row for future calls, it also changes
// the pinMode on the previous row to "INPUT", disabling all lights on that row.
void enableRow(int row) {
  if (currentRow != 0) {
    pinMode(currentRow, INPUT);
  }
  currentRow = row;
}

// This is a quick function to test one single LED or row on your dotmatrix display (I should have documented this one better but pass an incremeneting number to it and you'll see what it does...).
void lightOne(int pos) {
  enableRow(row1Pin + int(pos / (WIDTH+1)));
  shiftOut(dataPin, clockPin, MSBFIRST, 1 + pos % (WIDTH+1));
}

// This function draws the display stored in "rows".
void displayRows() {
  for (int i = 0; i < HEIGHT; i++) {
    digitalWrite(latchPin, LOW);
    enableRow(row1Pin+i);
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST, rows[HEIGHT-i-1]);
    digitalWrite(latchPin, HIGH);
    pinMode(currentRow, OUTPUT);   // set the current row's pin as OUTPUT
    digitalWrite(currentRow, LOW); // output LOW on currentRow to complete light's circuit and display
    delay(3); // time in ms to hold each row lit
  }
}

void loop() {
  displayRows();
  if (lastChange+1000 /* 1000ms between changes */ < millis()) {
    for (int i = 0; i < HEIGHT; i++) {
      rows[i] = random(4);
    }
    lastChange = millis();
  }
}

I think the code is likely wrong.
the code is called every 10ms, each time refreshing all columns and all rows and then immediately overwriting them all. so you should just see a quick flicker.
the typical way to approach this is to have a static variable to remember the row (or column) to be lit, and then load up the corresponding data for that row + columns when the display routine is called.
blanking isn't necessary for hc595.
edit: 1/21/2017.
now that I have a little bit more time, I would just add to the comments above.
we know the issues, as outlined above. here is a confirmation of it, in a simulation.

I ran your original code on an arduino uno. U2 is the shift register connected to the led matrix's rows (active low), and U3 to the columns (active high).
two things are obvious:
1. the code is invoked every 10ms;
2. the code for the most part resets the display: other than when the code is updating all rows / columns (the first half of the screenUpdate()), rows are high (inactive) and the columns are low (inactive), thanks to the display being reset by the bottom of the screenUpdate() routine.
the net result is that you for the most part don't see anything being displayed on the led, other than very fast flickers.
here is the solution: rewrite screenUpdate(), as below:
// Display the image - alternate routine
void screenUpdate2(void) {
    static unsigned char row = 0; // start with row 0
    //for (byte k = 0; k < 8; k++) {
        shiftOut(dataPin, clockPin, LSBFIRST, led[row] ); // LED array
        shiftOut(dataPin, clockPin, LSBFIRST, ~(1<<row)); // row binary number (active low)
        // latch low to high to output data
        digitalWrite(latchPin, LOW);
        digitalWrite(latchPin, HIGH);
        // bitshift right
        //row = row >> 1;
        row = (row==7)?0:(row+1);
    //}
    // Turn all rows off until next interrupt
    //shiftOut(dataPin, clockPin, LSBFIRST, 0);
    //shiftOut(dataPin, clockPin, LSBFIRST, ~0);
    // latch low to high to output data
    //digitalWrite(latchPin, LOW);
    //digitalWrite(latchPin, HIGH);
}

the updated routine, screenUpdate2(), utilizes a static variable, row, to remember the current row to be displayed. it shifts out the column data, and sets up the row to be activated, and then strikes out the display to the led matrix. after that, it updates row for the next invokation.
here is how it works in the simulation:

hope it helps.
post-it: if the main loop has good execution time (short, and fairly deterministic), you can run screenUpdate2() in the loop and it will work as well. running it through an interrupt provides better consistency.
edit: 1/21/2017 v2
short after posting the above, a couple sharp eyed individuals noticed that the output data seems to be flipped (more noticeable at 320ms in the simulation posted above). good catch.
that's due to the following lines in the main loop:
for (int i=0; i<8; i++) {
    led[i]= ~led[i];
}
delay (250);

I'm not sure what its purpose was in the original code - creating a blinking effect? - but if you comment out those lines, you will see that the execution would be as you would have expected:

you will find that the values match exactly what's in the led[] array.
you can think of led[] as a ram display buffer that stores information to be displayed. all your application code needs to do is to manipulate / update it in the main loop. the display routine, when called by the timer isr, will update that for you periodically, in a fully transparent and carefree manner.
I tend to utilize this approach with a lot of things. Thus having a hook to a timer to execute a piece of code is a valuable tool for a programmer to have.
edit: 1/21/2017 v3
I was asked how long screenUpdate() and screenUpdate() will run on an arduino (16MIPS): screenUpdate() takes about 2.1ms to run, and screenUpdate2() about 0.2ms. those numbers will determine the upper-end of the display update frequency.

Sorry, but being a beginner, I am not aware if the usual approach. Can you expand a bit? And also, I want to know whenever an ISR is set, how to determine the firing frequency.

I checked another one, with the MAX7219 based on the same principles (added in the question), which worked perfectly well. I actually do not want to know another way to do multiplexing, but rather understanding the general principles of IRS and the time taken for execution.

Okay, so a slight confirmation. The small flickers that were visible in the original code, that were the time it took the loop of the screenUpdate() function to complete one round, right?

Also, what software/instrument is the one you used for analysis?


text:
Disable SCK temporarily to save power
for logging of environmental data, I am using a MicroSD card adapter (no brand name, eBay, China) and a 4GB Intenso SD card. I want to read data and write it to the SD card once every 10 minutes. Power consumption needs to be as low as possible.
Between the measurement points, I switch off the power supply to my sensor and SD card adapter using an NPN transistor (BC547B, 2N3904, 2SC945) and put my controller to sleep using jeelib. Everything works fine!
But I realized, that even during sleep, still 1mA of current is drawn. This disappears, when I remove the SCK connection between the Arduino and the SD controller. Doesn't sound like a lot, but for my purposes, it's a major concern (when SCK is removed, I'm around 6µA during sleep).
Is it possible to switch the SCK signal off during sleep to save that last bit of power?
In case it matters, I am using the SdFat library to write to SD. Initialization is done before each write. I figured, this would be necessary because of the poweroff of 10 minutes. Here's the function:
#include <SdFat.h>
const int chipSelect = 10;
String outfilename = "Bienen.log";

[...]
int writeToFile(String outfilename, String writestring) {

  SdFat SD;
  if (!SD.begin(chipSelect)) {
#ifdef DEBUG
    Serial.println("Card failed, or not present");
    error_signal();
#endif
  } else {
#ifdef DEBUG
    Serial.println("card initialized.");
#endif
  }

File outfile = SD.open(outfilename.c_str(), FILE_WRITE);
#ifdef DEBUG
  Serial.println(outfile);
#endif
  if (outfile) {
    outfile.println(writestring);
    outfile.close();
#ifdef DEBUG
    Serial.println("Wrote successfully.");
    ok_signal();
#endif
    return 0;
  } else {
#ifdef DEBUG
    Serial.println("Writing failed.");
    error_signal();
#endif
    return 1;
  }
}

ok_signal() and error_signal() are merely functions to flash an LED.
EDIT:
Thanks for your reply! I tried the code snippets
SPCR &= ~_BV(SPE)

and
SPCR |= _BV(SPE)

at the appropriate places, although I did not understand them. There was, however, no change in power consumption - SCK still seems to run.
I could not adapt the physical changes detailed in the suggested wordpress article, as the adapter there is quite different from my microSD adapter, and I know too little about hardware to adapt the author's suggestions. It looks and sounds quite promising though ...
Thanks for your time! Any help is greatly appreciated!

You'll have to disable SPI (SPCR &= ~_BV(SPE)), and set the pin to LOW. Then when writing, re-enable SPI (SPCR |= _BV(SPE)).

Also see these posts: https://edwardmallon.wordpress.com/2016/10/27/diy-arduino-promini-data-logger-2016-build-update/ (Section named "The SD Card Adapter"), and https://edwardmallon.wordpress.com/2014/09/22/high-sleep-current-problem-solved/ for a lot of useful low-power information.

Re-visiting the issue, I have found a simple answer:
I set the SPI pins as outputs and inputs respectively:
const int chipSelect = 10;
const int MOSIPin = 11;
const int MISOPin = 12;
const int SCKPin = 13;

and
  pinMode(chipSelect, OUTPUT);
  pinMode(MOSIPin, OUTPUT);
  pinMode(MISOPin, INPUT);
  pinMode(SCKPin, OUTPUT);

Now, before I power down my machine, I do the following:
  SPI.end();
  digitalWrite(SCKPin, HIGH);
  digitalWrite(chipSelect, HIGH);
  digitalWrite(MOSIPin, HIGH);

Now, the drawn current drops from 1mA to roughly 0,02mA, which is satisfactoy for me!
Thanks for reading!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Upload custom trinket firmware
I'd like to disable the trinket 10-second bootloader when powered up, so it will just begin running the program. I would still like to be able to press the reset button to re-program it.
I found an edited version of the bootloader here. Currently, I am using an Arduino Uno and the 'repair the bootloader' sketch to load the hex to the trinket. The default hex is hard coded in the images.cpp file and the same hex is included in the Adafruit bootloader GitHub as trinketgemma_v1.hex.
How can I compile the forked copy to get the final compiled hex that can be burnt into the trinket?
Update:
I get this error when I upload to the board, how did you flash yours?
Setting fuses  Set Low Fuse to: F1 -> A000  Set High Fuse to: D5 -> A800  Set Ext Fuse to: 6 -> A400
Verifying fuses...
    Low Fuse: 0xF1 is 0xF1
    High Fuse: 0xD5 is 0xD5
    Ext Fuse: 0x6 is 0x6

Setting fuses

Verifying flash...
verification error at address 0x14C0 Should be 0x33 not 0x5F
Failed to verify chip

The fuses are set correctly, but it cannot verify the flash. The supplied Adafruit hex looks like about 93 lines of:
":2000000093CA15C0EBCA13C012C011C010C00FC00EC00DC00CC00BC00AC009C008C0112422\n"

Where the updated, compiled hex is about 181 lines of:
":100000005FCA5FCA5FCA5FCA5FCA5FCA5FCA5FCAA8\n"

Does the length of each line matter? The output of a successful flash looks like:
Verifying fuses...
    Low Fuse: 0xF1 is 0xF1
    High Fuse: 0xD5 is 0xD5
    Ext Fuse: 0x6 is 0x6

Setting fuses

Verifying flash...
    Flash verified correctly!
Verifying fuses...

Fuses verified correctly!
*OK!*

Looks like you can just replace the hex in the images.cpp, with the hex in flash_me_xv.hex. Though you have to encapsulate every line between a " and \n". Also make sure to change the fuses in image.cpp (correct value can be found here) (PS nice to see someone using my code)

@Gerben I tried just replacing the hex, however, it says there is an error verifying the flash. I updated the post with more info.

I used the makefile to upload the boot loader.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
RFM69HCW connected to Arduino Nano 33 BLE
I tried to connect my RFM69HCW to Arduino Nano 33 BLE, so that I won't be needing a logic level shifter to downgrade the voltage, since Arduino Nano is already 3.3V. Upon checking its data sheet and pinout, I noticed there's no dedicated pin for CS (Chip Select).
Which pin should I use as CS in the Arduino Nano?
Which pin should I connect the DI0 pin of RFM69HCW in the Arduino Nano?

There is no dedicated CS pin, and you can use any available Dx pin – which enables you, among other things, to have several devices on the same bus. The CS pin allows you to select (hence the S) the right device.

On any Arduino you can use any free digital pin as SPI CS.

Okay. Thank you! Even the DI0 pin of RFM69HCW can I connect it too to any pins of Arduino Nano?

@lostresearch, why not? it is free. the SPI pins on Nano are 11, 12 and 13

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
6-pin BME280 not giving I2C signal

I'm creating a telemetry package for my my mom's model rocket with a MPU6050, a BME280, and a SD reader/writer. The code I found for the BME does not read any information. When I upload an I2C scanner, the MPU gives a signal, but the I2C gives "No i2c signal found". The wiring schematics are the same. I've tried different boards, and I've tried different code. Nothing works.

Re: 12C gives "No i2c signal found" The I2C (I'm guessing) can't talk. So, what exactly is reporting this message. A library? What library? Your code? What code? If you're having problems detecting I2C devices generally run the I2CScanner sketch before trying anything specific to the sensors.

When you don't give us more information, it makes it hard to help. The BME280 can use I2C OR SPI. If it is on a board set up for SPI, that might be the whole problem.....or it is something else. A picture of the board or a schematic of the circuit would help a lot.

Sorry I did not clarify. The code I was using was the 12C scanner code.

Basic debugging: try a minimal setup - connect only the BME280 to the CPU, not the other parts. Run the I2C scanner. Also let us know WHAT are you connecting it to and exactly how did you wire it?

From the datasheet "Interface selection is done automatically based on CSB (chip select) status. If CSB is connected to VDDIO, the I²C interface is active. If CSB is pulled down, the SPI interface is activated. After CSB has been pulled down once (regardless of whether any clock cycle occurred), the I²C interface is disabled until the next power-on-reset." Again, maybe show us a picture of the board or circuit?

Your image does not show VCC and GND connected to your BME280. If that's not your actual wiring, show your actual wiring.

That is the actual wiring, but the board is flipped around.

Is it a 3.3V or a 5V module?

the picture shows no power connection and no ground connection ... you are trying to fly a rocket without an engine

You mean that it's reversed left-to-right and that in actual use it's the CSB and SDO that are unconnected? Really you should just get a picture of it as wired so as not to confuse the crap out people.

sorry ill upload the proper picture, it all works except the pressure value is off the charts.

@ModelRocketeer - I appreciate your frustration and I hope this will be of some help.
First of all, you have to make sure the board is wired correctly and it is anyone's guess whether it is wired correctly because you have not shown that to us and that frustrates us because we would like to help.
Here is a very similar board attached to a D1 mini.

If I flip it over to show the signal names, AND line it up correctly, one can see how it is hooked up....or it is just confusing because it is flipped over.

BUT why not just tell us, like this:

D1 mini<->280
3.3v   <-> Vcc
GND    <-> GND
D1     <-> SCL
D2     <-> SDA

AND show us a clear picture because many eyes on it can increase the likelihood of solving the problem.
BTW: using colored leads helps with checking.
I have several of these generic 280 boards - they are cheap and when I bought mine, they were sold as BME280, but it turns out (after hours of frustration) that they were in fact BMP280. Apparently, the board can hold either. Be forewarned.
I tested my board with a D1, like yours at 3.3v, and an UNO at 5.0V and they both worked.
I then tested a known-to-be BME280 and it worked fine with the D1 mini.
In ALL cases, I was able to use a port scanner and see the I2C address (0x76).
Because you have not been able to detect any connection over I2C for the board but can detect a port for the MPU6050, I think you need to do the following:
Make sure you have the proper connections.
Remove the MPU6050 and have only the BMP/BME connected and run the scanner.
If you still see nothing, I would say the board is bricked. Because you said you tested several boards, I suspect (as have others) that you do not have it connected properly.
When you get it connected properly and can see a port when scanning - try running BME software but if you use the Adafruit programs you might need to force I2C since this is not an Adafruit board. The latter is able to use both I2C and SPI.
If you still don't get results, consider that it may, in fact be a BMP280 and try software for that.
In either event, please let us know what happens.

Did you wait until I finished responding to get it to work? :)

Feels like it, but I stepped away from it for a few hours, and when I came back to it I redid everything and it "worked" though the pressure value, the only one I need is giving me an absurd value and saying I'm 32,000  feet in the air.

Yes, it can't do exact altitude on its own - see https://arduino.stackexchange.com/questions/44715/bmp-280-exact-altimeter-readings

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Sparkfun ISL29125 breakout board issue with Arduino IDE with ESP32
I am working on a project where I need to get the RGB light value from surrounding ambient light.
For that I am using an ESP32 with a Sparkfun ISL29125 breakout board. I have tried to scan available/connected I2C devices addresses. I'm getting the 0x44 address in the output, which is the address of the ISL29125.
But when running the following code, I am not getting any output. I have added the library to the Arduino IDE.
I have checked all wire connections. 2 other sensors are connected to the I2C bus.
I have connected the pins as follows:
GPIO21 (ESP32) -> SDA (ISL29125)
GPIO22(ESP32) -> SCL (ISL29125).
I'm supplying 3.3v and GND from ESP32.
I have scanned the I2C bus and getting the addresses of all connected sensors including the ISL29125.

0X38
0X44 (Address of the ISL29125)
0X47

Following is the source code.
#include <Wire.h>
#include <SparkFunISL29125.h>
SFE_ISL29125 RGB_sensor;
void setup() {
  // Initialize serial communication
  Serial.begin(115200);
  Serial.println("Hello123");
  // Initialize the ISL29125 with simple configuration so it starts sampling
  if (!RGB_sensor.init()) {
    Serial.println("Sensor Initialization Problem\n\r");
  }
}

void loop() {
  Serial.println("Hello");
  // Read sensor values (16 bit integers)
  unsigned int red = RGB_sensor.readRed();
  unsigned int green = RGB_sensor.readGreen();
  unsigned int blue = RGB_sensor.readBlue();

  // Print out readings, change HEX to DEC if you prefer decimal output
  Serial.print("Red: "); Serial.println(red,HEX);
  Serial.print("Green: "); Serial.println(green,HEX);
  Serial.print("Blue: "); Serial.println(blue,HEX);
  Serial.println();
  delay(2000);
}

This is the output I am getting
[     4][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz
Hello123
[    21][I][esp32-hal-i2c.c:75] i2cInit(): Initialising I2C Master: sda=21 scl=22 freq=100000

I am not getting any RGB value or the code is getting stuck in the init() method.
Can anyone guide me? What can be the problem? What is my mistake?

please remove the pictures of text ... replace them with the text ... format as code for readability ... that should stop the downvotes because your question will be readable by everyone, not just people with good eyesight

The code is a slightly instrumented stock example. If you want to be somewhat more certain where you're hanging it's best to .flush() after your got-here type messages. Otherwise you may successfully queue the message but hang before the message actually gets transmitted through hardware. There is at least small chance that showing your wiring would help. With reasonable assumptions about what you're not showing what you are showing looks fine. So, show more.

@jsotola you can click the image for bigger/more readable text. Still sucks compared to real text though...

@jsotola thank you for input. I have corrected the question.

@timemage I have rechecked the wiring and it's proper. otherwise it shouldn't show the address. I have connected the pins as follows GPIO21 (ESP32) -> SDA (ISL29125), GPIO22(ESP32) -> SCL (ISL29125). Supplying 3.3v and GND from ESP32.

@dandavis visually impaired people depend on screen readers to access the webpage content ... content of images cannot be read by the screen reader

@NikunjVadher i removed my downvote and upvoted your post for a well presented question

The library file "SparkFunISL29125.cpp" contains this: Wire.begin(); and I guess you want it to contain Wire.begin(21,22) from what you have said in a later comment.  Best would be to comment out Wire.begin(); in the library and put the corrected version in your sketch.
In such a situation I'd suggest  copying the .cpp and .h files of the library into the sketch folder. You also have to change this in the sketch: #include <SparkFunISL29125.h> to #include "SparkFunISL29125.h" to address the local copy.
Further, the schematic of the SparkFun ILS29125 breakout board shows that the on board I2C pullup resistors are connected via a solder jumper which by default is not bridged.
You appear to have done the I2C scan test with two other devices connected and may have "benefitted" from their I2C pullup resistors. If you did the live test with the ILS29125 alone, there may have been no I2C pullup resistors in the circuit.

"via a solder jumper which by default is not bridged" You can see the non-masked stub of copper running between the pads like you can see them leaving each pad to the left. If you play with brightness/contrast you will see the trace itself under the mask. Language in Sparkfun's hookup guide for the module confirms they are bridge by default; the pads are for reconnecting it really. I'm surprised supplying the pin numbers manually did anything because the output listing (and Wire/board variant source code) indicate that it is already using those pins Initialising I2C Master: sda=21 scl=22.

@timemage I've added the schematic which shows a default open solder jumper. Of course it is not impossible that that they have simply used the wrong footprint. The detail on the board picture is not really clear enough to come to any conclusion.  The symptoms, that is hanging, tends to indicate a pullup resistor problem. Maybe the OP comes back and says something more.

https://imgur.com/a/VxQZkk1 The left is a view of the Eagle brd file. The right is the original image just adjusted for contrast and brightness, rotated, mirrored (it's the bottom layer of the eagle file). Hookup guide says "If you want to disable the on-board 10kΩ I2C pullup resistors -- in case you want to use those built into your microcontroller or other external pull-ups -- simply cut the two traces between the three pads on the backside of the board. If you decide you want the pull-ups later, you can always solder the pads back together."

More for future readers than anything. The OP has already accepted. It's all stuff I researched before leaving the initial comment. That's why I find it surprising that that their issue is resolved. Anyway, perhaps they are as they appear in the schematic. But, I don't believe so. For what it's worth the UNO schematics also represent the cuttable RESET connection the same way as an open, even though it's closed on a shipped board.

@timemage It is certainly a mystery. It does appear from what you have found that simply a misleading symbol was used in the schematic. Maybe Eagle does not or did not have a normally closed solder jumper schematic symbol. So the board designer also works with an open jumper  then draws a track through it. Also plausible is that on the specific device used by the OP any closed solder jumpers had been already cut for reasons suggested in the guide you quoted. Unless the OP comes back we can only guess.


text:
Non-blocking analogRead for Arduino Nano 33 BLE sense
I need an alternative to analogRead() that doesn't block the processor. I've managed to find a lot of solutions for this for other boards, but not something that's compatible with nrf5240 like the one that's on Arduino Nano 33 BLE sense. Does something like this already exist? Would it be difficult to make?

It has mbed-os rtos, so you can do it in another thread. Or you can read nRF58240 Product specification and use EasyDMA (it has even sample rate, multiple channels setup, ..)


text:
very small PWM when timer says zero
I'am getting a little PWM signal when my potentiometer is at zero and OCR2B always reads zero on the serial monitor.  My LED has low forward voltage but I still get a little PWM on the pin when I prob it. I use timer 1 and it works good. I have a picture of the scope.

#include "RTClib.h"
RTC_DS3231 rtc;

#include <ResponsiveAnalogRead.h>
ResponsiveAnalogRead analog0(A0, true, .001);

unsigned int nowHour;

int analogOutPin3 = 3;
int sensorValueTimer2Pin3;

long z;

int analogOutPin9 = 9;
int analogOutPin10 = 10;

void setup() {
  Serial.begin(9600);
  //===============mode 5 pin 3,11==================//
  TCCR2A |= (1 << COM2A1);
  TCCR2A |= (1 << COM2B1);
  TCCR2A |= (1 << WGM21);
  TCCR2A |= (1 << WGM20);
  TCCR2B |= (1 << WGM22);
  TCCR2B |= (1 << CS22);
  OCR2A = 249;   //1KHz frequency
  TCNT2 = 0;
  //====================mode 5 pin 3,11==============//

  pinMode(3, OUTPUT);

  rtc.adjust(DateTime(2014, 1, 21, 7, 0, 0));
}

void loop() {
  DateTime now = rtc.now();
  nowHour = now.hour();
  analogWrite(9, LOW);
  analogWrite(10, LOW);
  analog0.update();
  sensorValueTimer2Pin3 = ((analog0.getValue() * 249L) / 1024);
  if (nowHour >= 7 && nowHour <= 21) {
    z = sensorValueTimer2Pin3;
    OCR2B = z;
    Serial.println(OCR2B);
  }
}

My mistake, it wasn't actually in mode 5, it was in fast PWM, I changed it to phase correct and that worked, it turns off.

"My LED has low forward voltage" - what does that have to do with PWM? Hope you're using a resistor for the led.

When analogWrite writes 0 or 255 value, it actually disables PWM output and sets the output to 0 or 1 correspondingly (maybe just one of them).
That's because there is just 256 values, but with both fully off and fully on PWM you'll need 257 values to archieve it.
If you're using direct access into OCRx, you have to make a choice if you want to have not fully on pwm or not fully off pwm (by setting polarity with COM2Xx)
Btw, you should clear TCCR2A/TCCR2B as all of the timers are configured by Arduino core to be running and prepared for the analogWrites...

Pretty sure the data sheets mention a spike when trying to attempt 0% or 100% PWM via Fast PWM mode. As per KIIV you should set the pin to High or Low for either extreme of PWM duty.


text:
How can I display text on OLED?
I'm trying to print the information, which is received from the other ESP32 by CAN transceiver, on an OLED. The CAN bus is working perfectly, as the 'HELLO WORLD' is already be received. But I can't print the received 'HELLO WORLD' on OLED (also the OLED is work). The code shows below,

#include <CAN.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void setup() {
  Serial.begin(115200);
  while (!Serial);

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  delay(2000);
  display.clearDisplay();
  display.setTextColor(WHITE);

  Serial.println("CAN Receiver");
  CAN.setPins(16, 17);
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }
}

void loop() {
  // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr()) {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    } else {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available()) {
        Serial.print((char)CAN.read());
      }
      Serial.println();
    }

    Serial.println();
  }
  delay(5000);

  display.clearDisplay();

  display.print((char)CAN.read());

  display.display();
}

To show code in your question, please edit your question, highlight the entire code segment, and click the '{}' button. It will be much easier for potential contributors to read it and answer your question.

please format your code ... use the {} button or put ``` before and after your code

Are we asking noah to fix his post formatting so he learns how to post a question the includes formatted code rather than editing his question and doing the formatting for him?

@DuncanC - noah is a "New contributor", so it's possible that one of our users was trying to be nice and help them out. Editing and improving Q+A's is encouraged by Stack Exchange, and there are 3 levels of "badges" awarded for editing them. Users with less than 1000 reputation are given 2 reputation for editing a question. I know of one Arduino SE user that has over 500 reputation and has never asked nor answered a single question. I agree with you about teaching, but I also have to "be nice", and lets not forget about those hardworking volunteers who edit questions to make our site better.

@VE7JRO, I was tempted to apply the edit myself, but didn't because I wondered if the "please code format your question" suggestions are "teach a user to post" moments. I'm fairly new on the Arduino site, but have a >100K rep on Stack Overflow, so pretty familiar with how Stack Exchange works.

Just guessing but looks to me like you read the CAN message and print it character by character to the Serial console but you don't save those characters in a buffer as you get them from CAN.read(). So when you then try to display.print((char)CAN.read()); at that point there are no more characters to available for the CAN.read() to read so nothing is printed by the display.print(). I'm just guessing though.

@RichardChambers Thanks mate! you save my life.

@RichardChambers Consider pasting your reply as an answer below, so it can be selected by Noah as the correct answer. For those sweet, sweet internet points ;) (and because then this question won't show up in the "unanswered" list)

@KenVanHoeylandt Thanks for the note. I just didn't think of it.

Just guessing but looks to me like you read the CAN message and print it character by character to the Serial console but you don't save those characters in a buffer as you get them from CAN.read().
So when you then try to display.print((char)CAN.read()); at that point there are no more characters to available for the CAN.read() to read so nothing is printed by the display.print().
So what you need to do is to read the characters into a buffer so that you save them after reading them so that you can use the text string for other purposes.


text:
How do I turn a number of pins to high and then off after 5 seconds based on a serial command
I have an Arduino sketch where I'm sending commands over serial, and as a result turning pins from low to high. What I'm looking to do is have those pins turn high for 5 seconds and then turn back to low. I was looking for a time or scheduling library for Arduino that allows multiple timers at once and lets you pass a parameter (at least I think that's what I need).
In other words, I would like to implement a "doAfter" method and pass the function it is calling a pin number.

Have you tried the delay() function? Try putting this in the loop() function for pin 3.
digitalWrite(3, HIGH);
delay(1000); // time in milliseconds as parameter
digitalWrite(3, LOW);

You can use the Timer library to achieve this:
#include "Timer.h"
[...]
digitalWrite(3, HIGH);
int afterEvent = t.after(5000, doAfter);
[...]
void doAfter() {
  digitalWrite(3, LOW);
}

As you can see, you cannot pass a parameter to the timer, just a callback. I suggest that you implement either a bunch of doAfter functions, from doAfter3 to doAfter9` for instance, and call the right one in the callback.
There are probably other timer libraries, but this one is simple and complete enough for your needs.


text:
PWM-FILTERS -DAC
I want to implement a digital controller C(z) on an Arduino Uno
(transfer function in the z domain) in order to control a plant
G(s) = 3750/[(s+10)(s+30)(s+100)].

I have implemented G(s) with electronics (op-amps, capacitors and
resistances). I want to realize C(z) on the Arduino Uno. The input to
the Arduino is the error signal (reference − output of G) and the
output of C(z) is the input of G(s). Finally, I will have a closed loop
system with negative unit feedback. The reference input is a unit step
signal (1 volt).
My problem is: how can I use PWM and filters in place of a DAC?

If you want to use PWM in place of a DAC, the normal thing to do is to
use some kind of analog low-pass filter. However, many people skip the
filter when the signal is meant for some system that inherently acts as
a low-pass. Example: dimming an LED, where the human eye is the filter.
In your case, since your plant looks like a third order low-pass filter
with cuts at 1.6, 4.8 and 16 Hz, you can probably skip the filter.
If you output on pins 5 or 6, the PWM frequency will be around
980 Hz
(exactly: fCPU/16384). At that frequency, your plant gain
relative to DC will be
G(j2π × 980 Hz) / G(0) ≈ 1.3 × 10−7 j
Probably low enough to not be an issue.

Generally have you  got any other information for this project;

No, and I guess you know the project better than I.

authors: Νίκος-Μάριος Κοκολάκης


text:
Why doesn't my 7 segment update every second like in the program?
I used sevseg.h library to write numbers to my 4 digit seven segment. The display should update every second with the current time since program started running. This is my code so far:
#include <SevSeg.h>

SevSeg sevseg;

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
}

void loop() {
    unsigned long timer = millis();
    for (int i = 0; i < 500; i++) {
        sevseg.setNumber(timer/1000, -1);
        sevseg.refreshDisplay();
        delay(2);
    }
}

Since the delay is 2, the for loop loops 500 times, resulting in 1000ms or 1 second. The current second is written to the display. For some reason, the display is updated every other 5 or 6 seconds. Why is this occurring? How can this be fixed so that my display turns into a stopwatch in a way?

This is the code that fixed the issue:
  #include <SevSeg.h>
  SevSeg sevseg;

  void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
  }

  void loop() {
    unsigned long timerGlobal = millis();
    sevseg.setNumber(timerGlobal/1000, -1);
    sevseg.refreshDisplay();
  }

In this, no delays are needed. millis is divided by 1000 and the integer second is drawn on the display. Proved to be much easier than I previously thought.

On SevSeg.h Arduino Page, It says:

Your program must run the refreshDisplay() function repeatedly to
  display the number.

I think that's the Problem. You are calling it just once and then your the number is changed.
Plus, you are saying it must get updated after One Second, but I think in your code, its being updated ever other 2 milisecond (WOW).
What I suggest is that you add a delay() for one second and then call sevseg.refreshDisplay(); several times in a for loop. You also need to change the way you measure no. of seconds elapsed.
i.e. try Something like this:
#include <SevSeg.h>
SevSeg sevseg;
void setup() {
  byte numDigits = 4;
  byte digitPins[] = {5, 4, 3, 2};
  byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
  sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
  sevseg.setBrightness(50);
  sevseg.setNumber(0000, -1);
}
unsigned long timerGlobal = millis();
void loop() {
  delay(1000);
  sevseg.setNumber( (timerGlobal - millis())/1000, -1)
  for (int i = 0; i < 50; i++) {
    sevseg.refreshDisplay();
  }
}

If my thinking is correct, the value of timer changes only when the void loop starts again, so even though the number gets set multiple times, it stays the same number. The refreshDisplay is also called 500 times a second since timer stays the same for a second. Adding large delays like 1000 doesn't work since it interrupts the constant refreshing of display. After running your code, I got - - - - showing on the display. After changing some code, the screen stays off for 1000ms and only stays on for a few ms.

well, I might be wrong since I haven't tested my code on Hardware. But, I think i would work. Can you try changing that 50 to some large number in for loop. That might help. Anyways. Sorry.

Using a delay is a terrible suggestion. From the SevSeg documentation: “any delays introduced by other functions will produce undesirable effects on the display”, which is quite obvious if you think about it.


text:
Code won't read the first line from SD
The general idea
I would like to target a link with certain parameters, which would trigger a force download of a txt file, to an SD card. Next, I'd like to loop through that file, and read one line at a time, doing something with each of the lines (storing in a variable, using it to send an SMS, etc). I'm using Arduino Uno + Ethernet shield.
Serverside script (PHP)
The serverscript does a DB query, and packs the results (first row/line in txt file - message text consisting of max 159 characters, all the other rows/lines - preformatted phone numbers, consisting of max 16 characters each) into a txt file. Newline and carriage returns for both the message and the phone numbers are added at the very end of, via
fwrite($txtFile,'+'.$cleanNum."\""."\r\n");

The plus sign and the escaped quote are there, because I'd like to have the numbers formatted like this
+389012345678"
because that prepares it for sending later on.
The Code
/*
 Circuit:
 Ethernet shield attached to pins 10, 11, 12, 13
 */

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <SD.h>

byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};
String msg ="";
String allTxt = "";
int counter = 0;
int testRead = 0;
int testmsg = 1;

char server[] = "myserver.dev";

IPAddress ip(192, 168, 1, 200);
EthernetClient client;

File file;

void setup() {
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  Serial.begin(9600);
  while (!Serial) {}

  if (!SD.begin(4)) {
    return;
  }

  if (Ethernet.begin(mac) == 0) {
      Ethernet.begin(mac, ip);
  }
  delay(1000);

  if (client.connect(server, 80)) {
    client.println("GET /dl.php?param=pass HTTP/1.1");
    client.println("Host: myserver.dev");
    client.println("Connection: close");
    client.println();
  }

  if(SD.exists("numbers.txt"))
    SD.remove("numbers.txt");

  file = SD.open("numbers.txt", FILE_WRITE);

  if (!file)
    while (1);
}

String readLine() {
  String received = "";
  char ch;
  while(file.available()){
    ch = file.read();
    if(ch == '\n') {
      return String(received);
    } else {
      received+=ch;
    }
  }
  return "";
}

void loop() {
  if (client.available()) {
    char c = client.read();
    allTxt += c;
    if(c == (char)13) {
      counter++;
      if(counter > 13) {
        for(int i = 0; i < allTxt.length()-1; i++) {
          file.print(allTxt[i]);
        }
      }
      allTxt = "";
    }
  }

  if (!client.connected()) {
    client.stop();
    file.close();
    if(testRead < 1) {
      testRead++;
      file = SD.open("numbers.txt", FILE_READ);
      if(file) {
        Serial.println("File opened!");
        while(file.available()) {
          if(testmsg==1){
            msg += readLine();
            Serial.println(msg);
            testmsg++;
          } else {
            Serial.println(readLine());
          }
        }
      }
      file.close();
    }
    Serial.println("**********************************");
    Serial.println("end");
    while(true);
  }
}

The Problem
Whenever the first row in the downloaded txt file has more than 110 characters, the code does not read it (although it IS present in the file). Since it's not being read, it's not being stored in the String msg variable.
Things tried
Breaking the message into two variables (on the server, inside the PHP script), via
$msgOne = substr($msg,0,floor(strlen($msg)/2)-1);
$msgTwo = substr($msg,floor(strlen($msg)/2)-1);

and then writing them as individual rows / lines of text into the txt file. The Arduino code is modified to include this change, with
msg += readLine();
msg += readLine();

This however, fills the msg variable with just the first part of the message.
Redeclaring msg as a chararray, and replacing msg+=readLine() with
readLine().toCharArray(msg,159);

also gave no results.
I have also tried replacing readLine() with Serial.println(file.read()), and everything is printed to Serial, so I'm guessing that something's wrong with my readLine() function. Maybe it (or Arduino itself) can't handle 159 characters in the first row.
Any help is appreciated.

Add code to check when String fails :)

The problem was in a newline character (I still haven't discovered where does it come from or why). I have resolved it by changing this part
    while(file.available()) {
      if(testmsg==1){
        msg += readLine();
        Serial.println(msg);
        testmsg++;
      } else {
        Serial.println(readLine());
      }
    }

into this
    while(file.available()) {
       while(testRead<3) {
        char c = file.read();
        if(c != '\n') {
          msg += c;
        } else {
          testRead++;
        }
      }
      Serial.println(readLine());
      }
    }


text:
MQTT Callback function don't called
I'm doing a device to recongnize NFC cards with an Arduino UNO, a CC3000 wifi shield, and a PN532 NFC shield. That's ok.
So, I created a sketch with this library: https://github.com/nathanchantrell/pubsubclient
I subscribed a topic /ocean/nfc/porta. When I publish a message to it, the callback function isn't called. Moreover, when it takes a card ID it publishs to a topic sometimes then don`t work more. How to solve it?
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>
#include <Adafruit_CC3000.h>
#include <cc3000_PubSubClient.h>

#define PN532_IRQ   (4)
#define PN532_RESET (3)  // Not connected by default on the NFC Shield

char cardID[ 16 ];

Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
// also change #define in Adafruit_PN532.cpp library file
   #define Serial SerialUSB
#endif

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   2  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  7
#define ADAFRUIT_CC3000_CS    10

// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "Ocean Convidado"
#define WLAN_PASS       "ocean2901"
//#define WLAN_SSID       "Ocean Lab"
//#define WLAN_PASS       "ocean3101"

// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

Adafruit_CC3000_Client client;

// We're going to set our broker IP and union it to something we can use
union ArrayToIp {
  byte array[4];
  uint32_t ip;
};

ArrayToIp server = { 25, 0, 25, 172 };

void callback (char* topic, byte* payload, unsigned int len) {

    Serial.println(F("CALLBACK"));
/*
    char payload_buffer[20];

    if (strcmp (topic,"/ocean/nfc/porta") == 0) {

        byteToChar(payload, payload_buffer, len);

        if (strcmp(payload_buffer, "permitir") == 0) {
          Serial.println(F("Abreeee!!!!!!"));
        } else {
          Serial.println(F("Não abre!!!!!!"));
        }

    }*/
}

cc3000_PubSubClient mqttclient(server.ip, 1883, callback, client, cc3000);

void setup(void) {

  #ifndef ESP8266
    while (!Serial); // for Leonardo/Micro/Zero
  #endif
  Serial.begin(115200);
  Serial.println(F("Hello OCEAN NFC Reader!"));

  Serial.println(F("Inicializando NFC Reader...."));

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print(F("Didn't find PN53x board"));
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print(F(".")); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println(F("Waiting for an ISO14443A Card ...\n\n"));

  Serial.println(F("Inicializando Wifi CC3000"));

  displayDriverMode();

  Serial.println(F("\nInicializando o CC3000 ..."));
  if (!cc3000.begin()) {
    Serial.println(F("Nao foi possivel inicializar o CC3000! Os cabos estao conectados corretamente?"));
    for(;;);
  }
  else {
    Serial.println(F("Carregou"));
  }

  uint16_t firmware = checkFirmwareVersion();
  if ((firmware != 0x113) && (firmware != 0x118)) {
    Serial.println(F("Versao do firmware errada!"));
    for(;;);
  }

  displayMACAddress();

  Serial.println(F("\nDeletando perfis de conexoes antigas"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Falhou!"));
    while(1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nTentando conectar-se a(o) ")); Serial.println(ssid);

  /* NOTE: Secure connections are not available in 'Tiny' mode! */
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Falhou!"));
    while(1);
  }

  Serial.println(F("Conectado!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Requisitando DHCP"));
  while (!cc3000.checkDHCP()) {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
  while (!displayConnectionDetails()) {
    delay(1000);
  }

   // connect to the broker
   if (!client.connected()) {
     client = cc3000.connectTCP(server.ip, 1883);
     Serial.println(F("Conectando em TCP"));
   }

   // did that last thing work? sweet, let's do something
   if(client.connected()) {
    if (mqttclient.connect("ArduinoUnoClient-CC3000-A2", "iotocean", "NZZOLd0O66oLS0vpajiA123")) {
      Serial.println(F("Publicando"));
      mqttclient.publish("/ocean/nfc/debug","A2 está online");
      mqttclient.subscribe("/ocean/nfc/porta");
    }
    else {
      Serial.println(F("Ouve um erro ao conectar-se ao broker"));
    }
   }

}

void loop(void) {

  delay(1000);

  Serial.println(F("Entrei no loop\n"));
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {
    // Display some basic information about the card
    Serial.println(F("Found an ISO14443A card"));
    Serial.print(F("  UID Length: "));Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print(F("  UID Value: "));
    nfc.PrintHex(uid, uidLength);

    if (uidLength == 4)
    {
      // We probably have a Mifare Classic card ...
      uint32_t cardid = uid[0];
      cardid <<= 8;
      cardid |= uid[1];
      cardid <<= 8;
      cardid |= uid[2];
      cardid <<= 8;
      cardid |= uid[3];
      Serial.print(F("Seems to be a Mifare Classic card #"));
      Serial.println(cardid);

          // Testa se ainda esta conectado
          if (!client.connected()) {
            Serial.println(F("!client.connected()"));
             client = cc3000.connectTCP(server.ip, 1883);

             if(client.connected()) {
               if (mqttclient.connect("ArduinoUnoClient-Office-A2")) {
                  mqttclient.publish("/ocean/nfc/debug","A2 está novamente online");
               }
             }
          } else {
            Serial.println(F("else !client.connected()"));
            // as per comment from LS_dev, platform is int 16bits
            sprintf(cardID,"%lu", cardid);

            mqttclient.publish("/ocean/nfc/id", cardID); delay(1000);
          }
          //delay(1000);

    }
    Serial.println(F(""));
  }

  Serial.println(F("Sai do loop\n"));
}

void displayDriverMode(void)
{
  #ifdef CC3000_TINY_DRIVER
    Serial.println(F("CC3000 is configure in 'Tiny' mode"));
  #else
    Serial.print(F("RX Buffer : "));
    Serial.print(CC3000_RX_BUFFER_SIZE);
    Serial.println(F(" bytes"));
    Serial.print(F("TX Buffer : "));
    Serial.print(CC3000_TX_BUFFER_SIZE);
    Serial.println(F(" bytes"));
  #endif
}

void charToByte(char* chars, byte* bytes, unsigned int count){
    for(unsigned int i = 0; i < count; i++)
      bytes[i] = (byte)chars[i];
}

void byteToChar(byte* bytes, char* chars, unsigned int count){
    for(unsigned int i = 0; i < count; i++)
       chars[i] = (char)bytes[i];
}

uint16_t checkFirmwareVersion(void)
{
  uint8_t major, minor;
  uint16_t version;

#ifndef CC3000_TINY_DRIVER
  if(!cc3000.getFirmwareVersion(&major, &minor))
  {
    Serial.println(F("Unable to retrieve the firmware version!\r\n"));
    version = 0;
  }
  else
  {
    Serial.print(F("Firmware V. : "));
    Serial.print(major); Serial.print(F(".")); Serial.println(minor);
    version = major; version <<= 8; version |= minor;
  }
#endif
  return version;
}

/**************************************************************************/
/*!
    @brief  Tries to read the 6-byte MAC address of the CC3000 module
*/
/**************************************************************************/
void displayMACAddress(void)
{
  uint8_t macAddress[6];

  if(!cc3000.getMacAddress(macAddress))
  {
    Serial.println(F("Unable to retrieve MAC Address!\r\n"));
  }
  else
  {
    Serial.print(F("MAC Address : "));
    cc3000.printHex((byte*)&macAddress, 6);
  }
}

/**************************************************************************/
/*!
    @brief  Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

Output of Arduino IDE:

O sketch usa 28.438 bytes (88%) de espaço de armazenamento para
  programas. O máximo são 32.256 bytes. Variáveis globais usam 1.546
  bytes (75%) de memória dinâmica, deixando 502 bytes para variáveis
  locais. O máximo são 2.048 bytes. Pouca memória disponível, problemas
  de estabilidade podem ocorrer.

I don't see any attempts to publish to /ocean/nfc/porta in your code. You are publishing from another node? Your broker is local? Post everything you get in the serial monitor.

I solved the problem. There is a bug on CC3000, so need to use WatchDog to reset for each while.


text:
DMX dimmer appears to receive data from Arduino but connected lights do not respond
I'm trying to control a DMX dimmer (eurolite ES-12 IEC DMX Switchback) through an Arduino Mega. In an earlier test, we were able to make one RGB DMX light run through the color spectrum. Now, a technician has installed this ES-12 dimmer pack with 12 1-channel DMX lights attached to it. The dimmer has some kind of built-in testing program and all the lights work.
The documentation on the dimmer is very sparse regarding the programming side of things. The dimmer is set to mode d--- and when the Arduino is running its program, a little green light flickers next to the d---, apparently responding to the signals it's receiving, like so: d---. Unfortunately, that the only light that responds.
I've tried using the DMXSimple library (the DMX is connected to pin 3), but even the example code (after correcting the brightness-- to ++) does not get any response -- none at all, not even the little green light. The only thing the little green light responds to is an analogWrite() on pin 3.
I'm guessing it's an addressing issue, but I don't know enough to fix it. As I understand it, the dimmer is seen as the controller and is sent a LOW on channel 0 as the Start Code (SC): http://www.dmx512-online.com/packt.html. The first light on the dimmer will then be channel 1, the second light channel 2, etc. (since, the technician tells me, they are 1-channel lights). Is this correct? Or is the dimmer its own universe that should be addressed in some other way?

I'm assuming the same DMX connector we used to run the tests on the RGB lights. I can't tell you the make and model, but the guy in charge of the hardware does this kind of thing for a living. Unfortunately, he's on vacation and he's built everything into a black box -- literally. I just do the software.

@Dan Nixon, I'll see if we can open the black box.

The light technician, Toby Peperkamp, came with the solution. I'm not sure exactly where he found the information, but apparently the protocol for non-RGB DMX lights requires that the lights be switched on to maximum (255) at the beginning of the connection. So I added that to the setUp() and all the lights started to respond.


text:
Working on a reaction test for the Arduino Uno using an led and an lcd shield
The situation involves some Asm inline practice and a basic circuit. The program turns an LED on after a somewhat random period of time then waits until the button is pressed to report back how many milliseconds it took. This is then printed by the LCD shield. My confusion occurs because after each reset it prints a 1 before the button is pressed, which overlaps returned millisecond value on the screen giving me some false data. I tried to cut the code down so if there is anything else that might be helpful let me know. I think the issue may be in the test reaction time function but am not sure.
/* --------------------------------------------------------------------------------------
  Includes
--------------------------------------------------------------------------------------*/
#include <LiquidCrystal.h>   // include LCD library

/*--------------------------------------------------------------------------------------
  Init the LCD library with the LCD pins to be used
--------------------------------------------------------------------------------------*/
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
/*--------------------------------------------------------------------------------------
  setup()
  Called by the Arduino framework once, before the main loop begins
--------------------------------------------------------------------------------------*/

void setup()
{
   //button adc input
   pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
   digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
   //lcd backlight control
   digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is high (on)
   pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
   pinMode(3,OUTPUT);                         //d4 is are LED
   //set up the LCD number of columns and rows:
   lcd.begin( 16, 2 );
   //Print some initial text to the LCD.
   lcd.setCursor( 0, 0 );   //top left
   //          1234567890123456
   lcd.print( "LinkSprite  16x2" );
   //
   lcd.setCursor( 0, 1 );   //bottom left
   //          1234567890123456
  // lcd.print( "Btn:" );

    Serial.begin(9600);

 pinMode(2, INPUT);

 }
/*--------------------------------------------------------------------------------------
  loop()
  Arduino main loop
--------------------------------------------------------------------------------------*/
void loop()
{

      //read the button
     byte result;//  = digitalRead(2);
      asm volatile(
          "ldi %0, 0 \n\t"
          "sbic 0x09, 2 \n\t"
          "ldi %0,1 \n\t"
          "nop \n\t"
          :"=r" (result)
          :
          :
      );
      int t =(random(0, 10000)+1000);
      unsigned long currentM = millis();
      //int t =(random(0, 10000)+1000 +millis());
      while( t < currentM){
      int x = testReactionTime();
       lcd.setCursor( 0, 1 );
     //if (result){
         lcd.print( "on " );
         lcd.setCursor(7,1);
         lcd.print(" ");
         //int x = testReactionTime();
         lcd.print(x,DEC);
         //delay(1000);
         //lcd.print("     ");
      //}else{
        //testReactionTime();
        // delay(random(0, 1000)+1000);
        //lcd.print( x,DEC );
        //digitalWrite(3, LOW);
      }
//}
}

/*
 *  after a random delay call this function to measure their reaction
 *  time in milliseconds
 *  It will immediately turn on a LED (pin 3)
 *  And then start timing the milliseconds until they hit the button (pin 2)
 *
 */
int testReactionTime()
{
  int answer;
  //delay(rand());
  asm volatile(
    "ldi %A0, 0 \n\t"  // initializw anwer to 0
    "ldi %B0, 0 \n\t"  // answer should be the number of ms until they hit the button
    "sbi 0x0b,3 \n\t"  //turn on the led pin 3
    "ldi r16, 1 \n\t"
    "ldi r17,0 \n\t"
    "movw r26, %0 \n\t"
    "rcall killms%= \n\t"
   "cbi 0x0b,3 \n\t"  //turn on the led pin 3

      "rjmp end%= \n\t" //skip over the routine
      //start of kill millesecond subrouting, need to waste ~16000 clock cycles
      "killms%=:ldi r24, 0x90 \n\t"  //lo8(3984)
      "ldi 25, 0x0f  \n\t"      //hi8(3984)
      "kloop%=: sbiw r24, 1 \n\t"   //2 clocks
       "brne kloop%=   \n\t"       //2 clocks since most times true!!
       "add r26, r16 \n\t"
       "adc r26, r17 \n\t"
       "movw %0, r26 \n\t"
       "sbis 0x09, 2 \n\t"
       "ret       \n\t"
       "rcall killms%= \n\t"
      //end of the kill millesecond loop
      "end%=: nop \n\t"
    :"=r" (answer)
    :
    :"r24", "r25"
    );

  return answer;
}

Looks to me like killms is calling itself recursively every millisecond. Your are going to quickly overflow your stack.

Expanding on my comment... I see a few issues in your asm code, not all
as serious as the first one:

killms is calling itself recursively indefinitely, which should
overflow your stack. The last rcall killms%= should probably be an
rjmp.
There is no need to move the answer around between register pairs.
Just use the compiler-allocated registers instead of r17:r16.
By adc r26, r17, you probably mean adc r27, r17.
Instead of add and adc, you could just adiw, which saves a
register pair.

Below is my version of testReactionTime(). I tested it on an Uno (with
Serial instead of an LCD) and it works fine. The assumptions on the
hardware are:

The LED is on pin 13 (PB5): it's the built-in LED.
The button is on pin 2 (PD2), which goes HIGH when the button is pressed.

/*
 * After a random delay, call this function to measure the reaction time
 * in milliseconds. It will immediately turn the built-in LED and then
 * start timing the milliseconds until the user hits the button (pin 2
 * going HIGH).
 */
int testReactionTime()
{
    int result, counter;
    asm volatile(
        "    clr %A[result]                      \n" // clear result
        "    clr %B[result]                      \n" // ditto
        "    sbi %[led_port], %[led_bit]         \n" // LED on

        // delay to make the loop 0 last exactly one millisecond
        "0:  ldi %A[counter], lo8(%[iterations]) \n"
        "    ldi %B[counter], hi8(%[iterations]) \n"
        "1:  sbiw %[counter], 1                  \n"
        "    brne 1b                             \n"
        "    nop                                 \n"

        "    sbic %[button_pin], %[button_bit]   \n" // unless button up:
        "    rjmp 2f                             \n" //     we are done
        "    adiw %[result], 1                   \n" // increment result
        "    rjmp 0b                             \n" // loop back
        "2:  cbi %[led_port], %[led_bit]         \n" // done: LED off

        : [result]     "=w" (result)
        , [counter]    "=w" (counter)
        : [led_port]   "I"  (_SFR_IO_ADDR(PORTB))  // LED on PB5
        , [led_bit]    "I"  (5)
        , [button_pin] "I"  (_SFR_IO_ADDR(PIND))   // button on PD2
        , [button_bit] "I"  (2)
        , [iterations] "i"  ((16000 - 8) / 4)
    );
    return result;
}

Thank you for the answer I did end up axing the recursion and going about it using a loop but this is very through and I like this way better than mine.

@SamKemp: In principle you can recurse in assembly, but 1) you have to make sure you ret as many times as you rcall, which seems to not be the case in your original code. 2) You must be aware that the Uno has only 2 KiB of RAM, which means you cannot recurse very deep before smashing the stack against the heap (or the BSS if you have no heap). Oh, BTW, you probably want to turn interrupts off in the timing routine.


text:
Arduino + UltraSensor - Serial Monitor outputs garbage
I am trying to connect an HC-SR04 to an Arduino Uno. For some reason when I run this code on the serial monitor it outputs wingdings in a straight line.
ýòøÿüÿøÿüòý÷ÿ÷ýÿÿúýÿýúÿòý÷ûòûòû÷ýÿøÿøÿÿ÷øÿüÿýÿþòøòÿÿøûüÿøÿÿòÿ÷ûòûòý÷ûòûòûöû÷ÿûû÷øÿÿ÷øÿüÿýÿüÿûöþÿý÷ûòûòûòûöûûûûûò
No breaks. Sometimes when I hit "Tools/Fix Encoding and Reload" it outputs
Ping: 0 cm
Ping: 0 cm
Ping: 0 cm
followed by more wingdings.
I've looked up some similar problems and it was usually fixed by changing baud to a lower value, 9600. I've done this and I still have problems.
Would you be able to help me out? I'd very much appreciate it.
const int trigpin = 9;
const int echopin = 10;
long duration;
int distance;

void setup() {
  Serial.begin(9600);
}

void loop() {
  pinMode(trigpin, OUTPUT);
  pinMode(echopin, INPUT);
  digitalWrite(trigpin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(trigpin,LOW);
  duration = pulseIn(echopin,HIGH);
  distance = duration *0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
}

Updated Solution
After testing out Joel's code to check the sensor was in order, I found some new sample code which worked to display the distance in inches of a HC SR04 sensor.
  // set up variables

  int trigpin = 13; // Trig Pin is connected to Arduino pin 13
  int echopin = 11; // Echo Pin is connected to Arduino pin 11

 // now we need variables which we will be measuring

 float pingtime; // Time for ping to travel to target and return
 float targetdistance; // Distance from sensor to target
 float speedofsound = 776.5; // speed of sound in miles per hour at 77 F

void setup() {
Serial.begin(9600); // Turn on serial port
pinMode(trigpin, OUTPUT); // Sensor trig pin is output
pinMode(echopin, INPUT); // input is reading from echopin

 }

void loop() {
digitalWrite(trigpin, LOW);// set trigger pin low
delayMicroseconds(2000); // pause to let signal settle
digitalWrite(trigpin, HIGH); // set trigger pin high
delayMicroseconds(15); // pause in high state, make sure sensor reads
digitalWrite(trigpin, LOW); // bring trigpin back low

   pingtime = pulseIn(echopin, HIGH);

// sensor will be sending HIGH pulse, measure pingtime at echopin
// ping time is in microseconds

  pingtime = pingtime / 1000000.;

// converts pingtime to seconds because speed of sound is miles per hour

  pingtime = pingtime / 3600.;
  // converts pingtime to hours
  // add a period to make float to avoid int mistakes

  targetdistance = speedofsound * pingtime;
  // calculates distance in miles traveled by ping

  targetdistance = targetdistance / 2;
  // accounts for roundtrip of ping to target

  targetdistance = targetdistance * 63360.;
  // convert target distance to inches
  // 63360 inches in a mile

Serial.print("The distance to the target is:");
Serial.print(targetdistance);
Serial.println("inches");
delay(1000);

 }

since it seems that the problem did have to do with the serial monitor settings, can you please select my answer as correct.

Check your serial monitor baud rate. This is definitely caused by your serial monitor being set to a different baud rate than the 9600 you specified in the program.
If it had anything to do with the sensor than this line would be printed properly Serial.print("Distance: ");
Once you change the serial monitor baud rate then try running this program, to verify that it is set properly:
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Hi There!");
}

If that prints "Hi There!" then the program your serial monitor is set up properly.

I tested your code and I get an infinite loop of "Hi There"s which I will take as a good sign. :D

@AngelaAlbrecht that is a good sign, try your original code again without changing any settings and see if it prints "Distance: "


text:
Help combining code
Can someone please help me fix my code?
Basically, a user inputs values that determine how many beeps will play from a breadboard-compatible speaker, and right after the beeps are played, a motor (connected to the breadboard)  is supposed to turn.
The beep-code is mine, and I got the motor code from the Arduino website. Anyway, SEPARATELY the codes work - the beeps play from the speaker, the motor turns fine. However, the codes don't work when I combine them (beeps play, but motor does not run after beeps are played), and I have no idea how to fix it. Any help is appreciated. Thanks so much.
int pin = 3;
#include <Stepper.h>

void setup() {
  Serial.begin(9600);
}

void loop() {
  int bpmeasure, measurespg, bpminute;
  Serial.println("Enter number of beats per measure:");
  while (Serial.available() == 0) {};
  bpmeasure = Serial.parseInt();
  Serial.println(bpmeasure);
  Serial.println("Enter number of measures on page:");
  while (Serial.available() == 0) {};
  measurespg = Serial.parseInt();
  Serial.println(measurespg);
  Serial.println("Enter tempo:");
  while (Serial.available() == 0) {};
  bpminute = Serial.parseInt();
  Serial.println(bpminute);
  float tppg = (bpmeasure * measurespg * 60000.0) / bpminute;
  // time it takes to play a page, in milliseconds
  float tpbeat = tppg / (bpmeasure * measurespg);
  // time between each individual note, in milliseconds
  float t = 0.0;
  for (float t = 0.0; t <= tppg ; t += tpbeat) {
    tone (pin, 30, 50);
    delay (tpbeat+50);
  }
  // speaker is supposed to beep every 'tpbeat' amount of milliseconds,
  // until it reaches 'tppg' milliseconds and then speaker should stop beeping
  const int stepsPerRevolution = 900;
  Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
  int stepCount = 0;
  // number of steps the motor has taken
  if (stepCount = 0) {
    // read the sensor value:
    int sensorReading = analogRead(A0);
    // map it to a range from 0 to 100:
    int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
    // set the motor speed:
    if (motorSpeed > 0) {
      myStepper.setSpeed(motorSpeed);
      // step 1/100 of a revolution:
      myStepper.step(stepsPerRevolution / 100);
    }
  }
}

Not very clear what you want to do... Do you want the board to stay still until you write through serial, then play the beats, then when they finish run the motor? And until when should it rotate? Anyway try to implement it yourself, then see what is wrong and come back asking "I did this, I expected that but got this other thing. Why?"

Right now I'm not worrying about making the motor stop rotating, I just want it to do so after the beats are played

Yes, but if you do not stop the motor and return to the initial idle state you will have to reset or turn off/on the arduino to enter the wait state again.. but if you don't care, what did you try? because in my opinion just copy-pasting the two programs one after the other and joining the loops will do that..

I am aware I have to reset the arduino. I did just copy and paste the 2 programs into the same loop, and it didn't work. I don't know what I'm doing wrong ;-;

Ok, now that you joined them you are ready for the second step, which is "see what is wrong and come back asking "I did this, I expected that but got this other thing. Why?"". Which means, post the complete code, your expectations and your actual results...

Okay, post is edited

just for the future: it is usually better not to delete previous content, but rather add it at the bottom. Anyway you say that the motor does not start. But does it stop playing the tone?

You have to make the code non-blocking otherwise the motor control will not work.

what part is blocking? and how do i make it nonblocking?

and yes, it stops playing the tone

I don't see where the motor pin is used.  it is defined at the top but not referenced in the code.

The first step with combining any programs together is to forget about combining programs together. Instead you need to do something completely different.
Analyse the existing programs individually. Work out and learn exactly how they work and how they do what they do.
Then think about your program. What do you actually want it to do, and how does that relate to the things the other programs did.
Then, finally, using what you learned from analysing the other programs, you write your own new program that does what you want it to do.
Yes, there may be a certain amount of copy-and-paste from the old programs to the new, but until you have taken the time to learn how the old programs work you won't have a clue which parts of them you may want to copy-and-paste, and which you may want to use as inspiration for writing new portions of code.


text:
Need help with programing the LCD for my project
I am trying to make a digital die for my project at school. I am having trouble with the programming. I don't really know how to write code and I am not a programmer.
I took inspiration from a post on the Arduino website (https://projecthub.arduino.cc/tylerpeppy/arduino-digital-dice-4d7e2e) where someone already made the project that I'm trying to make.
In the code I need it to roll or randomly generate numbers from 1 to 12. If possible I would like to make it so that it has different modes, where for example if I pressed the button twice it would change the mode to generate numbers from 1 to 6.
THE PROBLEM I'M HAVING:
When I upload the code to my Arduino it says "Digital", then immediately switches to saying "Rolling" and it stays on the word Rolling and doesn't say anything else until I press the button (then the whole thing starts over again).
NOTE: the right half of the display is blank due to hardware failure
So my  question is how do I fix it so that it gives me results of the dice roll?
Here are the schematics and some pictures;

This the code that I used for the programing:
include <LiquidCrystal.h>
long randNumber;

int Led = 13; //define LED port
int Shock = 2; //define shock port
int val;//define digital variable val

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12 );

byte customChar[] = {
  B00000,
  B00000,
  B11111,
  B11001,
  B10101,
  B10011,
  B11111,
  B00000
};

void setup()
{
  lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.home();

  pinMode(Led, OUTPUT); //define LED as a output port

  randomSeed(analogRead(0));

  pinMode(Shock, INPUT); //define shock sensor as a output port

  lcd.write(byte( 0));
  lcd.print("Digital dice");
  lcd.write(byte( 0));
  delay(1000);
}

void loop()
{
  val = digitalRead(Shock); //read the value of the digital interface 3 assigned to val
  if (val == LOW) //when the shock sensor have signal do the following
  {
    lcd.clear();
    lcd.print("Rolling dice...");
    delay(4000);

    lcd.clear();
    lcd.setCursor(0, 0);

    randNumber = random(1,7);

    lcd.print("Dice 1 = ");
    lcd.print(randNumber);
    lcd.setCursor(0, 1);

    randNumber = random(1,7);

    lcd.print("Dice 2 = ");
    lcd.print(randNumber);
  }
  delay(150);
}

I appreciate anyone that wants to help in any way!

you're trying to see something that lasts only a few milliseconds ... think about why you can see Rolling

ahh I see so the delay line in code is the one that tells you how long something is displayed?

in this program, yes ... the delay instruction actually stops the program ... that is why its use is not desired when the program should be responsive to inputs

the microcontroller is a very stupid machine, it can only do exactly what you tell it to do ... that is why you have to be aware what you are telling it to do at all times

I can see that now yes. Ive been playing around with it for a bit and I understand its way of working a bit better now.... thank you @jsotola I am really thankful and I really appreciate your help and patience with me

I hate when people say that delay "stops the program".  That leads to the types of misconceptions that make understanding non-blocking code harder.  The delay function doesn't "stop" the program.  It IS the program.  The program is running line by line just like any program does.  And each line does its own thing one at a time.  It's just that the delay line takes a really long time to finish and move to the next line.  The program is running.  It's just running that one line for a long time.

Understanding that helps I think to understand that non-blocking code isn't actually doing two things at once.  It's just not stopping on any one line to wait so that all of those lines get to run at least once in some very short period.

@Delta_G you are correct in your thinking ... the wait instruction loops inside itself, while counting interrupts until the requested time interval has passed ... to a an outside observer, the program stops running

I suggest you print the number on serial monitor. This will help the debugging process.

A delay() call favors one part of the sketch, or one part of it at a time, keeping others from executing. Generally we're trying to keep several rather slow (typically external) things happening at once, or at least tested often enough to service them as quickly as they need to be. To do that, we have to test whether each of those things needs to be started/stopped/adjusted, and do that really often and be really quick about it, until/unless we find one that needs some attention. Even then, we do whatever it needs, quickly!, and get back to testing the rest of our things.
A 'thing', in this case, means turning an LED on or off, writing a message or blanking an LCD display, starting or stopping a motor, etc.
Writing your sketch that way is called non-blocking programming. We don't let the processor be idle while some external thing is happening; we come back and check it again later (maybe only a few milliseconds later, but later).
Have a look at this earlier article of mine about non-blocking programming, then come back and read this answer again. That should give you a pretty good idea of how your sketch will need to work to do what you want it to do, and how to write one that does.


text:
How can I make an AC analog voltage with Arduino?
I am trying to create an AC voltage in Arduino. Until now I have only managed to get a square wave. How can this be achieved with Arduino?
If I try:
int up;
int down;
int out = 11;

void setup() {
  pinMode(out, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  for (up = 0; up <= 255; up++) {
    analogWrite(out, up);
    delay(1);
  }
  for (down = 255; down >= 0; down--) {
    analogWrite(out, down);
    delay(1);
  }
}

is it still pulsed DC?

What kind of frequency are you looking for? Do you want a sinewave, triangle wave, saw-tooth wave ... ?

just use an opamp to turn your square wave into a sine wave with a few caps and resistors

You have a few options:

Use a low-pass filter to round the square wave's edges some so they look more AC-ish.
Use a low-pass filter and have your code create steps of voltage that look AC-ish by varying the PWM widths.
Use an external SPI DAC chip that you can control with more discrete levels to make smoother looking AC.
Look into Direct Digital Synthesis (DDC) to learn more. Google "analog via ddS", lots of hits.


text:
Turn on each of the LEDs in order, by setting the cycle delay to 100 milliseconds
I have a tutorial to finish and I don't know the code I have to use to make all (4 LEDs) to turn on in order. So this is my code and my simulation. Thanks in advance!

My Code:
void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
  delay(100); // Wait for 100 millisecond(s)

  digitalWrite(13, LOW);
  digitalWrite(12, LOW);
  digitalWrite(9, LOW);
  digitalWrite(6, LOW);
  delay(100); // Wait for 100 millisecond(s)
}

EDITED:
I have to follow this one. I guess my simulator is correct.

you have the LEDs  really connected like on your fritzing schema? 5V to 5V pin

That wiring diagram (I refuse to call those things schematics) makes no sense to me at all. You have two LEDs in parallel, in series with two resistors that are also in parallel, and that chain is connected to two IO pins in parallel. And then you have it duplicated. The best you could hope for is turning on the LEDs in pairs. At worst, you will break the Arduino.

@Majenko, they are not in parallel. only the black wire is connected to 5V instead of ground (and uses red rail on the breadboard).

@Juraj You forget the metal strips in the breadboard... those LEDs are in parallel pairs, and the resistors are in parallel pairs.

@Majenko, true, Sorry, I am confused by this ugly fritzing

@Juraj Yeah. It's a ghastly toy but Arduino users seem to like it...

@Majenko I have edited my post. as you can see, that is the figure that I need to make.

I have a tutorial to finish ... did you do the tutorials that came before this? ... it appears that there is something that you did not understand about those tutorials ... you really need to identify what you do not understand, because it will affect your ability to write programs in the future

I see in your second diagram that you are controlling the ground side of the LEDs. digitalWrite(PinNumber, HIGH) will turn an LED OFF, digitalWrite(PinNumber, LOW) will turn an LED ON. Using delay() in a sketch should be avoided.
void setup(){
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
}

void loop(){
  digitalWrite(13, LOW);
  delay(100);
  digitalWrite(12, LOW);
  delay(100);
  digitalWrite(9, LOW);
  delay(100);
  digitalWrite(6, LOW);
  delay(100);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
  delay(100);
}

Your code switches them all ON and OFF simultaneously.
What I read from your question is you want to turn them on in order.
In this case, use a simple state diagram. This means you have to create variable (preferably an enumeration), e.g.:
enum EState { FIRST_ON, SECOND_ON, THIRD_ON, FOURTH_ON };

EState _state;

You can better use better names than FIRST_ON, ..., but I do not know what your lights mean.
In the setup, you initialize _state, e.g.
_state = FIRST_ON;

Than in the loop you check and change the state:
switch (_state)
{
case FIRST_ON:
    digitalWrite(13, HIGH); // Assuming this is the first light
    digitalWrite(12, LOW); // Put the others off
    ...
    ...
    _state = SECOND_ON; // Set the next state
    break;

case SECOND_ON:
    digitalWrite(13, LOW); // Assuming this is the first light
    digitalWrite(12, HIGH); // Put the second LED on
    .. // Put the third/fourth off
    _state = THIRD_ON; // Set the next state
    break;

    // Do the same for THIRD_ON and FOURTH_ON

default: // in all other cases
     break; // Should not happen
}

delay(100: // Wait for 100 milliseconds

Note, to not complicate the example, I've written out (mostly) the lines like you:
digitalWrite(13, HIGH);
digitalWrite(12, HIGH);
digitalWrite(9, HIGH);
digitalWrite(6, HIGH);

However, since these are almost copies (4 in the state diagram), it is best to write a separate function:
void SwitchLedsOn(int led1State, int led2State, int led3State, int led4State)
{
  digitalWrite(13, led1State);
  digitalWrite(12, led2State);
  digitalWrite(9, led3State);
  digitalWrite(6, led4State);
}

Now you can use in the first state case:
case FIRST_ON:
    SwitchLedsOn(HIGH, LOW, LOW, LOW); // Switch only first on
    break;

And do similar with the other states.

really? a state machine for this beginer? http://www.smart-jokes.org/programmer-evolution.html

are you sure that is for beginner cause my subject is something like beginner for arduino

It's not for beginner's true. However, the concept is so useful, that even for beginner's it is good to know it exists. Maybe they can read this answer at a later stage.

add this to loop() end
 digitalWrite(13, HIGH);
 delay(100);
 digitalWrite(12, HIGH);
 delay(100);
 digitalWrite(9, HIGH);
 delay(100);


text:
How to control DC motor speed with L298N and Node MCU?
I want to control an RC car with a joystick in mobile. Currently, I can only make the motor move forward and backward but not able to control the speed. Node mcu is used as a processor to receive the message.
Here is the code below:-

#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
#include <L298N.h>

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

const char * pubkey = "";
const char * subkey = "";

const char * subchannel = "base";

#define ENB D6
#define IN1 D3
#define IN2 D4

L298N motorL(ENB, IN1, IN2);

#define ENA D5
#define IN3 D1
#define IN4 D7

L298N motorR(ENA, IN3, IN4);

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(115200);

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);

}

void loop() {

  int tim = millis();

    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    if (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);

            String X = getStringPartByNr(msg, ':', 0);
            String Y = getStringPartByNr(msg, ':', 1);

            X.remove(0,1);

            int Xcord = X.toInt();
            int Ycord = Y.toInt();

            Serial.print("X: "); Serial.println(Xcord);
            Serial.print("Y: "); Serial.println(Ycord);

            int angle;
            int throttle = (Xcord + Ycord)/2;

            if ((Xcord > 100) && (Ycord > 100)) {
              angle = round(atan2(Ycord-100,Xcord-100)*(180/3.14));
              motorR.forward();
              motorL.forward();
              motorR.setSpeed(abs(int(throttle*sin(angle))));
              motorL.setSpeed(throttle);
              Serial.print("R speed: "); Serial.println(abs(int(throttle*sin(angle))));
              Serial.print("L speed: "); Serial.println(throttle);
              //motorR.forward();
              //motorL.forward();
            }
            else if ((Xcord < 100) && (Ycord > 100)) {
              angle = 180 - round(atan2(Ycord-100,100-Xcord)*(180/3.14));

              motorR.setSpeed(throttle);
              motorL.setSpeed(abs(int(throttle*sin(angle))));
              Serial.print("R speed: "); Serial.println(throttle);
              Serial.print("L speed: "); Serial.println(abs(int(throttle*sin(angle))));
              motorR.forward();
              motorL.forward();
            }
            else if ((Xcord < 100) && (Ycord < 100)) {
              angle = 180 + round(atan2(100-Ycord,100-Xcord)*(180/3.14));

              motorR.setSpeed(200-throttle);
              motorL.setSpeed(abs(int((200-throttle)*sin(angle)*(-1))));
              Serial.print("R speed: "); Serial.println(200-throttle);
              Serial.print("L speed: "); Serial.println(abs(int((200-throttle)*sin(angle)*(-1))));
              motorR.backward();
              motorL.backward();
            }
            else if ((Xcord > 100) && (Ycord < 100)) {
              angle = 270 + round(atan2(Xcord-100,100-Ycord)*(180/3.14));
              motorR.setSpeed(abs(int((200-throttle)*sin(angle)*(-1))));
              motorL.setSpeed(200-throttle);
              Serial.print("R speed: "); Serial.println(abs(int((200-throttle)*sin(angle)*(-1))));
              Serial.print("L speed: "); Serial.println(200-throttle);
              motorR.backward();
              motorL.backward();
            }

            Serial.print("Angle: "); Serial.println(angle);
            //Serial.print("time: "); Serial.println(tim);

        }
    }

    sclient->stop();

}

String getStringPartByNr(String data, char separator, int index)
{
    // splitting a string and return the part nr index
    // split by separator

    int stringData = 0;        //variable to count data part nr
    String dataPart = "";      //variable to hole the return text

    for(int i = 0; i<data.length()-1; i++) {    //Walk through the text one letter at a time

      if(data[i]==separator) {
        //Count the number of times separator character appears in the text
        stringData++;

      }else if(stringData==index) {
        //get the text when separator is the rignt one
        dataPart.concat(data[i]);

      }else if(stringData>index) {
        //return text and stop if the next separator appears - to save CPU-time
        return dataPart;
        break;

      }

    }
    //return text if this is the last part
    return dataPart;
}

Port Reading:-

What can the problem be?

NodeMCU's PWM ranges from 0-1024 I believe. Not just 0-255. Also, make sure the pin is PWM capable. And try a minimal sketch like: motorL.speed(1000); motorR.speed(500); motorR.forward(); motorL.forward();

thanks will try it

That's  because the l298n library are used for the arduino or other microcontroller that have hardware PWM in their systems. The library using hardware pwm by generating pulses and make variations of the cyclic rapport aka "alpha" .
Esp8266 have no pwm in their systems
So try to use software pwm library for the esp8266

this is the link. https://www.arduinolibraries.info/libraries/soft-pwm

Also don't include that library and try to make it work using easy lines of codes.

u mean controlling pwm using duty cycles or analogWrite?