text:
How to build image with ultrasound sensors HC-SR04
There is a simple algorithm on Wikipedia: how to build ultrasound image. And I want to build one. Resolution and presision are of no importance, I just want to do this for the case of study - I want to make such an "image 1D+depth slice" of a 20m^2 room. So I may just use these low frequency sensors - 1cm is enough.
So, as stated in the article, I need a phased array (to direct wave). And accidentally I have a couple of Arduino sensors HC-SR04:

Everyone uses them, but I stumbled how to use them. Interface seems to be totally weird, insuffient and unusable. Despite there are (visually) so many logic ICs soldered on the back.. So why is it designed so poorly and how to fix that?
Could you help me - where and what would you solder/desolder to use it for ultrasound imaging? I think that sensors itself could suit for this task.
PS. Basically I need to measure echoes delay (for depth) and echoes streight (for pixel brightness)
It should work on the phased array principles, without rotating, moving, without using any motors. Desired radiation pattern is illustrated by following animations:

Is it even possible to draw a 2D image with this sensor? There is just one receiver so the triangulation of the source of the echo is impossible. The algorithm description in Wikipedia looks more like "How to draw an owl" meme. https://knowyourmeme.com/photos/572078-how-to-draw-an-owl In reality this task is very complicated. Technically You can use this sensor with 2 steppers to draw image pixel-by-pixel but it will take minutes.

@FilipFranik As it was stated: "And accidentally I have a couple of Arduino sensors HC-SR04".. So its possible. Also, sorry, I dont learn memes (head space is way limited to trash it with remembering useless memes).

What I meant was "the description of algorithm in Wikipedia is misleadingly simple, whereas in reality the task is not". Having couple of those sensors helps, but you will need a device that sends only a single pulse of sound and then several microphones listen to the result (those sensors can't do that), then the tricky part comes, you need to look for local minimums and maximums in the result trying to match them between sensors. This way you can triangulate (in 3D) what pixels should be brighter. This is a very interesting (and difficult) project, and I will think more about it.

@FilipFranik My PC sound card (EMU1212) has 2 Output and 2 Input channels; It can easily sample at 192khz, meaning that generating/recording square wave at 48khz frequency is a simple task, as well as aligning/analysing phase (in software) - just shift signal start in left or right channel.. And 2 SR sensors has exactly 2 transmitters and 2 recievers (to be desoldered from such a poorly designed sensors). But also they have some logic, I wondered can I reuse a part of it?

The datasheet for the sensor doesn't say what chips are located on it. Could you please write the numbers you see on them in the question?. According to here http://osoyoo.com/2018/08/arduino-lesson-ultrasonic-sensor-hc-sr04-module/ they are two LM324 (quad op-amps) and MAX3232 (RS323 transceiver) This would explain the strange interface since this looks like a clever hack to lower cost of the sensor.

This might interrest you http://uglyduck.vajn.icu/ep/archive/2014/01/Making_a_better_HC_SR04_Echo_Locator.html and this http://www.pcserviceselectronics.co.uk/arduino/Ultrasonic/electronics.php There is open-hardware upgraded HC-SR04 board that replaces custom Chinese microcontroller with ATtiny24. Technically you can then upload any program you want on it.

@FilipFranik One amp is really the 324, second is unnamed, no markings on it. And a "max202 cse+1409" IC. Sensors are visually the same, but are non-measurable with standart multimeter. It gives infinite resistance even at 2MOhm. And zero voltage even at 200mV scale when loud sound pushed into it. So they are neither inductors, nor capacitors (upd: I think they're capacitors operated at microvolts scale). And it all is kind of "totally chineese magical stuff".. Thanks, I will read the info :)

This would be a fair first attempt. It may not fit your end-goal, but it's a good intermediary step: https://youtu.be/PlB3c2WaaBg

@Paul This could not help me, because it utilizes motor, but not phased array manipulation, to direct sound.

@jsotola It means that you have 2 sensors. By sensor I assume a transmitter and a reciever in one device. So you have 2 transmitters that could allow you to direct wave without rotating or moving your head to which it is attached. But by playing with wave phase so they cancel out. Having 2 recievers would allow to guess direction of a sound, as you ears do. That would give you one dimension: 1D. Another trick is that you could recieve more than 1 echo, that would give you depth, or second dimension. You havent even bothered reading wiki article in my question! It is described there very well!

@jsotola I want to build a 2D plane, where one dimension is horisontal and lies in the line, connecting human eyes, or ears. And second dimension is a depth. That gives a plane. It could be a fan-shaped image (like medical), showing rough approximation of room (and obstacles the plane crossects). I want to achieve it without rotating actual sensor (not using any kind of motor), that's primary goal. I think that more clever echoes processing could be required, than just "measuring time". For instance, I could need to process arrival phases. And also I'd like to measure echo strenght as well.

@jsotola I think 2 tranmitto-recievers (sensors) could build a fan-shaped figure in a plane, and 3 sensors could build a 3D space figure, limited by some cone, or even tetrahedra.. but all this "is not exact" - I've just started studying this field :)

@jsotola I've added animation to original question to illustrate what I want to achieve.

@xakepp35 i have heard of using a microphone array to record, at a distance, the voice of one person in a crowded room ...... your project is very similar ..... there may be detailed information on the web

@jsotola May. A link could be much useful than a mere rumors..   ;-)

This certainly cannot be done with these modules. But you should be able to reuse the ultrasonic piezo elements. If you really want to be a cheapskate you might be able to also reuse the op amps. Tomorrow I will try to write a somewhat answer, but you won't get a ready to use solution here.

https://www.youtube.com/watch?v=bgz7Cx-qSFw


text:
Voltage meter ADC + serial: Bytes lost during communication
I want to make a simple digital voltage monitor. So I have a sketch:
void setup() {
  Serial.begin(115200);
}

void loop() {
  int val = analogRead(A4);     // read the input pin
  val = 1;
  byte buf[4];
  buf[0] = 0;
  buf[1] = 0;
  buf[2] = val & 255;
  buf[3] = (val >> 8) & 255;
  Serial.write(buf, 4);             // report voltage value
}

When I tried to read serial buffer on PC host, I noticed that sometimes 1 byte can be lost, which lead to shifts and headache. How should the streaming be done?

PS.

host os: win7 x64;
language: c/c++
com port library: CSerial

Loop is as follows:
typedef int32_t sample_t;
while (true) {
    int nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(sample_t));
    size_t numRead = nBytesRead / sizeof(sample_t);
    if (numRead > 0)
        std::cout << "read: " << numRead << " samples\n"; // Calculate average here!
}

Either by printing it as simple ASCII, or by wrapping the values in a proper packet format with DLE.

@Majenko What is a "proper DLE packet"? I cannot find any reference on what DLE could stand for.

Data Link Escape. Your problem is you don't know where the data starts. You need a properly formed header with preamble, and a way of making bytes that appear in the data not appear to be a header byte. Or just use ASCII which restricts the valid data bytes to a very limited range.

@Majenko I thought i can prefix each values with 0xAAAA (like ethernet preamble stuff), then put a length field, then append postfix 0x5555 that means "transmission is done", and check if data length equals actual length - then is a valid packet.

That's the right kind of idea, yes. However you have to ensure that 0xAA or 0x55 never appear in your data. And that's where DLE comes in.

For example, replace 0xAA with 0xFF 0x0A then interpret that sequence at the receiver as 0xAA. Of course, 0xFF has to itself be escaped - as 0xFF 0xFF for example.

So at the receiver, if you see 0xFF then throw it away - but treat the next incoming character as something special.

@Majenko arduino 10-bit adc readings cannot exceed 1023. so these both cannot appear in data. i can even better place there 0xFFFF, 2 bytes length, 2*length bytes payload

One could. For example you may end up with 0xAA 0xAA 0x02 0x01 0x55 0x55 0x55

@Majenko so need to eliminate ending of a packet, replace it with length?

However, by the time you have done all this, your packet is now bigger than, for example, 1F3\n which would suffice.  That's just 4 bytes maximum (less if the value < 256) - the size of just your pre- and postambles.

@Majenko You mean Serial.println(val, HEX); and parsing that on host?

That would give you \r\n as the ending - wasting a byte. Serial.print(val, HEX); Serial.print("\n"); saves that one byte (if you care).  Then, yes, parse it on the host (which is simple enough).

The easiest way is to send the integer as ascii and do a atoi or atol on the pc. A '\n' or 'etx' at the end should be enough. If you want to be 100% sure, then a 'stx' at the begin and perhaps a checksum just before the '\n' or 'etx'. No HEX, but just Serial.print(val) for the data. The cable between the pc and the arduino is not a serial cable but a usb cable. A byte getting lost is almost impossible, something else is wrong.

@Majenko, That byte saved alot, now i am getting 5ksps instead of 3.5! Summing them up for a second and getting average leads to quite precise 16~20 bit voltmeter

@Jot It is solved, trouble was that i recieved data with 0 or 1 byte shift, and we found a simple way of solving it. sending via base-10 ascii would lead to poorer performance than sending hex

@xakepp35 For higher baudrates, you can try a arduino leonardo or micro. They have usb connected to the microcontroller itself and the communication is with usb speed because there is no real serial port. What about calculating the average in the arduino?

@Jot you think it will increase sampling rate (e.g better noise floor?) how much analogReads per second could it call? I have mega2560. How do i tie that to seconds in arduino? I need 1 measure per second, as precise as possible. Also summing up several thousand of samples would overflow 16bit integers.

The arduino mega has a 10-bits adc. Everything (linearity, noise, and so on) matches those 10 bits. I think a good start is an external 16-bits adc: https://www.adafruit.com/product/1085

@Jot when you sum up multiple samples, random noise is attenuated (If i sum up 16 samples, I could get at most 3 or 4 bits of extra precision, because random noise inside each sample will cancel itself out, and real DC data would properly sum up)

@xakepp35 yes, I always use the average of a number of samples to read dc voltages. But the linearity does not increase and that would be needed for a voltage meter. The overall precision requires a better adc than 10-bits.

@Jot for a 50 amps 220V wattmeter i calculated that i require 16 bit adc, to stay cool and precise less than 0.5W. Can i connect many 16-bit adc to single arduino board?

@xakepp35 The adafruit ADS1115 module has 4 analog inputs and 4 of those modules can be connected to a single i2c bus. For a wattmeter, what is the sample rate that you need? With many channels a adc with spi bus might be better, since the i2c bus is slow.

@Jot I need to measure up to 50a shunt, with precision more than "0.5W error per day"

With help in a comments I've managed to deal with the task myself.
First of all, as @Majenko pointed out, I was dealing with some multi-byte data. So I need some control character, that separates packets. I choose hex output with '\n' delimeter as control character - that served good. I was able to read 3.5 to 5k packets per second (with voltage reading) from serial on the host.
Second improvement, credited to @Jot, is to stack some sequential values right in arduino, before sending.
Alongside with increasing sampler frequency that could be very good.
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

void setup() {
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  Serial.begin(115200);
}

void loop() {
  int val = 0;
  for( int i = 0; i < 32; ++i )
    val += analogRead(A0);
  Serial.print(val, HEX);
  Serial.print("\n");
}

at the host recieve side, some simple conversion could be done:
#include "Serial.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

// sample to voltage
double s2v(int sample) {
    return 5.0 * (static_cast<double>(sample) / 1024);
}

int main() {
    std::ofstream ofs("test.csv", std::ios::out | std::ios::ate);

    size_t comPort = 3;
    size_t baudRate = 115200; // 57600;

    CSerial serial;
    if (serial.Open(comPort, baudRate))
    {
        std::cout << "COM" << comPort << " opened @" << baudRate << "bit/s\n";

        // serial recv buffer
        size_t bufSize = 1048576;
        auto lpBuffer = new char[bufSize];

        // accumulator
        size_t nVals = 0;
        int nAcc = 0;

        // timer
        __time64_t destTime;
        __time64_t destTime2;
        _time64(&destTime);

        while (true) {
            SleepEx(10, false); // care of 100% cpu core usage, poll serial port lazily
            size_t nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(lpBuffer[0]));

            //parse buffer:
            size_t cvtPtr = 0;
            for (size_t i = 0; i < nBytesRead; ++i) {
                if (lpBuffer[i] == '\n') {
                    try {
                        lpBuffer[i] = '\0';
                        auto val = std::stoi(lpBuffer + cvtPtr, nullptr, 16);
                        nAcc += val;
                        nVals++;
                    }
                    catch (...) {
                        // ignore, or warn that serial recieved junk/empty packet
                    }
                    cvtPtr = i + 1;
                }
            }

            //check if doom had come!
            _time64(&destTime2);
            if ((destTime2 - destTime) > 0) {
                auto fVoltage = ( s2v(nAcc) / 32 ) / nVals;
                std::cout << fVoltage << "\t(" << nVals << " ksps)\n";
                ofs << destTime << "," << fVoltage << "," << nVals << "\n";
                if((destTime % 30 ) == 0) // care of disk, write only once in 30 seconds
                    ofs.flush();
                destTime = destTime2;
                nVals = 0;
                nAcc = 0;
            }
        } // while
    } // if opened
    return 0;
}

That gives voltmeter with high precision, about ±0.5mV, that is updated every second.
Also! It was stated about 10bit adc, 5.0V/1024 = 4.88mV, but i got some subthreshold oscillations in vivo, adding samples up. So you are wrong, noise can be attenuated and resolution can be artificially pumbed up, in a trade for increased sampling time. Here is 14bit ADC built on top of 10bit ADC: . Its photovoltaic cell in a dark street, oscillations are caused by cars' front lights. Timescale is 1000 seconds per grid div

Don't you mean +-5mV? Because 5V / 1024 (10 bit) is about 4.9mV

@chrisl I mean i got 3-4 bits more resolution that was specified for arduino 10-bit ADC.

source: Stack Exchange

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

sort: votes


text:
How to generate 3 PWM signals
I have 2560 mega, and I Want to generate 3-phase PWM signal at 62.5khz, synced and shifted 120 degrees apart.
I need that for 3-phase split-coil boost converter (or even isolated flyback converter), with 3 phase transformer coupled inductor. So I dont need sine wave table like here, but actually, a direct square wave PWM output, from 3 synced digital pins, with chosen duty cycle. How can I do that?

How accurate the phase difference has to be? Is (0°, ±119.53°) good enough? If not, would a frequency of 62.745 kHz be OK? What duty cycle do you want?

@EdgarBonet  Hello. Probably, its better to stick with 2 phase or 4 phase, as it's easier to divide. Oh, and let's omit 2phase case, as it could be solved with h/w inverting (no software phase offset). All I want is a way to set up a phase offset in arduino, and question is about it. Everything other better fits as a topics for ee.se. Consider it is driving a transistors' gates, (no matter what is further), to focus only software question

If you have any timers left, I would (regardless of the number of PWM signals and if you need different PWM frequencies) just dedicate a timer to do IRQs to manage them.
The frequency of the IRQs would then depend on how accurately you want to control the duty cycle, ref. also to the comment from Edgar Bonet .

That seems to be nice solution. However, I am not very familiar with low level things of  arduino. Can you extend your answer with simple small example, please? It could be as simple as if you given 4 pins: pin[0,1,2,3], and 4 duty cycles: dc[0,1,2,3]. Frequency is fixed at 62.5khz (or 31khz, not matters), and pins must provide synced PWM signal, with given dutycycles, and phase offsets of 0, 90, 180 and 270 degrees respectively. Like for(i=0; i<4; i++) { analogWrite(pin[i], dc[i]); }, but for synced pins.  Can you give such how to sync pins, with fixed phase offsets and frequency??

Wow, hang on. Will try to write more later, but I mean that if e.g. 4 signals 90 degs apart all with 50% duty cycle, one would set a time at 8 times the frequency (not 4 since for a single 50% you need both the "LOW-to-HIGH" and "HIGH-to-LOW".Then depending on the duty cycle resolution/accuracy needs, one needs to increase the IRQ frequency (which above was the base frequency*8). Programming Arduino is like C, so operators like % (don't know the term in English, but I mean e.g. 107%100=7) come handy.

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


text:
DS1307 Real-Time Clock
I am trying to make an Arduino project based on the Sparkfun DS1307 RTC (real-time clock).
There are a few issues with how Arduino libraries don't support checking if the Arduino board has been powered down and check for that.
Then using that as a conditional as to when the program should fall back to the compiled time if the RTC isn't set to a time yet because of something else.
When I power down the clock, it will automatic fall back to the compiled time every single time, regardless of what is currently on the RTC. Clearly this is not something you would want.
Edited - This is my current code. Keep in mind there are a few more changes I could do like take Byte zero declare out of the loop so it is still rough.
#include <Wire.h>
#include <SparkFunDS1307RTC.h>

#define DS1307_ADDRESS 0x68

void setup() {
  Wire.begin();
  Serial.begin(9600);
  rtc.begin();
  if(false){
    //Should check RTC somehow to determine if should fallback to compiled time here.
    Serial.println("The DS1307 clock has lost power and reset to compiler's time");
    rtc.autoTime();
  }
}

void loop() {
  if(digitalRead(7)==LOW)
    printDate();
  delay(1000);
}

byte bcdToDec(byte val){
  return ((val/16*10) + (val%16));
}

void printDate(){
  rtc.update();
  Wire.beginTransmission(DS1307_ADDRESS);
  byte zero = 0x00;
  Wire.write(zero);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_ADDRESS, 7);
  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  int weekDay = bcdToDec(Wire.read()); //0-6 -> Sunday - Saturday
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  //Print the date like 3/1/1/11 23:59:59
  Serial.print(month);
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

You only need to set the time in the RTC once. There is no need to keep it in the code. But if you still want to, the DS1307 has a Clock Halt bit that is set when the RTC has lost it's power. So you can only set the time when this bit is set.

How do I check if this bit ha been set?

https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code#setting-the-time

That link doesn't answer my question. How do you check if RTC lost power? All that link does is show codes I already know about. I am able to set RTC to a new time. The trouble is each time I power up arduino board it will assume RTC is wrong regardless and overwrite it. Which end up with a RTC that still think it is January but really is June for example depending on time compiled.

When the RTC loses power the CH bit is set to 1. When you set the time this bit is also set to 0. So when the Arduino restarts, and this bit still reads 0, you know that you shouldn't change the time.

Please show us your code!

Changed to post my code.

The link did answer your question. Use if (! rtc.initialized()) { instead of your current if(false){. But I still don't see the use. You only set the time once on the RTC. If for some reason in the future the RTC loses power, it doesn't make a difference if you don't set the time, or use the compiled time, as both will be wrong.

I am trying to write a book explaining the basic code and want a nice simple single program. Instead of going back in code to change to true/false depending on your needs. I will test that out tonight. Edit: Looks like initialized() only works with adafruit not sparkfun DS1307 library.

That would indeed make it easier for others. The sparkfun library has no way to read the CH bit. You could instead check if the current year is smaller that 2017. The default value for year is 2000 if the chip loses power.

Yeah that would work well.

DS1307 gives a square wave output which can be set to specific frequencies which is available in the datasheet.
Initially the square wave output is disabled.
You can enable it when you set the time.
When you power up again, check for the square wave and if it is absent you can set the time again.
This can be easily done by creating a timeout code and resetting the timeout timer in an interrupt. If square wave is present an interrupt will be generated accordingly and the timeout time period will be set to initial value.
If the timeout time expires you set the clock. This can even track clock failures in real time. Also you can use the same interrupt to extract data from the RTC as square wave output can be configured to 1Hz and hence you can poll the RTC at every 1Hz and take the data from the RTC.

You could periodically store the date and time in the battery-backed SRAM in the DS1307. Every few seconds, once a minute, something like that.
Upon sketch start, perhaps in setup(), read the current RTC time, compare to the stored time, if the current time is later than the stored time, you can do the math and see how long the Arduino has been down.  Or use the Arduino's EEPROM to hold the last stored time if you are concerned about the RTC losing it's battery and resetting to it's default date and time, which would be earlier than the EEPROM time.

Easy. Here is one way to do it.

Read the clock off the rtc.
Wait a known period of time, based on the mcu frequency,
Read the clock off the rtc again.
Compare the two time reading and it should have advanced. If not, fall back to compiled time.

There are other ways to do it as well, like bor, or square wave output, interrupt on vbat line, ......

This RTC real time clock as far I am aware always tick forward. So checking for that time delta doesn't tell me if the clock has been reset to default time or not. Which is what the question is about.

There are a few issues with how arduino's libraries doesn't support checking if the arduino board has been powered down and check for that.

How is it supposed to do that? The board's powered down.

When I powered down the clock. It will automatic fallback to compiled time every single time regardless of what is currently on RTC. Clearly this is not something you would want.

So don't have a compiled in time.

I saw there was a flag in one of the custom library that check if RTC clock lost power (due to battery dying or disconnect or whatever). But it was for the different brand of RTC DS1307 that I have.

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


text:
Win10 64bit, IDE 1.8.0 back to IDE 1.6.13 won't compile anything including Blink. 1.6.12 does compile
Arduino: 1.8.0 (Windows 10), Board: "Arduino/Genuino Uno"
c:\program files (x86)\arduino\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

http://forum.arduino.cc/index.php?topic=134161.0 seems to contain multiple possible solutions. Run Arduino as Administrator. Create a new sketch, and copy all code to this new sketch. Something with the %tmp% directory.

Code file has full permissions and access. Running the IDE as administrator makes no difference. Same error message for everything (blink ++++) as above. re-install of IDE made no difference.

It looks like @grtblu and ArduinoAngryAtMe are the same person. It is confusing when someone else replies to a comment. It would help if you remembered your login credentials and replied as the OP.

I suggest downloading the IDE into a folder which is not in Program Files. Put it in Documents or some such place.

There are some reports of this error in the Arduino IDE issue tracker: https://github.com/arduino/Arduino/issues/5616 and https://github.com/arduino/Arduino/issues/4683 where it was found to be caused by antivirus software.

Try locating the code file in explorer.exe, go to its properties and check if the system has full access to the file. Just to be sure, run the Arduino IDe as an administrator.

I understand the logic in running as the administrator and its usually a good solution, but it may cause problems because the IDE reads and writes to folders within the user's profile and the Administrator MAY not have permissions to these files, so you need to check that as well.  It would be better to give users the permissions they need on the Arduino IDE folders and registry hives.

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


text:
DHT sensors with RGB LED
I have a DHT11 that outputs temperature and humidity values to my serial monitor. I'm trying to serial the COLOUR of the light based on the temperature conditions. So far I only get 1's and 0's. How can I change these integer values to output string say RED, GREEN or BLUE?
Code
#include <dht.h>

dht DHT;
#define DHT11_PIN A5
int redPin = 10; // Red LED,  connected to digital pin 10
int grnPin = 9; // Green LED, connected to digital pin 9
int bluPin = 8;  // Blue LED, connected to digital pin 8

void setup() {
  Serial.begin(9600);
  // Sets the pins as output for RGB LED
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;
  Serial.print("Temperature = ");
  Serial.print(t);
  Serial.print( "," );
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.print("\n");
  delay(60000);
  if((DHT.temperature < 26) && (DHT.temperature >= 23.2)) {
    // Writing the LED colour pins HIGH or LOW to set colours
    digitalWrite(redPin, HIGH); // yellow
    digitalWrite(grnPin, HIGH);
    delay(100);
    digitalWrite(bluPin, LOW);
  }
  if((DHT.temperature < 23) && (DHT.temperature > 20.2)) {
    digitalWrite(grnPin, HIGH); // green
    delay(100);
    digitalWrite(redPin, LOW);
    digitalWrite(bluPin, LOW);
  }
  if((DHT.temperature < 20) && (DHT.temperature > 17.2)) {
    digitalWrite(grnPin, HIGH); // aqua
    digitalWrite(bluPin, HIGH);
    delay(100);
    digitalWrite(redPin, LOW);
  }
  if(DHT.temperature <= 17) {
    digitalWrite(bluPin, HIGH); // blue
    delay(100);
    digitalWrite(grnPin, LOW);
    digitalWrite(redPin, LOW);
  }
  delay(1000);
  // Sensor shouldn't be read too frequently so delay of 1s
}

I will be grateful if I can get some help. Thanks!

Add Serial.print() in each block that sets the pins to new values.

So far I only get 1's and 0's

Before moving into the LED parts, you have to make sure that your system can correctly read the DHT sensor. There are debugging example from arduino-info.wikispaces.com

How can I change these integer values to output string say RED, GREEN or BLUE?

You can do it by simple if-else statement. This would be better than your original code, because there are multiple if's without any else which is (although not so significant) less optimal.
So, if put together, you can try:
void loop()
{
  int t,h,chk = DHT.read11(DHT11_PIN);

  switch (chk)
  {
    case DHTLIB_OK:
                Serial.print("OK,\t");
                break;
    case DHTLIB_ERROR_CHECKSUM:
                Serial.print("Checksum error,\t");
                break;
    case DHTLIB_ERROR_TIMEOUT:
                Serial.print("Time out error,\t");
                break;
    case DHTLIB_ERROR_CONNECT:
        Serial.print("Connect error,\t");
        break;
    case DHTLIB_ERROR_ACK_L:
        Serial.print("Ack Low error,\t");
        break;
    case DHTLIB_ERROR_ACK_H:
        Serial.print("Ack High error,\t");
        break;
    default:
                Serial.print("Unknown error,\t");
                break;
  }
  //moving on into next parts only if you get "OK" from serial reply, which means you successfully read the DHT11
  t = DHT.temperature;
  h = DHT.humidity;
  Serial.print(DHT.humidity, 1);
  Serial.print(",\t");
  Serial.println(DHT.temperature, 1);

  //----end of sensor reading and debugging

  if (t<=17)
  { //blue
   digitalWrite(bluPin, HIGH);
   digitalWrite(grnPin, LOW);
   digitalWrite(redPin, LOW);
   delay(100);
  } else
      if (t<20)
      {
       digitalWrite(grnPin, HIGH);  // aqua
       digitalWrite(bluPin, HIGH);
       digitalWrite(redPin, LOW);
       delay(100);
      } else
      if (t<23)
      {
        //....
      }
      //....
      //and goes on

 delay(1000);
}

And yes, as @Matt suggest, it would be better if you use PWM to control the RGB led which will give you (mathematically) 255*255*255 colour possibilities instead of 8 combinations from digitalWrite(). For example:
//....
//....
  if (t<20)
  { //aqua
   new_t = map(t,DHT11_min_temperature_reading,DHT11_max_temperature_reading,0,255);
   //you can do self research about DHT11 maximum and minimum temperature reading
   //parameters 0 and 255 is the minimum value of PWM(0) and the maximum value(255)
   AnalogWrite(bluPWMPin, new_t);
   AnalogWrite(grnPWMPin, 255-new_t);
   AnalogWrite(redPWMPin, 0);
   delay(100);
  }
//....
//....

Hope it helps :D

You need to use analogWrite(). You use this with a digital pin and it does Pulse Width Modulation (PWM) which will give you are larger range of colours. Have a look at the Reference page for the function.
You might even be able to use the map function (something like that) to 'map' the temperature to the colour values without all the if statements.

The PWM pins have a ~ next to them on the PCB.

Thanks for your response. Do you have an idea of how I can implement the map function?

Erm...  not a clue, I've never used it, but I have seen it on here.


text:
Serial not declared in this scope, newbie mistake most likely
Ok, newguy with a little VBA coding experience going to pull hair out soon. It is probably a simple thing I have missed but I would like someone to point out where I went wrong. I modified a sketch that used an lcd to use the serial monitor instead but I sometimes run into this "not declared in this scope" issue. Doing something wrong, please point me in the correct direction.
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;
DateTime now;
char daysOfTheWeek[7][12] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

void showDate(void);
void showTime(void);
void showDay(void);

void showDate()
{
  serial.print(now.day());
  serial.print('/');
  serial.print(now.month());
  serial.print('/');
  serial.print(now.year());
}

void showDay()
{
  serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
}

void showTime()
{
  serial.print("Time:");
  serial.print(now.hour());
  serial.print(':');
  serial.print(now.minute());
  serial.print(':');
  serial.print(now.second());
  serial.print("    ");
}

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

  serial.println("working....")
  //wire.begin();
  //delay(2000);
  if (! rtc.begin())
  {
    Serial.println("Couldn't find RTC Module");
    while (1);
  }

  if (rtc.lostPower())
  {
    Serial.println("RTC lost power, lets set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop ()
{
  now = rtc.now();
  showDate();
  showDay();
  showTime();
}

Case matters in C/C++. You should write Serial rather than serial.

OMG, I will not live that down!!!

Sorry, I will be more careful with that. I am used to VBA where if you @@$ up syntax it highlights it. Thanks for your quick answer. Hiding head now, lol

As a nebie I also noticed that when syntax is valid the color of the code is red/orange. Are functions highlighted in the IDE?

Built-in functions appear to be highlighted in orange, reserved words in blue-ish. Strings in Green-ish? Pretty sure it doesn't parse your code to highlight specific to your project.


text:
how to send FFT array consist of 512 Samples Data From arduino to raspberry pi using i2c and this is the code for FFT any Suggestion plz?
#include "arduinoFFT.h"
float y, x = 0;
#define t PE_0
#define SAMPLES 1024             //Must be a power of 2
#define SAMPLING_FREQUENCY 1024 //Hz, must be less than 10000 due to ADC
arduinoFFT FFT = arduinoFFT();

unsigned int sampling_period_us;
unsigned long microseconds;

double  vReal[SAMPLES];
double vImag[SAMPLES];

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

  sampling_period_us = round(1000000 * (1.0 / SAMPLING_FREQUENCY));
}

void loop() {

  /*SAMPLING*/
  for (int i = 0; i < SAMPLES; i++)
  {
    microseconds = micros();    //Overflows after around 70 minutes!
    y=(analogRead(t))*(3.3/4095.0)-1.65;
    x=((1000.0*y)/201.0);
    vReal[i] = x;
    vImag[i] = 0;

    while (micros() < (microseconds + sampling_period_us)) {
    }
  }

  /*FFT*/
  FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HANN , FFT_FORWARD);
  FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
  FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
  double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

  /*PRINT RESULTS*/
  //Serial.println(peak);     //Print out what frequency is the most dominant.

  for (int i = 0; i < (SAMPLES / 2); i++)
  {
    /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

    //Serial.println((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
    //Serial.print(" ");
    Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
  }

  delay(1000);  //Repeat the process every second OR:
  //while (1);      //Run code once
Serial.println("//");
}

this is the line that you have to replace with I2C comm Serial.println(vReal[i], 1);  .......... you have to start by writing code that sends just one Double between the two devices .... then merge the two codes

Are you thinking of using the Arduino as the master or the Pi as the master?


text:
Switch between timer2 and manually setting output of pin 3
I have a 62.5 kHz square wave created by timer2 on the pin 3. I would like to be able to use digitalWrite(3, HIGH) to force pin 3 high for several clock cycles, but then I would like it to return the 62.5 kHz square wave. Is there a way to reset a single output without resetting the entire program?
void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT); //Output for OCR2B (Timer 2)
  //The following block allows sets the Timer2 properties for PWM
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(WGM22) | _BV(CS20);
  OCR2A = 255; //Sets the period to 16us (62.5kHz)
  OCR2B = 0; //Sets the duty cycle of the signal (8-bit(255) resolution)
}

void loop() {
  int pot = analogRead(A0);
  int duty = map(pot, 0, 1023, 0, 255); //scale to duty cycle resolution
  OCR2B = duty; //set duty cycle
  delay(10000); //arbitrary wait time
  digitalWrite(3, HIGH);
  delay(10000); //arbitrary wait time
  //undo the digitalWrite to continue the pulse train here
}

Can you show how you are currently setting up the square wave? That is, are you using a library in Arduino, or are you using the timer/counter registers directly to produce the waveform? Are the "several clock cycles" actual MCU clock cycles, or cycles of the 62.5 kHz waveform?

"several clock cycles" is just an arbitrary time where the output is force either high or low.

please do not put code in comments .... somebody moved the code to your question, where it is supposed to be .... please delete the two comments

If you clear the clock select bits in TCCR2B, then the PWM stops and you can control the port normally. To re-start the PWM, set the CS20 bit just as you did in setup().

to clear the bits would i set tccr2b = 0; or just the _bv(0) part?

TCCR2B &= ~(_BV(CS20)); will clear just CS20 bit and leave all else the same.


text:
Arduino Nano PID Controller with Potentiometer + IBT-2 Motor Control Board
I have a potentiometer connected to an analog pin A1 and would like to implement PID
Control to move a robot arm up and down based on to a given serial command. For this
to work I will need PID out produce a direction and speed output.
#include <AutoPID.h>

// PID settings and gains
#define OUTPUT_MIN 0
#define OUTPUT_MAX 255
#define KP 0.12
#define KI 0.8
#define KD 0.003

// Variables on PID values
float analogReadValue, setPoint, outputVal;

int SENSOR_PIN = A0; // center pin of the potentiometer

int RPWM_Output = 10; //IBT-2 Motor Control
int LPWM_Output = 11; //

bool BarUp;
bool BarLow;
bool BarStop;

float sensorA1;

char c;

// Input/output variables passed by reference, so they are updated automatically
AutoPID myPID(&analogReadValue, &setPoint, &outputVal, OUTPUT_MIN, OUTPUT_MAX, KP, KI, KD);

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

  //Motor Direction controls
  pinMode(RPWM_Output, OUTPUT);
  pinMode(LPWM_Output, OUTPUT);

  myPID.setTimeStep(500);
}

float AnalogSensor()
{
    // read the input on analog pin 0:
    int sensorValue = analogRead(SENSOR_PIN);
    // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
    float voltage = sensorValue * (5.0 / 1023.0);

    return voltage;
}

void loop()
{
   analogReadValue=AnalogSensor();

  //Reading serial command
  if(Serial.available())
  {
     char c = Serial.read();

     if(c=='r')
     {
         BarLow=false;
         BarUp=true;
         Serial.println("Arm is Rising");
     }
     else if(c=='l')
     {
         BarUp=false;
         BarLow=true;
         Serial.println("Arm is lowering");
     }
}

if(BarUp)
{
  setPoint=UpperLimit;
  myPID.run();
}

if(BarLow)
{
  setPoint=LowerLimit;
  myPID.run();
}
}

void RaiseArm()
{
   analogWrite(LPWM_Output, 0);
   analogWrite(RPWM_Output, 20);

   delay(1000);

   StopArm();

   BarUp=false;
 }

 void LowerArm()
 {
   analogWrite(LPWM_Output, 20);
   analogWrite(RPWM_Output, 0);

   delay(1000);

   StopArm();

   BarLow=false;

 }

 void StopArm()
 {
    analogWrite(LPWM_Output, 0);
    analogWrite(RPWM_Output, 0);
 }

Ideally I would like to set the Setpoint to analog 5.0 for raising arm and analog
0 for lower arm. Baring in mind.
   analogWrite(LPWM_Output, 20);
   analogWrite(RPWM_Output, 0);

Is for raising arm and
   analogWrite(LPWM_Output, 20);
   analogWrite(RPWM_Output, 0);

Is lowering arm. Hope you can help as the current system is not implementing PID that can
potentially work. How can I out put a direction and speed from my pid function call to control the arm.

And what exactly is your problem in doing that? You didn't describe how exactly this is not working. Please be way more specific.

How can I output a direction and speed from my pid function call to control the arm direction and speed.  As I have not worked with PID previously.

do you understand the example code that is included with the AutoPID library?

Yes I understand parts of it but learning as I go. The Setpoint would be the desired Potentiometer value. I am trying to figure out how the output can be integrated with the direction and speed values to control the motor. analogWrite(LPWM_Output, 20);
analogWrite(RPWM_Output, 0);

The text about raising and lowering the arm doesn't match the code.  What does analogWrite(LPWM_Output, 20) actually do?  Is it's '20' what you would want to affect with the PID?    The way to understand PID is to focus on the "P"roportional term and the proportion of setpoint error that you want to convert into process output. Are you converting Ohms of error into PID duty cycle?  Volts of error into a servo position?  AnalogRead counts into speed?


text:
Help needed with I2C LCD + Arduino - DS-LCDD5
I am new to this forum and a relative beginner to Arduino (software wise) Have built many projects, but always just copy/paste/modify example code.
I found a couple of these modules (a PIC18 daughter board on the back of a common 16x2 LCD)
It says in the data sheet that it can be controlled via I2C, but my skill level is too low to figure out how to do it.
Can somebody please give me advice on how to proceed?
The "I2C Scanner" sketch identifies it at address  0x14 , but the usual I2C-LCD libraries don't work on it.
I use it with an Arduino UNO, SDA(A4), SCL(A5), 1k8 pullup resistors on each.
The module is working 100% with the 1 wire serial method as per the manual.
This is how I think it should work, but it does nothing:

// Include Arduino Wire library for I2C
#include <Wire.h>

// Define Slave I2C Address
#define SLAVE_ADDR 0x14   // 7bit address = 0010100D, 0x14 hex

void setup () {

 Wire.begin();                           // Initialize I2C communications as Master

  // Write something to the Slave
 Wire.beginTransmission(0x14);           //  0x14  (SLAVE_ADDR)  0010100
  Wire.write(0x28);                       //  00101000
  Wire.write(0x00);                      //  Register address  "0"
  Wire.write("A");                       //  some text
  Wire.endTransmission();

 }

void loop () {

}

Link to manual: http://www.i-lcd.com/PDFs/Drivers/Technical%20data%20on%20DS-LCDD5%20Interface%20Module%20(IDS).pdf

Try leaving out the Wire.write(0x28);.

If the leads are not long go to something in the 3.3 to 4.7K range. In my opinion there is a problem with the I2C libraries, they are not all compatible.  I found one that works and I put it in the folder with my sketch. Since doing that I have nad no more I2C-LCD problems.

Data sheet or firmware is wrong.
See this for solution:  https://forum.arduino.cc/t/need-help-with-i2c-code-for-a-16x2-lcd-ds-lcdd5/918289/28?u=jdev99
Thank you for all advice.
Joe

So, after I "remembered" that I have an oscilloscope, I hooked it up and noticed that I don't receive an "acknowledge" from the module.
Then I played around with the clock speed, and found I do get an "acknowledge" if I set it between 16000kHz and 18000kHz with the "Wire.setClock" command. :thinking:
Then by mere coincidence, I found that text must got to R1 NOT R0 and control commands to R2 NOT R1. :grimacing:
But I could not get any of the RGB commands to work.
I tried this on all 6 of the modules which I have, same results.
I will just stick to serial comms when I need to use any of these.
So, either the datasheet is wrong or the firmware in the module is flawed.
At least I learned a lot about the workings of I2C in the process, which my goal was.
https://forum.arduino.cc/t/need-help-with-i2c-code-for-a-16x2-lcd-ds-lcdd5/918289/28?u=jdev99
Thank you for all advice.
Joe
Working code:
'''
// Include Arduino Wire library for I2C
#include <Wire.h>
// Define Slave I2C Address
#define SLAVE_ADDR 0x14                      // 7bit address = 0010100D, 0x14h
void setup () {
Wire.begin();                                    // Initialize I2C communications as Master
Wire.setClock(16000);                            // only 16000 - 18000 work
//Clear display
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(0x01);
Wire.endTransmission();
}
void loop () {
//Start print on line1, pos1
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(128);
Wire.endTransmission();
// Write something to the Slave
Wire.beginTransmission(0x14);                       //  0x14  (SLAVE_ADDR)  0010100
Wire.write(0x01);                                   //  Register address  "0"
Wire.write("ABCDEFGHIJKLMNOP");                     //  some text
Wire.endTransmission();
delay(3000);
//Clear display
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(0x01);
Wire.endTransmission();
//Start print on line2, pos1
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(192);
Wire.endTransmission();
// Write something to the Slave
Wire.beginTransmission(0x14);
Wire.write(0x01);
Wire.write("1234567890-=+*/@");
Wire.endTransmission();
delay(3000);
//Clear display
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(0x01);
Wire.endTransmission();
}
'''

Try Replacing the "A" to single quotes 'a'
Wire.write('A');
or
Wire.write(0x41);
you can also try and add (byte) before the hex value:
Wire.write((byte)0x28);


text:
what is the maximum number of servo motors that can be connected to a l293d motor shield?
I have a requirement in which I need to run 2 motors and 6 servos.
The motors and servos won't be running simultaneously at any given time.
what best can I use. I Was hoping to use l293d shield as it powers 2 DC motors and 2 servos, but how do I get other 4 running too ?
I'm aware that l293d shield has 2 free pins pin2 and pin13 that I leverage for signal pins for servo. (am I right in this ?, if so, i'll still need 2 more free pins for signal)

Please provide a link to the shield that you are using.

2 DC motors with 1 H bridge each need 6 pins in total (each motor 2 direction pins and 1 enable pin). I don't know what shield you are using, but in principle that would leave you with plenty of pins to connect your two servos. Though if the shield connects the enable pins (which are typically driven with PWM) to pins 9 or 10 the servo library would interfere with that. Then you would need a servo library, that uses the other hardware Timer

The servo motors I know don't require an h-bridge. Do you want to change their polarity or what's the purpose of the L293d?

Sorry, an image (which is unfortunately also in bad quality) is not really enough. Better would be a link to the actual product page where you bought it. I'm particularly interested in the pin connections of the shield (I mean which component of the shield is connected to which Arduino pin). That will tell you which pins are still free.

Bought it from an hobby store.
Attaching a link which I feel could be helpful.
https://robojax.com/learn/arduino/robojax_L293D_motor_shield_manual.pdf
Adafruit is the actual owner.
https://cdn-learn.adafruit.com/downloads/pdf/adafruit-motor-shield.pdf
I haven't been through their manual though.
(As it is difficult for me to understand electronics and schematics).

Do you think the best way would be,
Use a l293D H-Bridge and servos connected to arduino directly ?
In that case how would the power source be connected ?

As to the PDF Guide on page 19:

How can I connect to the unused pins?
The analog pins (analog 0-5 also known as digital pins 14-19) are broken out in the bottom right corner.
Pin 2 has a small breakout since its the only truly unused pin
The remaining pins are not broken out because they could be used by the motor shield. If you are sure
that you are not using those pins then you can connect to them by using stacking headers when
assembling the kit or soldering onto the top of the header with wires, or using a "Wing shield"

So you should have access to pins A0 to A5 (enough for 6 servos). You might need to solder a pin header in that place before you can actually use them.
The wording "Pin 2 [...] the only truly unused pin" is a bit weird, but if you follow the link to the schematics repo and look at mshieldv12schem.png (which seems to be the schematic just as an image, so you don't need to install Eagle for viewing it) it shows the Arduinos pins A0 to A5 only connected to the pin header and nothing else. This tells me that they are actually free.

I haven't used analog pins for any PWM application, I guess will have to experiment with that this time.
Thanks for the support.

The Servo library uses a Hardware Timer, but actually it doesn't use its PWM functionality. The pins are controlled in a timer ISR. Thus every digital pin can be used by the library. Otherwise the library wouldn't be able to support up to 12 servos on the Uno


text:
Non-Linear readings on Analog Pin A0 vs. other Pins A1
I discovered a curios behavior of my Nano v3. The analog Pin A0 seems to measure data in a non-linear way while the other pins seem to work normal.
Please have a look at the screenshot. This is the normal ReadAnalogVoltage example with a 50K potentiometer. A1 (red line) raise and falls linear when turning the knob. But the A0 line (blue) does not.

Is there a way to change it back to the normal behavior? Some weeks ago it worked fine on A0 as well. So these results are quite surprising for me. In general it would have been easy using another pin, but I already created a pcb which utilize A0.
Thanks

Does this happen within your circuit, or does it happen on a nano that is just connected to pots? Also what is the code stamped on the pot?

It is the official Arduino example: https://www.arduino.cc/en/Tutorial/ReadAnalogVoltage
My circuit uses an audio sensor for clap detection. It wasn't triggering anymore, that is why stumbled upon it. So this happens to both: the nano directly connected to a poti and my circuit.

When Arduino is not powered, measure resistance between failing pin and 5V/GND pins


text:
Creation of multiple power cells to be controlled by Arduino
I'm fairly new to the Arduino world, but have a history of good working knowledge of computers and software (I'm a software engineer), but I've only had the opportunity so far to create a few simple successful play-around projects.
I've decided to embark on a fairly ambitious project to build my son a ride on battery powered car for Christmas and trying to put all the pieces together.
An integral part of this plan is to develop what I call a couple of 'Power cells', which is simply a battery enclosure that has:
Updated:

An input from the Arduino to control the motor speed/voltage.
An input from either the Arduino or forward reverse switch to control the direction of polarity (make motor spin forwards or backwards)
Has a output to power the motor: 20V, drawing about 1-1.5 Amps
Has a output to power the 9x 12V LED lights on it, about upto 50W total (the LED lights will be controlled by the Arduino outside of the power bank, seeing there are a few of them).

I've drawn up a schematic that works with the components I've bought to help put the system together and was wondering if I am missing anything, critical or not?
Info about the battery I'm using can be found here: Aldi Xfinity 20V Li-Ion Battery teardown.
More Specifically:

Are there any errors with the cabling, I'm assuming no additional earth is required in a DC Circuit.
What size cables will i need to adequately service my power requirements?
Would I be able to control the reverse polarity switch directly from the Arduino? As I would like to also trigger a beeper when it is switched in reverse mode. Keep in mind the arduino would need to control 2-4 power cells.
I assume the controlling the potentiometer from the arduino I would need to use junction boxes between the arduino and the power cells to distribute the signal across each power cell, would this be the best way to do this?
The Li-Ion Battery also seems to have T output pin, i assume this is temperature monitoring, is there a way to utilize this input into the arduino for safety monitoring?
I was thinking of splitting the lighting power load between 2 power banks, would this be recommended / possible? (left power cell would power left side leds and right power bank would power right cell leds, with the exception of them both powering the center led).
Are there any additional safety precautions I should be following, especially working with a Li-Ion battery, ie. Fuse etc ?

I'm planning to make 2x of these Power cells to put in the car (each powers its own motor) (with the ability to add another 2 down the track).
Would really appreciate your feedback (please let me know if this is not the right place to ask this sort of question).

I don't understand what you are trying to show with the wires. You have = and - lines merging. What is this supposed to mean? And this question will probably get flagged as not being a "Arduino" question since it is about stuff not directly about the Arduino boards or code that is running on them. I think a more electrical engineering forum is where they want questions like this. But while it is here I will try and give you an answer. One thing, there are no protection diode for the mosfet. I think you need to draw the negative paths for the circuit. It really doesn't make sense.

Each controller / regulator board has a + and a - input, the merging is simply the way in which visio represents it, they never merge except on the boards.

You show them merging and then connected to a mosfet. And that is meaningless. If you want to know if anything is wrong you need to clearly show how the circuit is connected. I design electronics for a living. 30+ year. What you have shown is nothing anyone can work with.

Maybe start with the boards. Then draw wires that show the connections to the terminal blocks/connectors on those boards. Use one color for + and one for -. (red and black are my favorites)

I've updated the schematic image, I hope this is more understandable. Red is positive, black is negative (ground) and the blue one is a data wire from the controller. Does this make sense ?

Do you have specific question, so that this would fit into the Q&A style of this site?

The connections for the regulator input (upper right) is reversed, just a drawing error, I'm sure you connect it right. It all looks OK but I would like a link to the PWM board. I don't know what the terminal block on the left is. Currently unused. IN, Out, but for what I don't know.

I've updated the question and schematic with more detail and specific questions. Feel free to post an answer :)

OK. Looks much better now. And I see one problem. It seems that the normal way to do the speed control is with a pot. A variable voltage at the input depending on the rotation. The Arduino low end designs have an analog out capability but it really is not analog. It is a pulse width variable signal that produces an on percentage between 0 volts and the CPU positive supply voltage. The boards do not have a real digital to analog converter. (maybe some higher end boards but not boards based on the Uno CPU.
It may still work but you need to integrate the pulse output and produce a real analog output voltage. A resistor on the output connected to a capacitor to ground will do the integration and filter out the pulses.

See http://www.ontrak.net/pwm.htm for more details.

The problem you might encounter is to much loading on the capacitor by the pot input circuit. Without more details about the module I couldn't say. The signal can be buffered with an amplifier but that adds to the complexity. Still would be doable though.
Or you can add a real digital to analog converter to the Arduino board. That would be my preference rather than having to add a buffer amplifier if a simple RC circuit wasn't good enough.
Do you have a link for that board?
From the picture of the linked speed module. It uses a LM324 opamp to generate the PWM signal. I did a quick look and found a typical circuit.

http://www.pcsilencioso.com/cpemma/graphics/erg_pwm_sch.gif
Typical but not the exact one. It is much as I expected. And if you did the RC only filtering then it may just work. The opamp input would not be too much loading on the capacitor. The concern that I have is that the 5 volt maximum from the Arduino may not be high enough to turn the motor on at its maximum value.

DC Motor Controller: https://www.banggood.com/PWM-DC-Motor-Speed-Switch-Controller-Control-Reversible-Regulator-p-912617.html?rmmds=search&cur_warehouse=CN

Voltage Regulator: https://www.banggood.com/LM2596-DC-DC-Voltage-Regulator-Adjustable-Step-Down-Power-Supply-Module-With-Display-p-1005123.html?rmmds=search&cur_warehouse=CN

I updated the answer.


text:
Coding force sensitive resistor to give output based on time used?
I have a basic set up of having a force sensitive resistor being used to power an LED as can be seen below. I am wondering how I can code it so that the LED is lit after a pressure has been applied to the FSR for a specified amount of time. Leading on from that I would like to use an RBG LED and have it so that after specified intervals on continuous pressure the LED changes colour.
Any advice would be greatly appreciated.
//Constants:
const int ledPin = 3;     //pin 3 has PWM funtion
const int sensorPin = A0; //pin A0 to read analog input

//Variables:
int value; //save analog value

void setup(){

  pinMode(ledPin, OUTPUT);  //Set pin 3 as 'output'
  Serial.begin(9600);       //Begin serial communication

}

void loop(){

  value = analogRead(sensorPin);       //Read and save analog value from potentiometer
  Serial.println(value);               //Print value
  value = map(value, 0, 1023, 0, 255); //Map value 0-1023 to 0-255 (PWM)
  analogWrite(ledPin, value);          //Send PWM value to led
  delay(100);                          //Small delay

}

You'll need to declare a variable to hold the start time (millis()) of when the force has exceeded the threshold.
You'll need to declare a constant to hold the threshold value (with analog data, you likely don't want to have your pressure threshold be "anything greater than 0", because noise and other things like small vibrations will trigger.
Also declare a constant to hold your "hold-off time" in milliseconds.
In your loop(), when you have an analog value that exceeds the pressure threshold, store the value of millis(). Also in your loop(), when the current millis() minus the start value  is greater than the "hold-off time", activate your LED.
For RGB, same setup, but you can set your color based on how much greater the time difference is than the hold-off time.


text:
How do I fix this error? It says "warning: invalid conversion from 'long int*' to 'long int' [-fpermissive]
I am working on an assignment that converts a reading of force into pounds and then finds the maximum and average of all the values received
This is my code:
void setup()
{

 // put your setup code here, to run once:

 Serial.begin(9600);

  // declare the outputs and inputs
  pinMode( 0 , INPUT);

  //figure out what pin the reading is going to be input to

  fsrReading = analogRead( 0 ) ;
  //the # is the same pin used to get input

  //or use analogRead ( # ), it depends if the pin input is on the analog side of the arduino

  // should this be under the while loop or here?

  //list functions here
  long ForceInPounds(long);
  long FindMax(long);
  long FindAvg(long);

  //declaring variables of functions
  FM = FindMax(new long);
  FA = FindAvg(new long);

        Serial.println("The max value is:");
        Serial.println(FM); //calls FindMax function

        Serial.println("The average value is:");
        Serial.println(FA); //calls FindAvg function

  }

void loop()
{
  // put your main code here, to run repeatedly

 int counter1= 0;

  while (counter1< 100)
  //runs test 100 times

  //should I just make this a function? instead of embedding it in the void loop

 {
      Serial.print("Analog reading = ");

      Serial.println(fsrReading);

      //declaring variable of function used in this segment
      FiP = ForceInPounds(new long);

      Serial.print("Force in Newtons:");
      Serial.println(FiP); //calls ForceinPounds function

      counter1 ++;
  }

}

//FUNCTIONS

long ForceInPounds(const long)
// converts recorded voltage to resistance to conductance to force to pounds
{
 fsrReading = fsrVoltage;

 if (fsrVoltage== 0)
 {
   Serial.print("No pressure");
 }
 else
 {
   fsrResistance = 5000.0 - fsrVoltage;
   //convert voltage to resistance
   fsrResistance *= 10000.0;
   fsrResistance /= fsrVoltage;
   fsrConductance = 1000000.0 ;

   //convert resistance to conductance
   fsrConductance /= fsrResistance;
   if (fsrConductance <=1000.0)
   //convert resistance to conductance
   {
     fsrForce = fsrConductance/80.0;
   }
   else
   {
     fsrForce = fsrConductance - 1000.0;
     fsrForce /= 30.0;
   }
   fsrPounds = fsrForce/4.45;

   //convert force to pounds
 }

 return fsrPounds;
}

long FindMax(long)
{
  int counter2 = 0;

  while (counter2 < 100);
  {
    if ( fsrPounds > maximum)
    {
          maximum = fsrPounds;
          counter2++;
    }
    else
    {
          maximum = maximum;
          counter2++;
    }

  }
  return maximum;

}

long FindAvg (long)
{
  long start = 0;
  //variable to begin avg function
  long avg;
  int counter3 = 0;

  while (counter3 < 100);
  {
    start = start + fsrPounds ;
    counter3 ++;
  }

  avg = start/100;
  return avg;
}

What am I doing wrong? This is my first time working with Arduino.
Thanks

There are several problems with the code, and I can't reproduce the errror you gave with the code you gave. Is this the actual/real code you are getting this error with? Are you using the Arduino IDE?

Please post your entire code, or at least a Small Self-Contained Compilable Example.

I just added the rest of the code. Thank you. And yes, I am using the Arduino IDE.

This is most likely not what you want to be doing
//declaring variables of functions
FM = FindMax(new long);
FA = FindAvg(new long);

And it is entirely incompatible with these definitions
//list functions here
long ForceInPounds(long);
long FindMax(long);
long FindAvg(long);

With the result that you pass a pointer to a long (ie, its address in memory), to a function which is instead expecting the value of a long.
However, it's going to be hard to propose a solution until you edit the body of the functions into your question.
There's probably no reason to use new here at all - let the functions allocate their own temporary variables on the stack, since they seem to return a value rather than a pointer.  Most likely even if this worked, the new long you create would be abandoned - ie, a memory leak.

Thank you Chris, I just added the rest of the code for review. Thank you.

There are several fundamental problems with the code. It appears your understanding of function declaration, definition, and usage are not accurate.
This part:
  //list functions here
  long ForceInPounds(long);
  long FindMax(long);
  long FindAvg(long);

Is unneccesary.
setup() is not the place to declare function variables:
  //declaring variables of functions
  FM = FindMax(new long);
  FA = FindAvg(new long);

If your functions use variables internally, the place to declare them is within the function definition.
In your FUNCTIONS section, you start off defining this function:
long ForceInPounds(const long)

The first long declares that the function will return a long, and the (const long) would normally declare what variable types your function accepts as parameters, as well as the name(s) of said parameters. You have only provided a type long, and a modifier const, but no name. It doesn't make sense to pass in a const variable anyway, as the const indicates the content of the variable will never change from the initial value. In your code, not only is the variable not named, it is not given an initial value.
Within that ForceInPounds() function, you start with:
  fsrReading = fsrVoltage;

which overwrites your initial fsrReading = analogRead(0); with an undefined value, as you have neither declared a type for fsrVoltage, nor given it an initial value.
Also, you call analogRead(0) once in setup, so it only captures the value once. The fsrReading variable is not continually updated with the analog reading. You have to keep calling analogRead(0) and storing it in a variable each time through your loop.
There are other problems with the code, but these are a few of the fundamental problems. There is no simple/quick fix to your code.
If you don't come from a C or C++ background, you may want to read a quick overview of them, at a minimum. Start with some of the Arduino example sketches and get a good understanding of how functions are defined and how they work.


text:
CurieBLE receive data without pairing
I read exist articles about it, but still not understand how to do that.
I have a Genuino 101 and an EEG Headband (neuro interface). Need to get data from neuro device. With external HC-05 bluetooth module the code look like this:
 SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
 bluetooth.begin(57600);
 while (!bluetooth.available()) {}
 byteRead = bluetooth.read();

Has anyone encountered a similar problem?
Thanks!

what problem are you referring to?

The code above will only read one byte

@dandavis I want to get one byte using BLE without pairing

HC-05 module is not BLE (Bluetooth 4.0)! HC-05 implements SPP (Serial port profile) over Bluetooth Classic (Bluetooth 2.0). You will need a module with BLE capability and that is not over yet. BLE implements several (hundred) profiles for each task such as heartrate monitor, neuro monitor, time etc etc. Your BLE module must be condigured to receive a specific profile data.

Thank you for the explanation.
So without SPP and detail configurations for BLE I can't receive data from neuro?

Seems like not :(


text:
Digital Band pass filter on Arduino
I am working with sensors on Arduino and would like to filter the sensor's output to a certain band of frequencies.
I found many examples online on how to implement simple digital low-pass filters in Arduino code, but not for band pass filters.
Is it even possible to achieve this in the scope of an Arduino program?
If anyone can share some tutorial for this, that would be much appreciated.

On an Arduino I would be tempted to do it in hardware. You really need a DSP to do filtering like that.

See http://www.iowahills.com/Example%20Code/WindowedFIRFilterWebCode.txt from http://www.iowahills.com/A7ExampleCodePage.html

A band pass filter simply means that it a filter between a certain interval of frequencies thus it can be made from a high pass filter and a low pass filter
e.g. this fact is mentioned here http://www.electronics-tutorials.ws/filter/filter_4.html
as well as lots of other web pages which a search by you can find.
So yes a band pass filter can be implemented on arduino if you can implement the corresponding high pass and low pass filter too.

The link you posted leads to analog filters where i specifically asked about ones implemented within the Arduino code, im afraid it is not relevant.
if i were to somehow implement both a low pass and a high pass filter separately in an arduino program, ill just lose both my high and low frequencies as they will both get filtered out.

Its easy enough to find the defintion of a band pass filter by a simple search which you can do

for a more relevant link

Sounds like you need to use two arduino (or at least two different signal filter circuits) to make a band pass filter

you implmented a low pass filter, you merely have to implment a high pass filter then combine the two to get a band pass filter.


text:
Would an Arduino Uno be suitable for a simple time-based locking circuit?
Background: I'm looking to start on my first real electronics project and I have an Arduino Uno I bought a while back. I've only done a few of the starter Arduino tutorials and that was a while back as well. Starting from very little electronics knowledge, I'm trying to get a bit of advice on how to tackle my first project.
TL;DR: I have an Arduino Uno but very little experience with it or electronics.
Project: I want an object that locks, I want the duration of the time it stays locked for to increase by ~1-3% every time it locks. I want to put my nicotine products in there to gradually pull myself off nicotine. I have designed a rough 3D model of the box, which I can 3D print so now I'm looking at the electronics.
TL;DR: A box which stays locked for longer, every time it locks.
Electronics: A microcontroller/Arduino/Pi to increase the locking duration; a locking circuit and some form of power supply.
My 2 questions are

Would the Arduino Uno be suited to this type of project?
What sort of components should I be looking for for the locking circuit and power supply (I'm thinking some sort of solenoid actuator and a battery pack)?

Sounds like an excellent project to use an Arduino for. I was thinking about using a servo, but a solenoid will work too. I probably would try to avoid using batteries. It's very hard to make an UNO not use a lot of power. And you probably want it to run for weeks.

Short answers: 1) yes, even if smaller boards are "more" suitable IMHO (but just for aesthetics); 2) power supply: usually I use a 5V USB charger, but any is fine. I suggest you not to use batteries (they tend to discharge...). actuator: a solenoid (with a transistor) is fine, or an RC servo (which complicates a bit the mechanics but is simpler in the electronics project)

@Gerben I usually avoid writing double comments, but I didn't see yours before posting ;) Sorry

@frarugi87 there is some value added by your comment.

An Uno is ideal for prototyping, but it's too power-hungry for the final thing. I recommend you go for a plain AVR microcontroller, aka “barebones Arduino”, and have a look at Nick Gammon's tutorial on power saving.

@EdgarBonet I started using the arduino pro mini boards for the "low" power applications. It lacks the USB interface and excluding the power led you get exactly the same circuit as the barebone one; barebone allows you to choose a different clock speed, so you can save a bit more power, but IMHO it is better to just switch to another microcontroller if you need a real power saving. However a pro mini board usually costs less than the bare microcontroller (and you have to solder the uc)... Then, if the power supply is not a battery using 20mA more is not a big deal, so even the uno is fine

Thank you all for your answers, they're really informative. I will definitely prototype the setup on my arduino uno. Good to know about the batteries, I shall have to see about either a usb cable to outlet or computer. And thanks for the advice on the locking mechanism, I might go for the servo over the solenoid (as a mechanical engineering student).

It is a great occasion to use the Arduino!
There are many tutorials for the Arduino out there, so thats a good place to start. This forum is a good place to ask any Arduino related question if you need to do so.

The following contains MY OPINION
In my opinion, an Arduino Nano would be great for this project. It is really user friendly and can pretty much accomplish many things. A Pro Mini would be better, but seeing sa you're a beginner, stick with the Nano.
A good long lasting batteRY would be a simple USB power bank. It outputs 5V and has a lot of juice. For a locking circuit, a simple servo would work IF THE THINGS THAT IS IN THAT "SAFE" ISN'T 1M $$. A servo does a decent job as a lock.

Good luck!

Thanks for the advice. I think I will use the Arduino Uno simply because I have it laying around and I'm not a stranger to programming. I'd not thought of using a power bank, thanks for the tip. I'm not trying to build something super secure so I don't think safe is the right word. I just want it to be more of an inconvenience to hack it open than to wait for the timer to run out.

Regarding your second question about what components to use, there are a couple arguments for a servo over a solenoid.
A solenoid in the energized state is relatively power hungry compared to a servo, which only requires any appreciable power while actually moving. Also, on power loss or interruption a servo fails as-is; a solenoid goes to the off position, which could cause an unwanted change of state for the lock.


text:
POE with Arduino Leonardo Eth
I recently purchased a Leonardo Eth and a 5v POE module in an attempt to have a POE micro-controller.  I installed the module in the holes closest to the Ethernet jack side of the board, but when I apply power, the green power light turns on every second or so, but never fully turns on.
What am I doing wrong? Did I install the module wrong? Is it the wrong module?

So you have PoE injector with 36V to 72V power supply? (I suppose 48V ones are most common as 24V is out of range for your PoE Module)

I have a PoE 48v 802.3 af switch

Have you verified that your terminations on the cable are good, and you are getting the necessary voltage at the Arduino end of the cable?  Once that is verified, check the output pins of the POE module, verify the necessary voltage, and if possible, hook a scope up to it, and watch what is happening.

POE switch and cable work fine, as I can power other POE stuff with it.  I measured the output voltage of the device and it was very unstable.  I think I will just buy a different module.

From the arduino.cc website.
"The optional PoE module is designed to extract power from a conventional twisted pair Category 5 Ethernet cable. PoE module features are as follows: IEEE802.3af compliant Input voltage range 36V to 57V Overload and short-circuit protection 12V Output High efficiency DC/DC converter: typ 85% @ 80% load 1500V isolation (input to output)"
It sounds like you need the 12V PoE module


text:
Writing data from multiple sensors in burst mode to an Arduino Due
I need help developing a simple sketch that can read data simultaneously from 3 analog accelerometers and send it in 'burst mode' to be stored on an SD card, to reduce the effect of latency.
I used this library to get my accelerometers to work properly, but I'm just having difficulty coming up with a sketch in the code to getting all the acceleration data out in bursts.
Your help will be much appreciated.
What I meant by 'burst mode' is that all acceleration data from all three sensors connected to the Arduino should be saved at once to the file on the SD card (a temporary measure, as I'll have to send this data via Bluetooth to a base station as I build the system up to be able to receive more data from multiple Arduinos).
Although there would be a delay of about 1/10th of a second between each reading from the three sensors, the idea behind it is to be able to read and write off the data in this said simultaneous burst mode at a high sample rate (this will be adjusted with an oscilloscope at a later stage) to prevent data from being lost or chunked up.
Here is a link to the datasheet as requested.

We really need more information here - what does burst mode mean? Could you add a link to the accelerometer datasheet? Please do this by editing the original answer, not by adding a comment as this makes the question hard to read.

I'm not sure what the difficulty here is. You read some sensors, gather the data, and then write a line of text to a file, right?

Yes that's the basic idea. But i found out that I started to loose data as I added additional MMA7361 sensors to the sketch, so the advice I got was to edit my sketch in order for me to send of each set of data in 'bursts' before the current data is read thereby emptying the memory of any data to avoid errors resulting from data accumulation. I used the delay feature to ensure that all the data are read and sent before a new set is read again, but increasing the sampling rate of the board results in the present state of the sketch, large data chunks lost over a period

What you need to do instead is to declare an array buffer of the data type you need to send, and send it through Serial. The array buffer could be of any length of your choosing, then you reiterate through on a for loop till all the contents of the buffer are read out which is essentially the burst mode you require.


text:
Weird sketch size/memory/compiler (?) related issue (hanging, RX led on)
Also posted at: https://forum.arduino.cc/index.php?topic=549672.0
is there anyone who experienced similar problem or knows a solution to it?
The problem is that after uploading the code Arduino Pro Micro hangs (and RX led is constantly on).
The problem occurs instantly after turning on the microcontroller even if I put "delay(10000);" at the begining of the code trying to see at which point the error occurs.
The problem can be "fixed" by adding 'Serial.print("aa");' at random place within the code...
Which results in the following output during upload:
Sketch uses 18318 bytes (63%) of program storage space. Maximum is 28672 bytes.
Global variables use 1814 bytes (70%) of dynamic memory, leaving 746 bytes for local variables. Maximum is 2560 bytes.

Suprisingly, using 'Serial.print("a");" instead does not fix the problem. It results in the following output during upload:
Sketch uses 18314 bytes (63%) of program storage space. Maximum is 28672 bytes.
Global variables use 1810 bytes (70%) of dynamic memory, leaving 750 bytes for local variables. Maximum is 2560 bytes.

It seems very weird to me that adding serial print instruction with certain length (at seemingly random place) can solve such problem...
Another circumstance which seems to be solving the problem is commenting out one of the 2 lines (does not matter which):
sprintf(at_cmd, "AT+NAME%s\0", bluetoothName);
sprintf(at_pin_cmd, "AT+PIN%s\0", pin);

It's a spaghetti code so I doubt anyone will analyse it but just in case if anyone wanted to check it for some more or less obvious characteristic (e.g. F()/eeprom/memory extensive use or something...) then here it is: Hastebin - link
I'm using "Arduino Pro Micro 5V" and Arduino IDE 1.8.5 with "Arduino Leonardo" board setting

You should make more use of PROGMEM for your string constants.  Use the _P variants of the string library functions.

You may want to look up how to use PROGMEM, That will let you move your arrays and global string literals to program space instead of taking up RAM

Does the only occur after uploading a new sketch or also after pressing the reset button or power-cycling?

Thanks for suggestion, but what do you guys think about the potential cause of the problem which I described?

@Gerben It happens after unplugging and plugging it back too. Not only after uploading.

Most strange hangings are caused by lack of RAM or buffer overruns. Using PROGMEM will help if it's the former that is the cause. It may also help you find where a buffer overrun is while you refactor your code.

Also asked here: http://forum.arduino.cc/index.php?topic=549672.0

Your description of the fault that goes away with some random print statement placed anywhere smacks of a buffer overrun somewhere in your code.

@Delta_G Wouldn't the code at least run until that overrun moment in such case? That's why I tested "delay(10000)" at the begining of setup function and realized it was not executed at all.

No.  An overrun causes undefined behavior.  That means it could fail at boot or when it gets to a certain line or it could make little demons fly out from your nose.   Anything goes with undefined behavior.


text:
Increase sample rate in ESP32 board
For my final project on the university as a Systems Engineer, I'm working on a "electronic stethoscope", which is giving me a lot of headaches.
I bought a Adafruit Feather ESP32 Huzzah (https://learn.adafruit.com/adafruit-huzzah32-esp32-feather/overview) which has a dual core processor that works around 240 MHz of speed, it has support of wireless communication with Bluetooth classic (which is the one I'm using) and also works with the I2S protocol.
That is the reason why I bought an I2S MEMS Microphone SPH0645 (https://www.adafruit.com/product/3421), which according with its documentation works under 50Hz-15KHz.
As a first approach, I thought that it would be enough, but I'm getting a very slow sample rate that is around 800 samples per second. With these values, I can't reproduce any sound with the expected quality.
On the other hand, since the ESP32 has not a high level library to interact with I2S such as ArduinoSound I had to create my own code based on the specification (https://esp-idf.readthedocs.io/en/v2.0/api/peripherals/i2s.html).
My code on the Arduino IDE looks like this:
#include "libraries/SmappioSound/SmappioSound.cpp"
#include "BluetoothSerial.h"

int *buffer;
BluetoothSerial serialBT;
int value = 0;
int framesRead = 0;

SmappioSound smappioSound(6835); //value for stabilization

void setup() {
  // put your setup code here, to run once:

  pinMode(DATA_PIN, INPUT); // Supuestamente necesario para que no haya ruido
  serialBT.begin("smappio_PCM");
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  smappioSound.begin(buffer);
}

void loop() {

  //gets the amount of bytes readed from the buffer.
  framesRead = smappioSound.read() / I2S_BITS_PER_SAMPLE_32BIT;

  for(int index = 0; index <= framesRead; index++)
  {

      value = smappioSound.getSampleValue(index);
      if(index % 2 == 0)
      {
          serialBT.print(String(value) + ",");
          Serial.println(value);
      }
  }
}

The SmappioSound.h library is where the interaction with I2S occurs.
The configuration for i2S is the following:
#pragma region // Sección de Configuración
  static const print_mode_t PRINT_MODE = BYTES;                                   // Tipo de impresión: BITS | BYTES | INTEGER | FULL_DETEAILED
  static const bool PRINT_BOTH_CHANNELS = false;                                    // Indica si imprime solo el "Canal 0" ó el "Canal 0" y el "Canal 1"
  static const int FRAMES_REQUESTED = 1;                                           // Parece relacionarse con la cantidad de buffers
  static const int TICKS_TO_WAIT = 0;                                            // Investigar
  static const i2s_bits_per_sample_t BITS_PER_SAMPLE = I2S_BITS_PER_SAMPLE_32BIT;   // Datasheet: 24. Ejemplo: 32.

  static const i2s_config_t SPH_CONFIG = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),                                            // El controlador es el Maestro y Recibe, el microfono es Esclavo y Transmite
    .sample_rate = 32000,                                                                           // Entre 32KHz y 64KHz (Datasheet)
    .bits_per_sample = BITS_PER_SAMPLE,
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,                                                   // El formato que usa el micrófono. No se encontró el Datasheet
    .communication_format = (i2s_comm_format_t) I2S_COMM_FORMAT_PCM,    //(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB) // Investigar
    //MSB: most significant byte -> BIG ENDIAN
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,                                                       // High interrupt priority (investigar)
    .dma_buf_count = 2,                                                                            // Cantidad de buffers, 128 max.
    .dma_buf_len = 32 * 2                                                                           // Tamaño de cada buffer
  };

#pragma endregion Sección de Configuración

As you can see, I'm trying to get 32KHz as sample rate with 32 bit-depth (not working for 16, and 24 bits), and I'm setting 115200 baud-rate in the Arduino IDE.
On the other hand, I created a .NET Winforms application that is receiving the generated PCM values over bluetooth 4.0. After 1 second is giving me only 693 samples which is very few.

Can I reach at least 20KHz as sample rate with these hardware components? Do you see something wrong in my code?

Serial is slow. Very slow. You can't do audio over it like that.

Thanks Majenko. What hardware component can you recommend for streaming audio with high quality?

Usb with isochronous transfers.

I don't get it. Are you using Bluetooth or USB-UART serial as a transmission medium? Because you transmit the values on both channels.

I want to transfer only 1 channel. I just saw that I can use channel_format = I2S_CHANNEL_FMT_ONLY_LEFT to send only mono. I'm using Bluetooth as a transmission medium.

Here's a few tips on optimization.
  for(int index = 0; index <= framesRead; index++)
  {

      value = smappioSound.getSampleValue(index);
      if(index % 2 == 0)
      {
          serialBT.print(String(value) + ",");
          Serial.println(value);
      }
  }

Doing
          serialBT.print(String(value) + ",");
          Serial.println(value);

is very wasteful. First of all you're debug-outputting every value as an ASCII string to Serial, second you're doing the same thing over serialBT with an additional ,.
It's wasteful because:

your baud rate is extremely low (115200 on Serial)
converting every value to ASCII will induce an overhead

Your int value is 32 bits / 4 bytes which may take arbitrary values. Say the value is at its positive max at 0x7fffffff = 214748364. Then transmitting the ASCII string will take 9 bytes (10 bytes for largest negative value), sending the raw binary value will always take 4 bytes. Thus you should always send your samples in raw binary format, not converted to an ASCII String.
At a wanted sampling rate of 32KHz with 32-bit values, you'd need an effective bit rate of 32000*32 = 1,024,000 Bits/s. Your Serial on which you are also printing every 2nd value, is on 115,200 bit/s (and you'd still have to account for the UART overhead, aka start and stop bits for every 8 data bits!).
Depending on the quality of the USB-UART converter on your board (FTDI, CP2102: good, CH340: bad), you can actually get to over 1 megabaud. The ESP32's UART periphal will allow you to set whatever clock divider you want to divide the 80 MHz APB clock (source, chapter 13.3.2). ESP-IDF has the UART_BITRATE_MAX defined to 5,000,000 (source), and since Arduino-ESP32 derives from ESP-IDF, that should be possible there, too.
As I said, the USB-UART adapter between the ESP32 and your PC is critical. It has to support such a high speeds with a sufficiently large TX/RX buffer. The max baud rate of a CP2101 is 921600 (source), an FT232RL (source) up to 3 megabaud.
In general you don't want to give your sample values to the peripheral value-wise. Both your Serial and your BluetoothSerial have the possibility to enqueue a whole buffer at once (source). I don't know the real underlying implementation where the final samples will be stored (and held stable for a while) but you might just be able to do
framesRead = smappioSound.read() / I2S_BITS_PER_SAMPLE_32BIT;
serialBT.write((uint8_t*) buffer, framesRead * sizeof(int32_t));

to send the whole buffer at once. You'd also have to check how to handle or set the transmission speed on the bluetooth peripheral. I don't know much about the ESP32's BT / BLE radio to answer that.
Speed on a UART adapter could further be advanced to a non-blocking DMA backed variant. Since both I2S and the UART periphal support DMA transfers. Thus, the maximum transfer speed would be reachable.
Another posisbility would be to change the transission medium. You could have your ESP32 join a WiFi network and transmit its audio buffers via UDP or TCP to some server listening on the PC. I think however Bluetooth and UART (with the right tweaks) would also be possible.

Thanks a lot Maximilian, I will check all the details of your response and I'll let you know how it goes.

The CH340 hardware can send with baud rates up to 3 MBaud (unfortunately with 6 stop bits). For details please read my CH341 baud rate calculation HOWTO at https://github.com/nospam2000/ch341-baudrate-calculation


text:
generate two phase-shifted PWM pulses triggered by frequency-divided external signal with Arduino uno?
I have a 4kHz pulse as trigger and I need two phase-shifted PWM output with divided frequency from arduino uno.
Now I've managed one PWM output using the following code:
int cnt = 0;
void setup() {
  pinMode(3, OUTPUT);
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
}

void loop() {

}

void rising_edge() {
  cnt = cnt + 1;
  if (cnt >= 4) {                           //divide by 8
    digitalWrite(3,(digitalRead(3)^1));
    cnt = 0;
  }
}

As suggested by Majenko♦, I tried using Timer1 lib, but the phase shift is always 15us, regardless timer1 period.
#include <TimerOne.h>

int cnt = 0;

void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, INPUT);
  Timer1.initialize(10000);
  Timer1.attachInterrupt(ISP_T1);
  attachInterrupt(digitalPinToInterrupt(2), ISP_INTx, RISING);
}

void loop() {

}

void ISP_INTx() {
  cnt = cnt + 1;
  if (cnt >= 4) {
    digitalWrite(3,(digitalRead(3)^1));
    cnt = 0;
    Timer1.start();
  }
}

void ISP_T1() {
  digitalWrite(4,(digitalRead(4)^1));
  Timer1.stop();
}

Shift should be arbitrary value between 0-1 x period (depends on divider)
Adjustable duty is preferred but not necessary.

Phase shifted by how much?

0-1 x period, which depends on the divider (integer)

So you want a variable phase shift then? That makes it harder.

For this question, fixed phase shift is fine. I can listen serial port on loop function and reassign registers later.

If you can live with a fixed duty cycle of 50%, then you could set Timer 1 to mode 4 (CTC with TOP = OCR1A), put both outputs into toggle mode, and use OCR1B to control the phase shift. No interrupts, no involvement of the CPU once the timer is set up. The tricky part would be selecting between the phase shifts φ and φ+π. For that, TCCR1C could help.

I think your first example is very close. What about:
int cnt = 0;
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
}

void loop() {

}

void rising_edge() {
  cnt = cnt + 1;
  if (cnt >= 4) {                           //divide by 8
    cnt = 0;
  }
  switch(cnt){
    case 0: digitalWrite(3,HIGH);break;
    case 1: digitalWrite(4,HIGH);break;
    case 2: digitalWrite(3,LOW);break;
    case 3: digitalWrite(4,LOW);break;
  }
}

Assuming a uniform input frequency, pin 3 will be 90 degrees out of phase with pin 4. You could make this adjustable if you don't mind a larger divider by expanding the switch/case to eg 6 or 8 steps.
You could get more steps by triggering on rising and falling edges (although that may not give uniform phase if the incoming PWM is not at 50% duty cycle.

If I understand correctly, it uses timer0 for interrupt and CPU for counting.

No, it doesn't. The interrupt is an interrupt. Timer0 is a timer.  At the moment you just have an external interrupt triggering an ISR which adds to a variable and toggles an output.
Timer0 is used to drive millis() and delay().
What you need to do is set up a timer (not Timer0 since it's already reserved) which will time out with a period equal to the time difference of the phase shift.  Start it in your existing ISR (when the output is toggled), and in the timer's ISR stop the timer and toggle the second output (or set it the same as the 0° output).
You may find the TimerOne library helpful for this.

But why timer0 functions doesn't work with attachInterrupt ?

timer0 has nothing to do with attachInterrupt.

link  here it says 'Inside the attached function, delay() won’t work and the value returned by millis() will not increment'.

That is correct. the Timer0 ISR won't run while the INTx ISR is running. But that has nothing at all to do with your question, so why are you asking?

I tried setting up Timer1, but the shift is always 15us.


text:
I keep getting an error message and I don't know how to fix it
I am using an Arduino Genuino, this is what comes up
Multiple libraries were found for "LiquidCrystal.h"
 Used: /home/user/Arduino/libraries/LiquidCrystal
 Not used: /opt/ArduinoIDE/libraries/LiquidCrystal
In file included from /home/user/Arduino/libraries/dht/DHT_U.cpp:22:0:
/home/user/Arduino/libraries/dht/DHT_U.h:25:29: fatal error: Adafruit_Sensor.h: No such file or directory
 #include <Adafruit_Sensor.h>

                             ^
compilation terminated.
exit status 1

what do you understand about what the message is telling you?

The first notice about multiple libraries is not stopping you. The DHU library relies on the Adafruit Unified Sensor Library
You should have the following libraries (installed and) included:
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>


text:
How to increase the volume in speaker using talkie library in arduino uno...?
What else should I add to this code to increase the volume..??
#include "talkie.h"

Talkie voice;
const int8_t speech[] PROGMEM=
{0x00,0x00,0x00,0x08,0xd8,0x39,0x54,0x00,0xa7,0xa6,0x32,0xe0,
0x04,0x46,0x55,0x28,0xde,0x53,0xaa,0xa9,0x42,0xe9,0x69,0x95,
0xbb,0x4f,0x4c,0xa5,0xe7,0x51,0x15,0x5e,0x31,0x94,0x91,0x49,
0xee,0xa8,0xc5,0x50,0x45,0x2a,0xb9,0x13,0x02,0x43,0xad,0xb9,
0xf7,0x9d,0x0b,0x76,0x35,0x17,0x31,0xb7,0x46,0xd8,0x35,0x96,
0x69,0xdf,0xb8,0x60,0xd3,0x54,0xc0,0x31,0x97,0xa2,0x14,0xf0,
0x27,0xa3,0x02,0xfe,0xbb,0x52,0xc0,0x3f,0x3b,0x0a,0x38,0x79,
0x42,0x00,0xbb,0xb4,0x2b,0x60,0x06,0x43,0xd7,0x65,0x4e,0xde,
0xe9,0xa5,0x52,0x1f,0x94,0x56,0x58,0x84,0x2c,0x7d,0x34,0x9e,
0xe6,0x15,0xb0,0x0d,0xd1,0x87,0x8b,0x77,0xc8,0xd4,0x87,0x58,
0x4e,0x5e,0x11,0x52,0x1f,0x7c,0x17,0x78,0x95,0x0c,0xbd,0x77,
0xdd,0x60,0x55,0xc1,0x75,0xce,0x6c,0x13,0xd7,0x04,0xd7,0x05,
0x91,0xc3,0xec,0x33,0x44,0x67,0x79,0x0c,0x53,0x34,0x02,0x04,
0xec,0xe4,0xcc,0x80,0x9d,0x53,0x10,0x30,0x05,0x13,0x69,0x3a,
0x26,0xce,0xb4,0xd4,0xaa,0xc9,0x48,0xa3,0xc2,0x1a,0xa4,0x2e,
0xb0,0xa8,0x76,0xab,0xe0,0x3a,0xab,0xb2,0xda,0x24,0x02,0x1a,
0x89,0x9e,0x74,0x33,0x07,0x80,0x80,0x95,0xcd,0x19,0x30,0x9d,
0x85,0x00,0xba,0xf6,0x14,0x25,0x0f,0x9d,0x6a,0x5e,0xc1,0x95,
0x22,0x75,0x48,0x46,0x88,0x54,0xba,0x10,0xa1,0xd9,0x25,0x53,
0xe9,0x62,0xb8,0x77,0x95,0x0c,0xa5,0x4e,0x69,0x39,0x16,0x31,
0x94,0xaa,0xba,0xe5,0x48,0x2c,0x57,0xda,0x26,0xda,0x23,0x0d,
0x5d,0xe5,0x1b,0x7b,0x8f,0x34,0x72,0x75,0x28,0x14,0xd5,0xd2,
0xd0,0x34,0xa9,0xa1,0xe5,0x48,0x43,0xd5,0xa6,0x8a,0x96,0x23,
0x09,0x55,0x97,0x2a,0xa9,0xad,0xc4,0x52,0x5d,0x0e,0xaa,0xbc,
0xd2,0x58,0xf4,0xd5,0xa9,0x41,0x46,0x1c,0xf2,0x0f,0xc3,0x2a,
0xc2,0x8d,0xc9,0x3f,0x93,0x99,0x12,0x26,0x46,0xc0,0xca,0xa2,
0x00,0x00,0x00,0x0f};
const int ProxSensor=2;
int inputVal=0;

void setup() {
  pinMode(13,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(ProxSensor,INPUT);
  Serial.begin(9600);
  // put your setup code here, to run once:
}

void loop() {
  if(digitalRead(ProxSensor)==HIGH)
  {
    digitalWrite(13,HIGH);
  }
  else
  {
    digitalWrite(13,LOW);
  }
  inputVal=digitalRead(ProxSensor);
  Serial.println(inputVal);
  if(inputVal==0)
  {
    digitalWrite(7,HIGH);
    //digitalWrite(8,HIGH);
   // voice.say(speech);
    //delay(3500);
    //exit();
  }
  else
  {
    digitalWrite(7,LOW);
    //digitalWrite(8,LOW);
  }
  if(inputVal==0)
  {
    voice.say(speech);
    delay(2500);
    //exit();
  }

  // put your main code here, to run repeatedly:

}

In this youtube video an amplifier was added.

Is this you? https://github.com/going-digital/Talkie/issues/30

Your sample values (that is, the speech[] array) range from 0x00 to 0xfe, using 99.6% of the total range of possible values.
Thus, there is no software solution to increase the volume, as you are only 1 bit away from the maximum output level (0xff is the max, and one less is 0xfe).
This requires a hardware solution. One easy way is to use a commercial audio amplifier or a powered speaker (a speaker with a built-in amplifier).