text:
Inaccurate voltage readings on an esp32 as opposed to multimeter
I am working on detecting the amplitude of a signal coming from a guitar pickup. I am using an esp32 and an LM386 module for amplifying the signal.
I get quite stable readings with a multimeter, but the readings on the Arduino IDE show peaks and also peaks come when no signal should be there.

Here is a link for short videos of both the esp32 readings and the multimeter:
https://drive.google.com/drive/folders/1gpvkN_sz627jG0TNPpUps82105EB89OF?usp=sharing
Thanks!
EDIT (Adding simple code being used) :
int ampedVoltagePin = 12;

void setup() {
  pinMode(ampedVoltagePin, INPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println(analogRead(ampedVoltagePin));
  delay(100);
}

EDIT (Adding diagram):

And what happens, if you take the average over a longer time and show that? Because thats, what a multimeter does. My multimeter seems to average over about 500ms. Also you would need to take the min and max values before averaging to get the amplitude, since otherwise taking the average of the wave directly would mostly cancel out. Please show the code and the wiring of your project.

How is the ESP32 connected to the output of the amplifier? What kind of signal is this?

@chrisl, I just added diagram and code. I will now try your suggestion of getting the average

@StarCat, I hope the newly diagram helps with the questions. Otherwise I'll try to clarify further

I see multiple problems with your setup:

You only take a measurement every 100ms. That measurement takes the voltage during a very short time span. But the lowest string on a guitar in standard tuning has 82.41Hz (E2). You are measuring at 10Hz. According to the Nyquist–Shannon sampling theorem you need to measure at at least twice the frequency of your lowest frequency to measure. Otherwise your measured data will not have any real meaning and will not represent the input wave. So you need to measure at least with 165Hz.

The amplifier can output voltages up to it's supply voltage, so 5V. You connect the output directly to the ESP32, which is a 3.3V device. That can damage the pin, that you are using.

Currently you are trying to measure the signal directly. But you wrote, that you want to have the amplitude. Currently you would need to calculate that in code (for example by taking the min and max value over a time range greater than one period of the lowest frequency, so at least 12ms (1/82.4Hz)). A multimeter most likely will do that in hardware with analog electronics.

I'm not sure if it is good to connect a speaker and the ESP in parallel. As a speaker is basically an inductor moving in a magnetic field, you might get backwards voltage induced by it. That might be harmful to the ESP. Others here might know more about that.

You connect the Arduino ground to speaker ground. But that is most likely not the same as the amplifiers ground. Most likely the amplifier drives the speaker symmetrically, so also with negative voltages in reference to the speaker ground. That can damage the ADC of the Arduino. Also it's unclear, how good that ground actually is. That pin is not meant for grounding a microcontroller. Driving a speaker is different from measuring the voltage with an Arduino, so you would need different amplifiers to do it.

I'm not an expert in the field of analog electronics, but I guess you could use a diode to get one half-wave and then feeding it into a low pass filter. The resulting voltage is relatively steady (depending on the cut-off frequency of the filter) and can then be measured by the ESP. I'm sure, that this will only give you a rough measurement of the amplitude, but enough for typical applications like amplitude visualization. For really precise measurements you most likely need to use a more complex electronics setup to work against the non-linearities of the parts (especially the diode).

Thanks, very good points.

You only take a measurement every 100ms:

This I fixed by taking a larger sample and getting the average.

The amplifier can output voltages up to it's supply voltage, so 5V:

I can regulate this with a volume knob in the LM386 module

I'm not sure if it is good to connect a speaker and the ESP in parallel:

This is the only way I've found to get readings that make sense. If the speaker is not there I get high values that don't reflect anything from the actual input.

I am wondering about why it works only with the speaker connected and how can I get rid of it as I don't really need a speaker on my setup

Mhh, the amplifier most likely acts like a current source and will raise the voltage, until the needed current flows or the limit is reached. So the problem is the type of amplifier. With a different amplifier you should be able to ditch the speaker. Though - as I wrote - I'm really no expert in that field.

@AlejandroCamus Taking samples and calculating the average to find the amplitude is meaningless. Imagine a single cycle of a pure sine wave. Think about sampling at regular points along that waveform. What will the average be? Now reduce the amplitude but keep the offset the same and do it again. What will the result be? You see the average has no relation to the amplitude - it only gives you the "DC offset" of the waveform. Instead you need to take lots of samples and find the MAX and MIN values over that period. The difference between the two values is the amplitude.

@Majenko Actually I think the OP gets satisfying results, because he tries to use the speaker ground as ground for the Arduino. Most likely the amplifier outputs a symmetrical wave around the speaker ground. But the ADC doesn't measure the negative voltages, thus the OP actually only measures one half wave. The average still doesn't give the real amplitude, but that still might be sufficient for the OPs application. At least that is my theory whats happening.

I managed to get accurate readings by following @chrisl's suggestion in the comment.
Instead of trying to get values at given points I am now averaging 500 values and the readings are as expected.
New code:
int ampedVoltagePin = 12;
int counter = 0;
int sumOfVoltages = 0;
int sampleSize = 500;
int average;

void setup() {
  pinMode(ampedVoltagePin, INPUT);
  Serial.begin(9600);
}

void loop() {

  sumOfVoltages += analogRead(ampedVoltagePin);

  if (counter > sampleSize -2) {
    average = sumOfVoltages/sampleSize;
    Serial.println(average);
    sumOfVoltages = 0;
    counter = 0;
  }

  counter ++;
}

Yes, you do need to sample at a rate at least 2x the highest harmonic you want to consider.  But that's not your biggest problem.
The LM386 is normally used with an output capacitor.  The chip specs say it is "self balancing", which means its output sits at half the supply voltage when there is no signal present, then swings up and down from that.  The inductance of the speaker is not the issue here, it's that it has a very low DC resistance (8 ohms, typically) and you are putting it across a 2.5V DC source (the LM386 output).  This not good for the amp, and it's terrible for the speaker since it is outside its normal centered operating point.
So use a big electrolytic capacitor between the LM386 and the speaker.  The data sheet shows 250 uFd, but that's not critical. Note that the + pin of the capacitor must connect to the LM386 output.  But the Arduino input must connect to the amp directly, as you are doing now, and you must subtract +2.5V from every reading to get an AC waveform.  You can then handle that as you wish, such as by taking the absolute value and filtering (averaging with a time constant).


text:
What would cause fuses to be writeable but bootloader not to be writeable?
I am trying to burn a bootloader onto an ATmega328P-AN using an Microcenter knock-off Arduino Uno R3 as my ISP for several days with no luck. The farthest I've gotten is writing and reading a few fuses prior to bootloader burn.
I have checked and rechecked the connections:
Uno    ATmega328P-AN
GND    GND
VCC    VCC
MISO   MISO
MOSI   MOSI
SCK    SCK
SS     RESET

I have a 2.2 uF cap from ground to RESET on my Uno, and a 16 MHz crystal with two 22 pF load caps to ground on my ATmega328P's XTAL pins.
I have ArduinoISP loaded onto the Uno and my bootloader target is "Arduino Pro or Pro Mini", and my processor is set to "ATmega328P (5V 16MHz)".

I am using Arduino 1.8.9 on Windows 10.
Things I've tried:

Multiple boards and ATmega328P ICs - No difference.
Burning a bootloader to an Ebay Arduino Pro Mini knockoff, which worked, but there's no obvious electrical difference between this part and a raw ATmega328P. (Weirdly, the slight progress I made (setting some fuses - see below) was done by bypassing the DTR-cap-pullup reset path and running the ISP SS directly to the reset pin on the ATmega328P chip.)
Using Arduino IDE 1.0.x - No success.
Using a genuine Arduino Uno R1. No success.
Checking all the rails. I have a clean 5V and a clean ground. Unfortunately my lousy scope isn't picking up any of the 16 MHz oscillators, so I'm not sure what my clocks are up to.
In-circuit programming in a populated board with flying leads from the appropriate ICSP nodes. No success.
In-circuit programming with fresh board and just a power supply bypass cap, oscillator, load caps, and supply rails available.

Here's my Arduino IDE terminal output:
    C:\Users\xxx\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/bin/avrdude -CC:\Users\xxx\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\xxx\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf"

             Using Port                    : COM3
             Using Programmer              : arduino
             Overriding Baud Rate          : 19200
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f (probably m328p)
    avrdude: erasing chip
    avrdude: reading input file "0x3F"
    avrdude: writing lock (1 bytes):

    Writing | ################################################## | 100% 0.01s

    avrdude: 1 bytes of lock written
    avrdude: verifying lock memory against 0x3F:
    avrdude: load data lock data from input file 0x3F:
    avrdude: input file 0x3F contains 1 bytes
    avrdude: reading on-chip lock data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of lock verified
    avrdude: reading input file "0xFD"
    avrdude: writing efuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of efuse written
    avrdude: verifying efuse memory against 0xFD:
    avrdude: load data efuse data from input file 0xFD:
    avrdude: input file 0xFD contains 1 bytes
    avrdude: reading on-chip efuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of efuse verified
    avrdude: reading input file "0xDA"
    avrdude: writing hfuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of hfuse written
    avrdude: verifying hfuse memory against 0xDA:
    avrdude: load data hfuse data from input file 0xDA:
    avrdude: input file 0xDA contains 1 bytes
    avrdude: reading on-chip hfuse data:

    C:\Users\xxx\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/bin/avrdude -CC:\Users\xxx\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b19200 -Uflash:w:C:\Users\xxx\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.23/bootloaders/atmega/ATmegaBOOT_168_atmega328.hex:i -Ulock:w:0x0F:m
    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of hfuse verified
    avrdude: reading input file "0xFF"
    avrdude: writing lfuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of lfuse written
    avrdude: verifying lfuse memory against 0xFF:
    avrdude: load data lfuse data from input file 0xFF:
    avrdude: input file 0xFF contains 1 bytes
    avrdude: reading on-chip lfuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of lfuse verified

    avrdude done.  Thank you.

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\jms\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf"

             Using Port                    : COM3
             Using Programmer              : arduino
             Overriding Baud Rate          : 19200
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.01s

    avrdude: Device signature = 0x000000 (retrying)

    Error while burning bootloader.
    Reading | ################################################## | 100% 0.01s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

If I try to burn the bootloader again, I just get the "Device signature = 0x000000 (retrying)" messages, but no fuse write/read cycles.

I am really stumped at this point.
Questions

Am I bricking my ATmega328P parts when the bootloading process is not successful?
What am I missing?

Do yourself a favour and get a proper programmer, rather than using an Arduino. Remove that link from the chain. A USBASP costs <$5 from eBay/Amazon/AliExpress.

That was my next step. What makes the Arduino a poor programmer?

It's not so much a bad programmer - it's awkward and easy to get it wrong. Far simpler to stick to something that is designed for the task - plug in and go.

Cool. A programmer is on the way, and we'll see what happens.

As an aside, are ATmega ICs that don't get a completed a bootloader effectively bricked?

No, not normally. The main way of bricking one is to get the fuses wrong so it needs an external clock. For that you need to apply a 1MHz clock signal to the crystal input to get it to work again. Or use a High Voltage Programmer (Nick Gammon has a tutorial on doing it IIRC).

source: Stack Exchange

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

sort: votes


text:
Motor isnt spinning when using L298N motor controller
I have a L298 motor controller connected to a motor with a 6 volt power sources. the motor however isn't spinning any ideas I'm using a esp 8266 node mcu board. I would like to use pwm but for right now I'm just trying to get it to work so I disabled the pwm.
//int d0 = 16;
const int d0 = 16;
const int d4 = 2;

//=======================================================================
//                    Power on setup
//=======================================================================
void setup() {
  Serial.begin(115200);
  pinMode(d0,OUTPUT);
  //pinMode(d1,OUTPUT);
  pinMode(d4,OUTPUT);
}

//=======================================================================
//                    Main Program Loop
//=======================================================================
void loop() {
  //PWM Value varries from 0 to 1023
  Serial.println("10 % PWM");
  //analogWrite(d0,102);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("20 % PWM");
  //analogWrite(d0,205);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("40 % PWM");
  //analogWrite(d0,410);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("70 % PWM");
  //analogWrite(d0,714);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("100 % PWM");
  //analogWrite(d0,1024);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

}

Did you remembet to supply power to the controller itself?

I did connect 9v to the controller in the is there something else im missing?

Um... The controller itself needs ~5V logic supply voltage (7V max). Where do you connect your 9V supply to? If you have that popular pre-assembled L298N motor board with a built-in linear regulator, and you connect 9V to VCC, you will also have to install the jumper to enable the linear regulator to produce 5V for the logic supply. Or, alternatively, you can connect the "5V" pin to some other 5V supply. Either way, you have to provide a 5V for the logic to work.

https://drive.google.com/file/d/19EKge7SHiktcq1ulWxvT7IfyXD5St_MM/view?usp=sharing

That's a picture of how I have the motor controller setup does it look right?

That doesn't look right. The actual motor power supply is supposed to be connected to the leftmost pin in the group of 3. And in your case it is not connected to anything. The logic power supply (5V) is supposed to be connected to the rightmost pin in the group of 3 (red wire in your picture). What is this red wire? Is this a power supply to L298N? Or is it powering something else from L298N?

You need two supply voltages for this board to work: motor supply, which goes directly to your motor (up to 35V for this L298N board, depends on what your motor needs), and logic supply of 5V, which powers the board's logic chips. If the motor supply voltage is between 7V and 12V, you can derive 5V logic supply from motor supply by enabling this board's built-in linear regulator.

The actual motor power supply should be connected to the VCC terminal of the L298N board you have in your picture. This is the leftmost terminal in the block of 3 in the picture (sometimes it is labeled +12V instead of VCC). In your case it is not connected to anything at all. This is already wrong.
It is not clear what the purpose of the red wire is in your picture.
In your comments you mention different voltages of motor power supply (6V in one place, 9V in another...). If you are feeding this board 9V through the red wire, you are doing it wrong. The rightmost terminal in the block of 3 is the 5V pin. Don't attempt to feed more than 5V to that pin.
If you'll be using the red wire to supply 5V logic power to the L298N board from an external source, then you need to disable this board's own linear regulator - remove the jumper that is shown above the 3-terminal block.
If you'll decide to use it to supply 5V logic power from the L298N board (e.g. to your Arduino), then you have to keep the jumper.
In any case, the leftmost terminal has to be connected to motor power supply.

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


text:
Send Strings via SPI both ways using two Arduino UNOs(Master to Slave & Slave to Master)
I need to create a two way String exchanger via SPI with two Arduino UNOs. Strings and their lengths are independent variables of the main loop and they can change with every iteration. I need both of the Arduinos to communicate with each other regardless of what the strings contain. I want to see basically the same screen with the serial monitor.
It is kind of working. I am not sure how to explain it, I'll just show it below.
Basically the main idea for both of the Arduino's is like this:
Master: hey
Slave: hi

Instead I get this on the master:
Slave:
Slave:
Master: hey
Slave: y
Slave:
Slave:
.
.
.
Slave: i
Slave:
Slave:
.
.

And the slave displays only itself:
Slave: hi

I have created for loops to transfer every char of the string seperatly and respectively but this is still the case. I couldn't find any sample code online for independent string transfering via SPI. I know I probably have many mistakes but how can I fix them to work just as I intend to?

Connections:
Arduino1.pin13 --- Arduino2.pin13
Arduino1.pin12 --- Arduino2.pin12
Arduino1.pin11 --- Arduino2.pin11
Arduino1.pin10 --- Arduino2.pin10

Master Code
//MASTER

#include<SPI.h>

String textSend="", textReceive="";

void setup(){

  Serial.begin(115200);

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV8);    //Sets clock for SPI communication at 8 (16/8=2Mhz)
  digitalWrite(SS,LOW);
}

void loop(){

  textSend=""; textReceive="";
  textSend = Serial.readString();
  if(textSend != ""){
    for(int i = 0; i < textSend.length(); i++){
      delayMicroseconds (20);
      SPI.transfer(textSend[i]);
    }

    Serial.print ("Master: ");
    Serial.println (textSend);
  }else{
    int i = 0;
    char c;
    do{
      delayMicroseconds (20);
      c = SPI.transfer(1);
      textReceive += c;
      i++;
    }while(textReceive[i] != 0);

    if(textReceive[i] == 0){
      Serial.print ("Slave: ");
      Serial.println (textReceive);
      textReceive = "";
    }
  }
}

Slave Code
//SLAVE

#include<SPI.h>

String textSend="";
String textReceive="";

void setup (void){
  Serial.begin(115200);
  pinMode(MISO, OUTPUT);
  SPCR |= _BV(SPE);
  SPCR |= _BV(SPIE);
  SPI.attachInterrupt();

}

ISR (SPI_STC_vect){ //Interrupt Service Routine

  byte c = SPDR;

  if(c != 1){ //Slave receives
    for(int i = 0; i < textReceive.length(); i++){
      textReceive += SPDR;
    }
    if(textReceive.length() > 0){
      Serial.print("Master: ");
      Serial.println(textReceive);
      textReceive = "";
    }
  }else{
    for(int i = 0; i < textSend.length(); i++){
      delayMicroseconds(20);
      SPDR = textSend[i];
    }
    if(textSend != ""){
      Serial.print("Slave: ");
      Serial.println(textSend);
      textSend = "";
    }
  }
}

void loop() {
  if(textSend == "")
    textSend = Serial.readString();

}

It's not trivial to have both arduinos communicating "with each other" as SPI is a master-slave bus. That means the slave cannot start a transmission, communication must always be initiated by the master instead. Another thing with SPI is that you can't read the slave without writing to it. SPI works like a shifting register: on every clock cycle both devices transmit the byte in their SPDR to each other. So, to read a long string from the slave the master has to transmit the exact same number of dummy-bytes and simultaniously read the incoming stream. This is great if only a specific number of bytes need to be transmitted (e.g. exchanging variables which always consist of the same number of bytes), but becomes complicate when the number of bytes varies. You will then need to implement some protocol that is able to read a variable amount of bytes from the slave (e.g. you will have to tell the master the number of bytes that have to be read).
I think serial communication like UART is perfect for your purpose as communication is real full-duplex, it's no master-slave-system and the common protocol uses a terminating character to end a data stream which makes it ideal to transmit strings. Also the arduino can run several serial interfaces (you might need another for debug output).

First of all, SPI is mandatory for my assignment so I can't use anything else (but thank you for suggesting an alternative for a solution). For keeping the Master listening to the slave, can we maintain a medium which the Master keeps sending a dummy byte constantly to receive Slave's bytes (when the Master does not have anything to send). Slave wouldn't take the dummy byte into consideration and add the anything else to the string? Theoratically, I think it should work that way but I can't get it to work.

Yes, you could kind of emulate the UART protocol on SPI which means you probably will need the master to send continuously. You will then have to define a dummy-byte which will be ignored by both master/slave and a terminating byte (in UART it's typically \n) to mark the end of a string in the byte stream. Even though it's not the most elegant way I see no reason why it shouldn't work.

The reason why it doesn't work are some mistakes in your code. E.g. while(textReceive[i] != 0); is wrong as you continuously check for a condition which can't change while you check it. So the routine either does not enter this loop or it will be stuck for ever. Your master code looks like you haven't fully understood the mechanism behind SPI. Keep in mind that you have to write and read each byte at the same time. That means that a for loop like in your case for(int i = 0; i < textSend.length(); i++) doesn't work because you don't handle the incoming bytes which by this are lost.


text:
Results for GP2Y1010AU0F Dust Sensor
I am using Dust Sensor GP2Y1010AU0F
I downloaded the code from the manufacturer here:
http://www.waveshare.com/wiki/Dust_Sensor
/*********************************************************************************************************
*
* File                : DustSensor
* Hardware Environment:
* Build Environment   : Arduino
* Version             : V1.0.5-r2
* By                  : WaveShare
*
*                                  (c) Copyright 2005-2011, WaveShare
*                                       http://www.waveshare.net
*                                       http://www.waveshare.com
*                                          All Rights Reserved
*
*********************************************************************************************************/
#define        COV_RATIO                       0.2            //ug/mmm / mv
#define        NO_DUST_VOLTAGE                 400            //mv
#define        SYS_VOLTAGE                     5000

/*
I/O define
*/
const int iled = 7;                                            //drive the led of sensor
const int vout = 0;                                            //analog input

/*
variable
*/
float density, voltage;
int   adcvalue;

/*
private function
*/
int Filter(int m)
{
  static int flag_first = 0, _buff[10], sum;
  const int _buff_max = 10;
  int i;

  if(flag_first == 0)
  {
    flag_first = 1;

    for(i = 0, sum = 0; i < _buff_max; i++)
    {
      _buff[i] = m;
      sum += _buff[i];
    }
    return m;
  }
  else
  {
    sum -= _buff[0];
    for(i = 0; i < (_buff_max - 1); i++)
    {
      _buff[i] = _buff[i + 1];
    }
    _buff[9] = m;
    sum += _buff[9];

    i = sum / 10.0;
    return i;
  }
}

void setup(void)
{
  pinMode(iled, OUTPUT);
  digitalWrite(iled, LOW);                                     //iled default closed

  Serial.begin(9600);                                         //send and receive at 9600 baud
  Serial.print("*********************************** WaveShare ***********************************\n");
}

void loop(void)
{
  /*
  get adcvalue
  */
  digitalWrite(iled, HIGH);
  delayMicroseconds(280);
  adcvalue = analogRead(vout);
  digitalWrite(iled, LOW);

  adcvalue = Filter(adcvalue);

  /*
  covert voltage (mv)
  */
  voltage = (SYS_VOLTAGE / 1024.0) * adcvalue * 11;

  /*
  voltage to density
  */
  if(voltage >= NO_DUST_VOLTAGE)
  {
    voltage -= NO_DUST_VOLTAGE;

    density = voltage * COV_RATIO;
  }
  else
    density = 0;

  /*
  display the result
  */
  Serial.print("The current dust concentration is: ");
  Serial.print(density);
  Serial.print(" ug/m3\n");

  delay(1000);
}

My results seems rounded or always returning in certain 'steps'.
(below are my results)
Is there a rounded error in the code or something else that could be going on?
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 124.10 ug/m3

Its because the resolution of the analog read is 10 bits or 1024 discrete values.
In your code the density is basically calculated as:
density = (((5000 / 1024.0) * analog_value * 11) - 400) * 0.2

You can calculate the resolution as:
(5000 / 1024.0) * 11 * 0.2

and you get 10.7421875, which matches your observation.
If your filtering (calculating the average over last 10 values), would calculate and return a float, you would get smoother values.

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


text:
(ultrasonic sensor code : No such file or directory)
I'm beginning in Arduino I do not understand what the error means. Please tell me where I can find the resources to understand it and allow the code to compile.
#include <RCSwitch.h>
#include <Ultrasonic.h>

Ultrasonic ultrasonic(11,10);
RCSwitch mySwitch = RCSwitch();

int i;

void setup() {
    mySwitch.enableTransmit(4);
}

void loop() {
    i = ultrasonic.Ranging(CM);
    mySwitch.send(i, 24);
    delay(100);
}

Arduino: 1.8.7 (Windows 7), Board: "Arduino/Genuino Uno"
433mhz-lcd-water-level-transmitter:2:24: error: Ultrasonic.h: No such
  file or directory
compilation terminated.
exit status 1 Ultrasonic.h: No such file or directory
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

Did you install the library?

I did add an ultrasonic library but have the same error

Thanks for all my problem is solved download ultrasonic code here https://www.arduinolibraries.info/libraries/ultrasonic i found another library ultrasonic solve my first problem(Ultrasonic.h: No such file or directory) but then have another error... it say(class Ultrasonic' has no member named 'Ranging').... in this time i changed some of my code and now working good my code after solve include include Ultrasonic ultrasonic(11,10); // (Trig PIN,Echo PIN) RCSwitch mySwitch = RCSwitch(); int i; void setup() { mySwitch.enableTransmit(4); } void loop() { Ultrasonic ultrasonic(11,10,3000); // (Tri

This kind of error means that the Arduino IDE (assuming that is what your are using) did not find 'Ultrasonic.h' in a folder named 'libraries' within your Arduino sketch folder. (Some libraries are contained in other places within the IDE's executable, but putting your additional libraries in '.../libraries' keeps everything easy to find and maintain).
Go to File | Preferences (in Windows or Linux) or Arduino | Preferences (Mac). The top box in that dialog is the path to your sketch folder. That folder should contain one called 'libraries'.
The libraries folder should have a folder for each library, so in this case, there should be a folder named 'Ultrasonic', containing files 'Ultrasonic.h' and 'Ultrasonic.cpp'. There may be other items in there as well, perhaps an Examples folder, a 'keywords.txt' file (helps the IDE with syntax coloring), a text file with release notes, etc., but the important structure is
[path/to/your/sketch/folder]
     libraries
         Ultrasonic
              Ultrasonic.h
              Ultrasonic.cpp
         someotherlibrary
              someotherlibrary.h

etc.

the .h and .cpp of the library can be in src subfolder if 'new' library format is used

Indeed - thanks for pointing that out. The above should be taken as the minimum basic structure.

It means what it says:

Ultrasonic.h: No such file or directory

The file Ultrasonic.h can't be found.
Anything in your code that starts #include... is usually a library. These are third party pieces of software that you have to obtain and install into the relevant location (See Installing Additional Arduino Libraries).
Some libraries are bundled with the IDE, and some are available through the "library manager" in the IDE. However most aren't, and you will have to get used to finding those libraries and installing them.
The location you got your example code from will most likely link you to where to find the relevant libraries to get the code working.

i found another library ultrasonic solve my first problem(Ultrasonic.h: No such file or directory) but then have another error... it say(class Ultrasonic' has no member named 'Ranging')....
in this time i changed some of my code and now working good
my code after solve
#include <RCSwitch.h>
#include <Ultrasonic.h>

Ultrasonic ultrasonic(11,10); // (Trig PIN,Echo PIN)
RCSwitch mySwitch = RCSwitch();

int i;

void setup() {
  mySwitch.enableTransmit(4);
}

void loop() {
Ultrasonic ultrasonic(11,10,3000); // (Trig PIN,Echo PIN, Max.TimeOut in µsec )
  mySwitch.send(3000 ,24);
  delay(100);
}


text:
Value read is not changing while rotating pot in arduino?
I am trying to read voltage using analogRead in Arduino Uno from a voltage divider circuit consisting of 1k resistor and 10k pot. The Pot used is bourns 3296. The values obtained only range from 1011 to 1023? Why is the count not reducing further if I rotate the pot?
(this how i have connected the circuit, but the pot is the one that i have mentioned above, i couldn't find that kind in the software, but i have made the connection this way only)

int analogPin = A0;

// variable to store the value read
float val = 0;

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

void loop() {
  Serial.println(val); // read the input pin
  val = analogRead(analogPin); // debug value
}

Since potentiometer itself is a voltage divider, I have tried connecting as per the answer, the ends of the 10k pot to 5V and ground , and the slider pin to the analog pin A0. The new circuit is as shown below, but I am still unable to get the value ranging from 0 to 1023. The values returned only vary in between 1010 to 1023. What is going wrong? How do I get the full range?

And the code your using while your at it.  Issue is probably in the divider circuit, but still good to have a look at all of it.

A potentiometer is a voltage divider in itself. You don't need the extra 1k resistor

@chrisl I am trying to model a sensor which works at 5V as a voltage divider. So can I just use the pot? Most of the simulations that I have seen use a resistor along with pot. Please confirm.

Yes, you only need the pot. Connect it as described at the start of your sketch. A pot is a resistor strip, that gets divided by the middle wiper.

ok, one more question, then what does those voltage dividers with pots serve purpose for?

@chrisl Is it for cases when we really need to lower the voltages , such as using the microcontrollers  working on say 3.3 V?

A potentiometer is already a voltage divider by itself. The outer contacts are connected to the ends of a resistor strip. The middle pin is connected to a wiper, which can slider over the strip, dividing the strip into 2 parts. So you connect it like it is described at the start of your sketch (before the last edit): The outer pins to 5V and ground respectively and the middle pin to the analog input. (When using this in different circuits, keep in mind, that you should not draw too much current from the middle pin. Don't drive any load directly from it. The analog input does only draw a very small amount, so that's absolutely no problem.)
When adding a constant resistor in series with the pot, you are only adding a dead range, that cannot be set with the circuit.

what does those voltage dividers with pots serve purpose for?

Only the pot: Potentiometers are mostly used to give a setpoint, a user controlled voltage, which can be read by a microcontroller or used directly for controlling further electronics.
With an additional resistor: You can put in an additional resistor at the high side of the pot, to lower the voltage further. For example if you - for whatever reason - have to use a higher voltage for the voltage divider, than the microcontroller can handle. You can calculate the value of the resistor, so that the voltage on the analog pin will never exceed the limits. But this scenario must be very rare. I didn't encounter such a situation ever.

I did the connections like you said, but still the value returned varies only between 1010 to 1023. What is wrong?

Please show a wiring diagram of the new situation. You can add it to your question by editing it. Let the original question stay as before, so that others can follow and learn from it later. Just add the new information at the questions bottom

The answer didn't solve the problem, so you can uncheck it, until it does

OK, I am unable to leave a comment (< 50) so...
Use this link to learn about the AREF pin on the Arduino, this may not be your problem but it is good to know about anyway:
what is arduino adc reference?
Your pot MAY be broken. Measure the resistance of the pot with an ohm meter, from the center pin to either of the side pins. Verify when you turn it the resistance varies from 10K to 0.
You can also measure the voltage it is providing your Arduino by measuring the voltage it presents to pin A0. Verify the voltage changes little by little from +5 to 0 when you turn it back and forth.
You list the pot as being a "bourns 3296" which the data sheets show as a "Multiturn / Cermet / Industrial / Sealed" pot.
Just so you know, when you adjust it you will have to turn it 25 turnes to fully adjust it through its entire range. The data sheet shows "Effective Travel.........25 turns nom."


text:
16-Channel 12-bit PWM/Servo Shield check if it is powered by adapter
I'm using Adafruit 16-Channel 12-bit PWM/Servo Shield with Arduino Uno controller
In setup() I have a number of default positions with PWM commands for motors with plug of USB to PC and turning on
I'm trying to figure out, how to avoid setup() commands, or any other signals during process to servos, in case if shield is not powered from power adapter, which is 6V 8Amp in my case, to not send signal to servo while it is not powered by power supply

Have you thought of using an input pin to sense the voltage of the power adapter? You only have to isolate it from Vcc with a diode (as long as the voltage of the adapter is not higher than the Unos 5V. In that case you also would need a voltage divider.

@chrisl Hello, and what is the program part in this case, since I need this condition in sketch code. It would be very useful to find some more detailed guide on this task

The only releveant code here is to use a value = digitalRead(pin_number). Youc an then do whatever you want with this, for exmple check in an if statement, if the result is HIGH or LOW by doing if(value){...} else {...}. I don't know, what I should write there in my answer.

@chrisl Yes, but I could not yet use this scheme to check result. As I've said below, it is not enough voltage with using of diode

I would propose a circuit like the following:

simulate this circuit – Schematic created using CircuitLab
The voltage divider (consisting of the resistors) will divide the 6V to 5V for the Arduinos digital input. The values are not critical, they can be made higher, but maintain the relationship to still get the 5V. The diode will prevent current to flow from the shield into the voltage divider, when the shield is powered through other means. Now you can simply do a digitalRead() on the corresponding digital input pin of your Arduino, to check, if the power was applied.

Please notice, that the diode will reduce the voltage a little by it's forward voltage (depends on the diode). But that shouldn't be a big problem.

Thank you for answer. Can you clarify, if this way I could monitor power to the servos using one of "digital input pins" with resistor divider to divide that down to 5v or less for the Arduino Uno, what is a difference of using "analog pin" in this case, I found number of close guides: 1. Measuring DC Voltage 2. Arduino Battery 3. Energy meter

From your question I assumed, that you use a normal power adapter, which means, that the 6V for the shield are already regulated beforehand. I think of a wall wart. In this case there are inly two possibilities: 6V or no voltage at all. Then the digital pin is sufficient. If you have a battery connected there and want to also sense the low voltage case, you can use an analog pin.

Hello, I could not yet use this scheme to check result. Something is incorrect for particular shield. I've soldered scheme exactly as you shown, 2 resistors 1.0 and 5.07, diode 1N4148. Without anything power jack shows 6.56V, shield turns on. Through scheme voltage runs from 6.29 to 6.52V, shield does not turns on, seems like it is not enough voltage

The shield should also work with voltages down to 5V. Is the green LED on the shield on? Does it work, if you bridge the diode? Is it mounted the right way? (Putting it in reverse will block the voltage to reach the shield)

Yes cathode (pole with black line) directed with output wire to the shield, should prevent flow from the shield into divider. Anode pole directed to 1kΩ resistor from plus. Voltage from VCC and GND runs 6.18, 6.29, 6.52V... Green LED on the shield off, shield does not works. Without scheme direct meter test shows 6.56V, green led on, shield works. I did not tried bridge the diode

The lower voltage shouldn't be a problem. Adafruit states directly, that you can use 5 or 6V and they suggest power supplies with 5V. The problem must lie somewhere else. Do you have motors connected at this time? If yes, try without any motors connected. If this works, the current may be too small

Your diode has a maximum of 300mA continous forward current. Depending on connected motors, that might not be enough.

Are you sure that the diode is needed? I use only one source of servo power. Also  it is quite  tiny, I'm not sure if it is  rated for sufficient current to drive a servo

I looked closer at the schematics and there seems to be no connection between Vcc and the servo power. Then it would be ok without the diode. Also you can test this: Check the voltage at the servo power  pins, when the external power is not connected. If there is 0V, you don't need the diode. I will update the answer with this

Sorry for late answer. Yes, without diode works as needed. Thank you for support


text:
Check if Arduino Uno connected with PC
I'm using Arduino Uno controller
How it is possible to know if controller connected to PC via USB, to detect if wire is plugged and get condition for variable in sketch.
I've tried Serial.available(), but I'm not sure, if I can do it this way:
if (Serial.available())
{
   val = true;
}
else
{
   val = false;
}

I want use this condition to avoid setup() commands by some unexpected reason in case if controller powered only with adapter

I don't know the answer of the problem, but your code can be rewritten to a shorter and equally functional val = Serial.available();

you can do another thing like you continuously send some random data over serial. when arduino is connected to the PC it will receive same data from arduino, indicating arduino is connected to your PC. For reception point of view you can write some python script as well.

You can't determine if there is a valid USB source on the UNO without modifications, because the Atmega328P just receives serial data when the host sends some data. Some approaches that you can keep in mind.

If you want to determine whether you are connected through the USB or barrel connector, you can connect an analog pin to the Vin pin through a voltage divider (you should calculate the values so that you do not exceed 5V on the analog pin). This way if you detect a voltage greater than 6.6V you will know that you are being powered from the barrel jack.
If you want to detect a particular PC, you can write a SW in the PC which scans for new ports, then opens them and sends a particular string. If you receive that within X seconds, you know that you are connected to the PC
If you want to determine if you are connected to any valid PC, then I think you will need to modify the program in the Atmega16u2 which is used as a serial bridge between the two. I'm not sure whether it is possible or not, but I think that the Atmega16u2 knows when a valid USB session is started, and so can tell the Atmega328 this information (through the serial interface)

It's an ATMega16u2, not a ATMega32u4, that's on the Arduino UNO. Other than that, options 3 would be possible.

@Gerben I was totally sure it was the same as on the Leonardo.. Goot catch, I fixed it in the answer. Thank you

And older revisions were using ATMega8u2. Knockoffs started 8u2 or FTDI, ended with cheaper CH340G


text:
Does the Arduino Uno have two crystals?
Take a look at this picture:

I think most of use agree that the "big silvery" thing on the board (red) is the famous 16 MHz crystal of the Arduino. That's what I've believed until very recently.
I was bored so I looked at my Arduino Uno, and saw that it has what seems like another crystal (yellow). It looks like the one that is on the Pro Mini. It's also located near the XTAL pins. After I inspected the schematic a second time, it also appears that there are two crystals on the board.
Which one out of those two is actually connected to the XTAL pins and why are there two?

The ceramic resonator in yellow is connected to the main MCU, and the crystal in red is connected to the other MCU. USB requires tighter tolerances than is available from a resonator therefore a crystal must be used instead.

There are 2 that you can see, but there are internal resonators in both chips. You can use the ATMega328's one if it's on a breadboard (it's half the frequency tho), and much more temperature-dependent. Just need to give it a fresh bootloader.

authors: ภัทรพล จันเขียน

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


text:
Analog pins for 4x4 matrix keypad
I am working on a project on nano and want to use analog pins for 4x4 matrix keypad input. My connections are for keypad are as follows:

Digital pins are D10-D13 and Analog pins are A0-A3.
A0->14,
A1->15,
A2->16,
A3->17

Code is:
#include <Keypad.h> // includes the keypad library
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] = {
 {'1','2','3','A'},
 {'4','5','6','B'},
 {'7','8','9','C'},
 {'*','0','#','D'}
};

byte rowPins[ROWS] = {10,11,12,13}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {14,15,16,17}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

Can I use analog pins as I defined for keypad? Is "Keypad.h" library compatible with Arduino Nano v3.0?

if you want to use just a few pins, get a few cheap shift register ICs, like the  74HC165.

Tested on Nano v3.0 and it works flawlessly with this exact code. You can't use A6 and A7 as they are analog inputs only.

The problem i was going through is because of pin number 13. Pin 13 is connected to LED and is not good option for taking input as it is connected to 3.3V internally. Because of this arduino was detecting one key pressed constantly making other key presses undetected. In this case the key was charecter *.

ADVICE: Don't use pin 13 for input!

You can use the analog pins. I prefer {A0, A1, A2, A3} in the code instead of {14, 15, 16, 17}. That makes it easier to check if you connected the wires to the right pins.
Don't use pin 13 for an input with the Arduino Nano. An LED is connected to that pin. You can use that pin as an output for something else.

i tried that but nano is unable to take inputs from keypad. Keypad is working fine on mega.

You'd better try with another Nano if the solution Jot proposed not working.

it's working when tested separately but not with the whole 400 lines code which worked perfectly on mega. i changed pin numbers etc but no result.

Could the problem be a memory problem ? What does the compiler say about sram (dynamic) memory usage. Do you use large arrays or many String objects ?

In fact that, 4x4 keypad programming with Arduino is quite straight forward. So, I am surprised you have an issue with that . Since we can't see the entire code, it is hard to give a proper look and answer accordingly. You maybe do some debugging with some "Serial.print(yourvariable)" to see where the bottleneck is. As Jot has also mentioned that the memory is quite an issue when you use memory consuming large array or struct in the code. I am not talking about the memory used when you complied but in run time.

Thank you all of you guys for trying to help me. But just now i discoverd the problem. its wriiten in answer.


text:
How to connect an Arduino and a WAMP server's MySQL database?
I'm trying to connect an Arduino Mega to my WAMP server's database using MySQL connector for attendance logging. But it shows "Connection failed".
What is my WAMP server's IP address?
I connect my laptop and Arduino with a router so:

My laptop is 192.168.1.2
My Arduino is 192.168.1.3

I think this is correct.
/*
  MySQL Connector/Arduino Example: basic insert
  This example demonstrates how to issue an INSERT query to store data in a
  table. For this, we will create a special database and table for testing.
  The following are the SQL commands you will need to run in order to setup
  your database for running this sketch.

  CREATE DATABASE test_arduino;
  CREATE TABLE test_arduino.hello_arduino (
    num integer primary key auto_increment,
    message char(40),
    recorded timestamp
  );

  Here we see one database and a table with three fields; a primary key that
  is an auto_increment, a string, and a timestamp. This will demonstrate how
  to save a date and time of when the row was inserted, which can help you
  determine when data was recorded or updated.

  INSTRUCTIONS FOR USE

  1) Create the database and table as shown above.
  2) Change the address of the server to the IP address of the MySQL server
  3) Change the user and password to a valid MySQL user and password
  4) Connect a USB cable to your Arduino
  5) Select the correct board and port
  6) Compile and upload the sketch to your Arduino
  7) Once uploaded, open Serial Monitor (use 115200 speed) and observe
  8) After the sketch has run for some time, open a mysql client and issue
     the command: "SELECT * FROM test_arduino.hello_arduino" to see the data
     recorded. Note the field values and how the database handles both the
     auto_increment and timestamp fields for us. You can clear the data with
     "DELETE FROM test_arduino.hello_arduino".

  Note: The MAC address can be anything so long as it is unique on your network.

  Created by: Dr. Charles A. Bell
*/

#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here
char user[] = "root"; // MySQL user login username
char password[] = ""; // MySQL user login password

// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    Serial.println("Connected Successfully...");
    delay(1000);
  } else
    Serial.println("Connection failed.");
}

void loop() {
  delay(2000);
  Serial.println("Recording data.");
  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

The IP address of the laptop (with your MySQL server) is 192.168.1.2, but you are trying to connect to 192.168.1.3.

As gre_gor pointed out, it looks like your connecting to the wrong ip.
Change:
IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here

To:
IPAddress server_addr(192, 168, 1, 2); // IP of the MySQL *server* here


text:
Does restarting Yún configuration mess up Arduino or its SD card?
I noticed something odd recently - a Yún, that was working previously, wouldn't connect.
After logging in to the web setup, setting the access point and password (which hadn't changed), and save & restart, it connected. Unfortunately, it still doesn't work, and after ssh into it, I find I cannot ls /mnt/sd/ or sda1. It just sits there, requiring Ctrl+C, and gives no output.
Did I reset the Arduino or Linux somehow by setting up access point again, or could my SD card be broken after months of heavy logging?

It sounds like your SD card has likely failed. Try connecting it to a computer with an SD card reader. If it works at all, back it up immediately if you have files you wish to keep. Then try reading and writing files on it. Also if you have a spare SD card, try to use that in the Yun after setting it up appropriately. That should help narrow down the cause to either the Yun or the SD card.

It could also simply be SD card corruption. This can easily happen if a file is being written to and the Yun looses power, or can happen from being force reset while in a stuck state.

Good guess, actually it looks like the ls command hangs when  there are >11000 files in the root of the card - after removing them and trying again it works.


text:
Reserve /dev/ttyUSBx
I have multiple Arduinos that I want to control using Python. My problem is that when I plug my Arduinos into the computer, they get assigned the port /dev/ttyUSBx where x increments with each one I connect.
Is there any way to reserve a certain number for a certain Arduino so that I can hard code that into the Python script? If not, can I scan the port to figure out which Arduino it is?

Do they have unique serial numbers?

@IgnacioVazquez-Abrams What do you mean by serial number? Do you mean the baud rate?

No. The serial number of the USB device.

@IgnacioVazquez-Abrams You mean the x in /dev/ttyUSBx?

No. I mean the serial number when you run lsusb -v.

If you mean iSerial, it's 0 for both.

Yes, iSerial. If they are the same you are kind of screwed. That's the price you pay for cheap Chinese clones though.

Am I screwed if I use Majenko's answer?

Since it relies on the serial being unique, yes.

You might be able to reprogram the serial, but I wouldn't count on it.

Yes. You need to create new unique names for them using udev rules.
By using the unique serial number, along with the VID and PID of the board you can use udev to create a symbolic link to a device name of your choice. Best to keep it to something that the Arduino IDE recognises if you want to access the link from within there for programming (otherwise you can choose what you like).
Rules are stored in /etc/udev/rules.d and take the form of .rules files with various instructions in.  One example, that should do what you want, is:
SUBSYSTEMS=="usb", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="6493832323135111C0A1", KERNEL=="ttyACM*", SYMLINK+="ttyACM50", MODE="0666", GROUP="plugdev"

Of course, tweak it to your personal requirements.
Once you have crafted your rules be sure to restart udev:
sudo systemctl restart udev

or
sudo /etc/init.d/udev restart

and plug your board in.
Genuine Arduino devices usually use /dev/ttyACM* not /dev/ttyUSB*. If you have /dev/ttyUSB* then you are either on a very old device (with an FT232 chip) or a cheap Chinese clone.
If the latter then your mileage may vary somewhat.

Yep Chinese clones. Thanks for your answer.

Stepping on standard namespaces is probably not the best idea though. Naming the symlink something like "arduinoNN" might be a better idea.

Then the IDE won't see it. You notice I chose a name way up in the numbers - one not likely to be used under normal circumstances.


text:
Why need a delay between readings?
When I learn the tutorial in

Analog Read Serial
Digital Read Serial

both of the code examples have a line of code of delay(1) and I cannot understand the comments clearly:
 delay(1);        // delay in between reads for stability

The stability for/of what?

Cross-posted to Arduino Forum.

yes,  i was afraid that no one will answer  my question, since i think there is no much active user as much as Stack Exchange.
Sorry!

You can't have been too afraid, as you posted the questions within an hour of each other. Maybe cross-post if a day or two elapsed with no answers. The Arduino Forum has quite a fast response to questions. You got a response there 8 minutes after posting. And another one 5 minutes later. So I don't quite believe this "fear" of yours.

sorry，it is my fault， i wont do it again

Those delays are nonsense. They don't add to the stability of anything. The best you could say is that they stop you spamming your serial port. (However 1 ms is not very long).
Sometimes people throw in a delay because "it seems to work better" without examining the underlying cause. I would speculate that in this case the author may have been using delays to improve receiving serial data, and got the idea into their head that the occasional delay now and then "improves stability".

Analog Stability
From the Datasheet of ATMEGA328 Page 240:
When the bandgap reference voltage is used as input to the ADC, it will take a certain time for the voltage to stabilize. If not stabilized, the first value read after the first conversion may be wrong.
So if you are doing multiple reads, you need to wait a few cycles.
Delays are not required when using auto-triggering:
When Auto Triggering is used, the prescaler is reset when the trigger event occurs. This assures a fixed delay from the trigger event to the start of conversion. In this mode, the sample-and-hold takes place two ADC clock cycles after the rising edge on the trigger source signal. Three additional CPU clock cycles are used for synchronization logic.
Also if reading different channels of the same ADC module, you need to provide a delay between the reads so that the analog MUX is positioned and the S&H capacitor is charged.
This information is from hardware perspective and I'm not sure if Arduino internal ADC routines compensate for those delays.
Digital Stability
From the digital read tutorial schmatic:

In the schematic, the push button is not electrically de-bounced. A delay in reading states would help de-bounce it in software.
As Nick Gammon suggested, they also improve serial flooding.


text:
Shaft Encoder Accuracy
So, first of all I just want to point out this code is from: Reading Rotary Encoders and is not mine.
I have a magnetic shaft encoder mounted on a regular DC motor, my problem is that I cannot receive the exact angle of the motor. The encoder outputs +1 each 90 degrees (I then multiply by 90). And is there any relationship between valx, valy, valz and the angle?
#define encoder0PinA 2
#define encoder0PinB 3
int rounds= 0;
volatile unsigned int encoder0Pos = 0;
unsigned int tmp_Pos = 1;
unsigned int valx;
unsigned int valy;
unsigned int valz;

boolean A_set;
boolean B_set;

int enA = 9;
int in1 = 10;
int in2 = 11;

void setup() {

  pinMode(encoder0PinA, INPUT);
  pinMode(encoder0PinB, INPUT);
  // encoder pin on interrupt 0 (pin 2)
  attachInterrupt(0, doEncoderA, CHANGE);

  // encoder pin on interrupt 1 (pin 3)
  attachInterrupt(1, doEncoderB, CHANGE);
  Serial.begin( 9600 );

  pinMode(enA, OUTPUT);

  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  analogWrite(enA, 225);
  Serial.begin (9600);
}

void loop(){
//Check each second for change in position

  if (tmp_Pos != encoder0Pos) {
    Serial.print("Index:"); Serial.print(encoder0Pos * 90,DEC);
    Serial.println();
    Serial.print("valx:");Serial.print(valx,DEC);
    Serial.println();
    Serial.print("valy:");Serial.print(valy,DEC);
    Serial.println();
    Serial.print("valz:");Serial.print(valz,DEC);
    Serial.println();
    tmp_Pos = encoder0Pos;
  }
}

// Interrupt on A changing state
void doEncoderA(){

  // Low to High transition?
  if (digitalRead(encoder0PinA) == HIGH) {
    A_set = true;
    if (!B_set) {
      encoder0Pos = encoder0Pos + 1;
      valx=analogRead(0);
      valy=analogRead(1);
      valz=analogRead(2);
    }
  }

  // High-to-low transition?
  if (digitalRead(encoder0PinA) == LOW) {
    A_set = false;
  }
}

// Interrupt on B changing state
void doEncoderB(){

  // Low-to-high transition?
  if (digitalRead(encoder0PinB) == HIGH) {
    B_set = true;
    if (!A_set) {
      encoder0Pos = encoder0Pos - 1;
    }
  }

  // High-to-low transition?
  if (digitalRead(encoder0PinB) == LOW) {
    B_set = false;
  }
}

Provide a link to the rotary encoder used.

Wiring?  Picture?

If the motor speed is fairly steady with only gradual speed up slowdown, you may be able to model it with a software locked loop running faster and adjusted to match the timing of the four pulses you do get.  You can then use that to interpolate the likely position at any point in time to a higher resolution.

If the encoder only gives +1 pulse per 90 degrees, you aren't going to get better than 90 degree accuracy out of it.
In the example code at the link, the val{x,y,z} are measured analog variables of some other thing that are sampled at each encoder lcoation:

My project is a data loger where three analogue inputs are sampled
  each time a rotary encoder pulse steps clockwise. On an Arduino, time
  is of the essence to get this data sampled and saved somewhere (I have
  not included the 'saving somewhere' part of this project yet.) In
  order to save some processor cycles, I have slightly redesigned the
  interrupt system to maintain a pair of boolean states outside of the
  interrupt loop.

These are not directly related to the positioning of the encoder, and there is no reason to think they provide angle information.


text:
Can a Arduino Uno handle all these components?
Its my first project with an Arduino, so please bear with the dumb questions.
For this project of mine, I need an Ultrasonic Sensor, a Gyroscope, a Buzzer, three push buttons and an 16x2 LCD.
Can I connect all these components at once to an Arduino Uno? I mean will I run out of pins or not? Should I go for a Mega 2560 (will have to buy one though).
Edit: a GSM sim800 as well lol

ultrasonic s. 2 pins, buzzer 1 pin, buttons 3 pins, gyroscope i2c? 2 pins, LCD i2c? same two pins, not i2c LCD  6 pins. Uno has 13 pins.

Yeah getting I2C for LCD, but I don' think the gyro comes with one. Here's the link to it: gyro

The gyro is I2C too

I think you're fine depends on the gyroscope model and lcd.
-For ultrasonic sensor thats 2 pins
-the lcd needs at least 6pins but with an i2c adapter you only need 2 pins
-3 push buttons 3 pins
-one pin for the buzzer
Plenty of room left on the uno

Thanks for replying. So if I get a i2c, I'll be good to go? Here are the links to the components: Gyro Ultrasonic I2C Buzzer


text:
Can't open serial monitor on Ubuntu (Teensy 3.2)
I am running a simple blink/hello world program on Teensy 3.2. The code is compiling and running fine but I can't see the serial output. When I try to open the serial monitor it gives me

"Board at /sys/devices/pci0000:00/0000:00:14.0/usb3/3-1 is not
  available"

The source code is pasted in below, and the terminal outputs below that.
I'm using Teensyduino 1.4.6 and Arduino IDE 1.8.9 running on Ubuntu 18.04. The 49-teensy.rules file has been copied to /etc/udev/rules.d/ as required.
The Tools > Port menu is greyed out, can't select it.
Any suggestions on what I am doing wrong? Why can't I see the serial output?
int led = 13;

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

void loop() {
  digitalWrite(led, HIGH);
  Serial.println("Hello (on) world");
  delay(1000);
  digitalWrite(led, LOW);
  Serial.println("Hello (off) world");
  delay(1000);
}

Terminal output below:
> /usr/local/arduino/arduino-1.8.9/arduino-builder -dump-prefs
> -logger=machine -hardware /usr/local/arduino/arduino-1.8.9/hardware -tools /usr/local/arduino/arduino-1.8.9/tools-builder -tools /usr/local/arduino/arduino-1.8.9/hardware/tools/avr
> -built-in-libraries /usr/local/arduino/arduino-1.8.9/libraries -libraries /home/hubert/Arduino/libraries -fqbn=teensy:avr:teensy31:usb=serial,speed=48,opt=o2std,keys=en-us -ide-version=10809 -build-path /tmp/arduino_build_530222 -warnings=all -build-cache /tmp/arduino_cache_588473 -verbose /home/hubert/Arduino/Blink_T32/Blink_T32.ino
> /usr/local/arduino/arduino-1.8.9/arduino-builder -compile
> -logger=machine -hardware /usr/local/arduino/arduino-1.8.9/hardware -tools /usr/local/arduino/arduino-1.8.9/tools-builder -tools /usr/local/arduino/arduino-1.8.9/hardware/tools/avr
> -built-in-libraries /usr/local/arduino/arduino-1.8.9/libraries -libraries /home/hubert/Arduino/libraries -fqbn=teensy:avr:teensy31:usb=serial,speed=48,opt=o2std,keys=en-us -ide-version=10809 -build-path /tmp/arduino_build_530222 -warnings=all -build-cache /tmp/arduino_cache_588473 -verbose /home/hubert/Arduino/Blink_T32/Blink_T32.ino Using board 'teensy31'
> from platform in folder:
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/avr Using core
> 'teensy3' from platform in folder:
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/avr Detecting
> libraries used...
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-g++
> -E -CC -x c++ -w -g -Wall -ffunction-sections -fdata-sections -nostdlib -fno-exceptions -fpermissive -felide-constructors -std=gnu++14 -Wno-error=narrowing -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=146 -DARDUINO=10809 -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3 /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp -o /dev/null
> Generating function prototypes...
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-g++
> -E -CC -x c++ -w -g -Wall -ffunction-sections -fdata-sections -nostdlib -fno-exceptions -fpermissive -felide-constructors -std=gnu++14 -Wno-error=narrowing -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=146 -DARDUINO=10809 -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3 /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp -o
> /tmp/arduino_build_530222/preproc/ctags_target_for_gcc_minus_e.cpp
> /usr/local/arduino/arduino-1.8.9/tools-builder/ctags/5.8-arduino11/ctags
> -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_530222/preproc/ctags_target_for_gcc_minus_e.cpp
> Compiling sketch...
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/precompile_helper
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3
> /tmp/arduino_build_530222
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-g++
> -x c++-header -O2 -g -Wall -ffunction-sections -fdata-sections -nostdlib -MMD -fno-exceptions -fpermissive -felide-constructors -std=gnu++14 -Wno-error=narrowing -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=146 -DARDUINO=10809 -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3 /tmp/arduino_build_530222/pch/Arduino.h -o
> /tmp/arduino_build_530222/pch/Arduino.h.gch Using previously compiled
> file: /tmp/arduino_build_530222/pch/Arduino.h.gch
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-g++
> -c -O2 -g -Wall -ffunction-sections -fdata-sections -nostdlib -MMD -fno-exceptions -fpermissive -felide-constructors -std=gnu++14 -Wno-error=narrowing -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=146 -DARDUINO=10809 -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I/tmp/arduino_build_530222/pch -I/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3 /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp -o
> /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp.o Compiling
> libraries... Compiling core... Using precompiled core:
> /tmp/arduino_cache_588473/core/core_teensy_avr_teensy31_usb_serial,speed_48,opt_o2std,keys_en-us_d47a876dd1beb90b689e2017ddeb665b.a
> Linking everything together...
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-gcc
> -O2 -Wl,--gc-sections,--relax,--defsym=__rtc_localtime=1559084002 -T/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3/mk20dx256.ld
> -lstdc++ -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -o /tmp/arduino_build_530222/Blink_T32.ino.elf
> /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp.o
> /tmp/arduino_build_530222/../arduino_cache_588473/core/core_teensy_avr_teensy31_usb_serial,speed_48,opt_o2std,keys_en-us_d47a876dd1beb90b689e2017ddeb665b.a
> -L/tmp/arduino_build_530222 -larm_cortexM4l_math -lm /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-objcopy
> -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /tmp/arduino_build_530222/Blink_T32.ino.elf
> /tmp/arduino_build_530222/Blink_T32.ino.eep
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-objcopy
> -O ihex -R .eeprom /tmp/arduino_build_530222/Blink_T32.ino.elf /tmp/arduino_build_530222/Blink_T32.ino.hex
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/stdout_redirect
> /tmp/arduino_build_530222/Blink_T32.ino.lst
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-objdump
> -d -S -C /tmp/arduino_build_530222/Blink_T32.ino.elf /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/stdout_redirect
> /tmp/arduino_build_530222/Blink_T32.ino.sym
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-objdump
> -t -C /tmp/arduino_build_530222/Blink_T32.ino.elf /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/teensy_post_compile
> -file=Blink_T32.ino -path=/tmp/arduino_build_530222 -tools=/usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/ -board=TEENSY31 Opening Teensy Loader... /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-size
> -A /tmp/arduino_build_530222/Blink_T32.ino.elf Sketch uses 13468 bytes (5%) of program storage space. Maximum is 262144 bytes. Global
> variables use 4564 bytes (6%) of dynamic memory, leaving 60972 bytes
> for local variables. Maximum is 65536 bytes.
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/teensy_post_compile
> -file=Blink_T32.ino -path=/tmp/arduino_build_530222 -tools=/usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools -board=TEENSY31 -reboot -port=/sys/devices/pci0000:00/0000:00:14.0/usb3/3-1 -portlabel=(null) -portprotocol=(null)
Board at /sys/devices/pci0000:00/0000:00:14.0/usb3/3-1 is not available

And if you select the actual /dev/ttyACM0 serial port and try again...?

Go into the Tools menu, then Port, and select the port.

Have you installed the "49-teensy.rules" file as described in the tutorial?

Have updated question: the Ports menu is greyed out and the "49-teensy.rules" is installed.

It looks like you haven't even managed to program the board - so there is no serial port for you to use.


text:
Construct Strings with UTF-8 characters from data
I am printing some ASCII art to the Serial monitor from Arduino UNO, with some success. However, using string literals uses more memory than I would like. I wanted to try constructing the strings/chars from other data types so that I can manipulate the data and print the ascii art without storing it in string literals.
However, I have found that there seems to be no way to print UTF-8 characters other than from a string literal. Is this the case? Is there no way to construct a string containing characters that have numeric values that are too big for char?
As an example, to print "▓" works fine as a String literal but, it seams, no other way.
Serial.println("▓");                         // works fine
Serial.println('▓');                         // char can't store value
Serial.println(String('▓'));                 // char can't store value
Serial.println(0x2593);                      // just prints the numeric value
Serial.println((char)0x2593);                // char can't store value
Serial.println((wchar_t)0x2593);             // doesn't work
Serial.println(String(0x2593));              // doesn't work
Serial.println(String((wchar_t)0x2593));     // doesn't work

Similarily with write() instead of print():
Serial.write("▓");                  // Works fine
Serial.write('▓');                  // char can't store value
Serial.write(0x2593);               // just prints the numeric value
Serial.write((char)0x2593);         // char can't store value
Serial.write((wchar_t)0x2593);      // doesn't work

I also tried deriving new component strings from a string literal using substring() and charAt(). Neither works. Both produce � in the output.
String((char)65) constructs the string "A" from the numeric value 65. Neither String((char)0x2593) nor String((wchar_t)0x2593) produce the desired results. Is there a way to construct a string from numeric values that are too big to store in 'char'?

try Serial.println("\u2593");

I would try printing  byte arrays that contain the UTF-8 serialisation, not the numeric code point.  For example \xe2 ,\x96, \x93 instead of \u2593

As you have noticed, Serial doesn't know how to deal with wchar_t.
If you are building your strings algorithmically from Unicode code
points, you need to convert those code points to UTF-8 for printing. I
am not aware of any built-in function that does that. You may want to
search the library manager for a library providing this functionality.
Alternatively, you could write the conversion yourself: it is not that
complicated. For example, here is a function that converts any code
point from the BMP (i.e. < 216) to an UTF-8 string:
// A BMP multi-byte character, with terminating NUL byte.
struct Mbchar {
    char utf8[4];
};

// Convert a wide character to UTF-8. Only works within the BMP.
Mbchar wchar_to_utf8(wchar_t c) {
    Mbchar result;
    if (c < 128) {               // 0xxx.xxxx
        result.utf8[0] = c;
        result.utf8[1] = 0;
    } else if (c < 2048) {       // 110x.xxxx 10xx.xxxx
        result.utf8[0] = 0xc0 | (c >> 6);
        result.utf8[1] = 0x80 | (c & 0x3f);
        result.utf8[2] = 0;
    } else {                     // 1110.xxxx 10xx.xxxx 10xx.xxxx
        result.utf8[0] = 0xe0 | (c >> 12);
        result.utf8[1] = 0x80 | (c >> 6 & 0x3f);
        result.utf8[2] = 0x80 | (c & 0x3f);
        result.utf8[3] = 0;
    }
    return result;
}

Keep in mind that, depending on the Arduino you are using, wchar_t may
not support characters outside the BMP. The AVR-based Arduinos
definitively don't.
This function can be used like this:
Serial.println(wchar_to_utf8(0x2593).utf8);  // prints “▓”

Might be worth adding that their '▓' usage will not produce a wchar_t type, it'll just produce some useless char value. They'd need L'▓' which they should be able to use in conjunction with your code in Serial.println(wchar_to_utf8(L'▓').utf8);


text:
Arduino wrap or subclass print() to work with multiple Serial
I am writing an Arduino program that uses Bluetooth on Serial1 to print text to a Bluetooth terninal on an Android phone and also normal Serial to print text to the serial monitor on a laptop. I would like to wrap the Serial.print() and Serial.println() functions so that they work with either or both Serial and Serial1. For example the code below works fine depending on the values of the global variables. But this only works for single chars, but print() and println() can take a very wide variety of datatypes. If I also define overloading functions for int and String types it works fine, but that is a very verbose and maybe fragile solution, it also ignores the optional inputs to the underlying functions. What is the proper way to do this ?
void print(char x) {
  if (g_use_Serial)
    Serial.print(x);
  if (g_use_Serial1)
    Serial1.print(x);
}

void println(char x) {
  if (g_use_Serial)
    Serial.println(x);
  if (g_use_Serial1)
    Serial1.println(x);
}

I have implemented the solution suggested and it works nearly perfectly. There seems to be a problem with the new line characters on the bluetooth (Serial1) connection.
The code is:
class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

void setup()  {
  Serial.begin(9600);
  Serial1.begin(9600);
  delay(1000);
}

void loop() {

  out.use_Serial = true;
  out.print("Printed to USB only.\n");
  out.use_Serial1 = true;
  out.print("Printed to both USB and BT.\n");
  out.use_Serial = false;
  out.print("Printed to BT only.\n");
  out.use_Serial1 = false;

  delay(3000);
}

The output on the USB Serial monitor is as expected:
Printed to USB only.
Printed to both USB and BT.
Printed to USB only.
Printed to both USB and BT.

The output on the Bluetooth terminal is not as expected, the new lines are not in the right position:
Printed to both USB and BT.Pri
nted to BT only.
Printed to both USB and BT.Pr
inted to BT only.
Printed to both USB and BT.Pr
inted to BT only.
Printed to both USB and BT.Pr
inted to BT only.

Any suggestions on how to fix this. Are there other function members that need to be re-implemented to make this work properly?
Many thanks for high quality answers so far.

No. The general technique should work OK. Perhaps the Bluetooth can't handle more than 30 bytes before throwing in a newline of its own. In any case, why not use println rather than print and then supplying your own newline?

I tried with both println("...") and print("...\n"), same behavior with both. I hard coded the same outputs with Serial and Serial1 and it works fine so nothing to do with Bluetooth. It is something to do with the new class.

The Bluetooth link should see the exact same byte stream whether you print through Serial1 or this class. Only the timing will be slightly different, so it could be that whatever receives the data is sensitive to the timing of the incoming bytes. This could be mitigated by overriding virtual size_t write(const uint8_t *buffer, size_t size).

Should that look like this:     virtual size_t write(const uint8_t *buffer, size_t size) {         if (use_Serial) Serial.write(buffer, size);         if (use_Serial1) Serial1.write(buffer, size);         return 1;     }

I doubt the timing will matter. Those bytes will be buffered and sent out by an interrupt service routine.

The Bluetooth terminal might not recognize newlines. Can you prove it does?

Some LCD screens don't recognize newlines for example. You have to explicitly tell them to go to a new line and/or column.

@NickGammon. Update. If I insert a 100ms delay before using Serial1 the problem goes away. But that is not acceptable for the final program. The problem seems to be the same with direct use of Serial1 as it is with DualPrint so the original question is answered. A new question is how to control the position of new line characters in the Bluetooth terminal.

You can create a class derived from Print that forwards its output to
either or both Serial and Serial1. The only method you need to
implement for this to work is write(uint8_t):
class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

You would use it like this:
out.use_Serial = true;
out.println("Printed to Serial only");
out.use_Serial1 = true;
out.println("Printed to both Serial and Serial1");
out.use_Serial = false;
out.println("Printed to Serial1 only");

Note that with this approach, unlike yours, printing number will format
them as text only once, and the underlying Serial and Serial1 will
only handle the resulting characters.

Edit: To answer the question in OP's comment, the construct
class ClassName
{
    ...definition...
} classInstace;

is a shotcut for
class ClassName
{
    ...definition...
};
ClassName classInstace;

A very similar construct exists in plain C:
struct struct_name {
    ...the struct fields...
} struct_instance;

for advanced users I would override availableForWrite() and flush() too

@Edgar Many thanks for this, very helpful. One request, I am more experienced at C than C++ so the class definition is unfamiliar. In the usage example out is an instance of DualPrint, is that right? How is it declared? DualPrint out;??

@HubertB: Yes, out is an instance of DualPrint. See expanded answer.

Edgar & @Juraj I have updated the question with a progress report on implementing the suggested solution. It works almost perfectly except for new lines in wrong sequence in BT terminal. Any suggestions? Is this related to flush() or other functions that also need to be re-implemented?

I have implemented this, thank you (in this case to write to a SD error file) and noticed that the Serial.write() is much slower on the serial monitor than Serial.print() - any reasons for this and is this an issue?

@CestLaGalere: No idea why. It would be difficult to answer that question without more details on what you are doing, and a minimal testable example.

Having created a sample that just logs to Serial there is no slowdown, the conclusion is that writing to the SD card to log to a file is still going on whilst trying to write the Serial data, slowing the Serial write down.  I am not sure if a worked example would therefore help as needs a SD card attached to the ESP to recreate. Thanks for the feedback

@CestLaGalere: It may well be the case that writing to the SD card is slow if done one character at a time, but is faster if a whole “message” is written at once. To test this idea you may want to implement virtual size_t write(const uint8_t *buffer, size_t size) in DualPrint that just does write(buffer, size) to the underlying streams. See if that speeds things up.

Thanks @edgar-bonet, that certainly seems to be the case, having implemented this it is much faster.


text:
7 segment display with common anode
I am brand new to electronics. I am trying to use a seven segment display breakout module with my arduino uno. My problem is that the display has a common positive instead of negative common. How do I make this work? As far as I am aware, all the arduino pins output positive with the exception of the ground, which is the negative common.

You might want to add what driver you are using...Max7219?

This answer assumes Arduino Uno. For other types, refer to the documentation.
Ardino pins are not positive per se: you can change the voltage with digitalWrite() to either 0V (LOW, equal to the GND pin) or 5V (HIGH, equal to VCC).
The difference between a common cathode or common anode will be the flow of the current. With a common cathode (negative), the pins will need to provide current ("source" current), with a common anode, the pins will need to receive current ("sink" current).
There is a description for the limits of sourcing and sinking:

Pin SOURCE Current Limitations:
20 mA at VCC = 5 V
Pin SINK Current Limitations:
20 mA at VCC = 5 V

Please also read about the maximum total of 150 mA sourcing and 100 mA sinking.
You'll need to compare those current limits with the current requirements of your 7 segment display. My guess is that your a 7 segment display has 1 VCC pin and 7 output pins that you connect to the Arduino. The limiting factor is the total maximum here. The Arduino can handle 100 mA/7 = 14mA in the worst case. If that's enough for your 7 segment, it should work.
For example, this one works with 10 mA, so it would be compatible with Arduino. Make sure you have resistors in place.

Thank you very much for your sagely wisdom! I was so wound up over trying to get an answer to my problem, that I neglected to mention that I am using an Arduino Uno! Again, thank you so much for your time and effort.


text:
library problem ? how to solve this?
Arduino: 1.8.11 (Windows 10), Board: "ESP32 Dev Module, Disabled, Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS), 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, None"
Multiple libraries were found for "WiFi.h"
 Used: C:\Users\User\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\WiFi
 Not used: C:\Program
 In file included from C:\Users\User\Documents\Arduino\libraries\async-mqtt-client-master\src/AsyncMqttClient.h:4:0,
             from C:\Users\User\Desktop\sketch_jul13a\sketch_jul13a.ino:3:

C:\Users\User\Documents\Arduino\libraries\async-mqtt-client-master\src/AsyncMqttClient.hpp:9:22: fatal error: AsyncTCP.h: No such file or directory

compilation terminated.

exit status 1
Error compiling for board ESP32 Dev Module.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Not used: C:\Program - is that where you put your Arduino code, or is something going wrong with C:\Program Files (x86)?

sir what i have to do for this ? pls tell

i updated the ide but again it show same error

Then install the Async TCP library, or whag ever library gives you the file AsyncTCP.h. The compiler complains, that the file is missing, so most likely you didn't install all the needed libraries

do what it tells you to do at the end of the printout


text:
Determine what size power supply I need to run stepper motors
I have recently purchased two 7.4V, 1A, Planetary Gear Unipolar Stepper Motors as well as two Cytron 3A 4-16V Dual Channel DC Motor Drivers. I was told that I would need these to run the motors off an Arduino board. The question I forgot to ask was: what size power supply I would need for something like this?
I am just looking to learn how to code these arduino boards. I was hoping to get something that I could plug into a wall to save me from buying multiple batteries.

You can't run these off the Arduino board for several reasons:

the Arduino board does not provide 7.4V on any pin, only 5V (model dependent, but never 7.4 V)
the Arduino board can provide about 20mA per pin, never 1A or higher
even if the board would only need to pass the voltage on, the total current were >2A. This would possibly fry the board.

So, what you need is: a power supply with constant 7.4V or a regulated one where 7.4V is within the range. From this power supply you will power 3 devices only:

one arduino board via the Vin pin (accepts 7 to 12 V, so 7.4V is ok)
two Dual Channel DC Motor Drivers (accepts 4 to 16V, so 7.4V is ok)

From each motor driver, you will power

one Planetary Gear Unipolar Stepper Motors (designed for 7.4V)

Now, let's sum of the currents:

Arduino Uno board without any peripherals: ~45 mA
two Stepper motors: 1000 mA each
two motor drivers: hard to say. In theory, the motor driver would not consume power by itself, just forward it to the motors. In practice, it cannot forward everything. The driver will get hot and thus consume some power itself. The datasheet is not specific about the power consumption. Let's assume a 70% efficiency = 30% loss. 30% of 1000mA is 300mA each.

The total current needed for this setup is 2645mA. Depending on your budget you could buy a 3A or 5A power supply. At constant 7.4V, that's 23W or 37W. For a regulated 0V to 20V power supply, go for 60W or 100W.
A cheap regulated one should be at ~50 USD. Expect those to be loud because of bad cooling / fan noise.


text:
Issues with connecting XBee to Arduino Uno R3
I have an Arduino Uno R3, Wireless Proto Shield and a XBee XB24-AWI-001 all hooked together. I'm using X-CTU software to access the XBee and change the properties of it. I did a little research and found out that if I want to access the XBee, I have to connect the GND to the RST pin (on the Proto Shield) or hold the RESET button on the board. This method works and when I do that, I can find the XBee on X-CTU.
The question is - why do I have to do that? I'm probably wrong, but as far as I understand, if I have my Arduino connected to the computer, I'm accessing the ATmega microprocessor and that's the reason I can't access the XBee, but when I do the reset, I'm constantly resetting the microcontroller and that's the reason why I can access the XBee? Hopefully someone can explain this...
The link where I found the information about resetting (or removing) the ATmega microproccesor, Using Arduino to Connect Xbee Serial to Computer.

@Greenonline Done!

I am slightly surprised that you can actually talk to the XBee from your PC over USB with the XBee in the shield. XBee shields are generally designed for the XBee to be used by the Arduino only. The fact that you can actually talk to the XBee from the PC using X_CTU with the XBee in the Arduino shield, by holding down reset, seems to either be a quirk or a feature of the shield1.
Generally to use X-CTU to talk to the XBee, one would use an XBee explorer board or a Development board. One would configure the XBee completely in the Explorer dongle and then transfer the XBee to the shield for the Arduino to use it.
See the thread on the Digi forums, xbee s1 xctu arduino:

The shield is not design for writing and reading firmware to and from
the XBee module. It is only designed for basic two way communications.
If you want to read or write firmware to the module, you need to use a
board that is designed for it such as the XBIB boards from Digi.

See also Can an XBee be programmed with an XBee Shield.
However, hopefully someone with more knowledge of the internals of an Uno and XBee shield than I, could explain the actual electrical reasoning behind this issue. I have attempted to explain it below in the footnote.

1 Having said all of that, looking at some of my XBee shields, a couple have a microswitch, that enables the XBee to talk to either the Arduino or the USB, but not both at the same time. So, I guess that the need to hold the reset on your shield is because you do not have such a microswitch.
So the reason being, is that the Arduino and the USB can not talk to the XBee at the same time, as there would be conflict on the Rx and Tx serial lines - see this thread, UNO + Sparkfun's Xbee Shield Always Reset if Receiving Data From X-CTU Terminal which hints at the same thing. Two comments of note from that thread are:

It would be a lot simpler to debug the issue if you put the switch in the other position, and used SoftwareSerial to talk to the XBee and Serial to talk to the PC. Using one port to talk to two devices IS going to frustrate you no end.

and

Note that a communication application connected to an arduino that opens a com port, sends data, then closes may cause the arduino to reset.

As a (really wild) guess, I would imagine that the USB-to-TTL IC's DTR line, or equivalent (?), is [logically] tied to the Arduino's RST line, so that if the PC tries to communicate to the XBee, it ends up resetting it, rather than signalling to the XBee that it is ready to communicate.
Note: The USB-to-TTL IC could be a FTDI, ATmega 4U2/8U2/16U2 or an FTDI clone, depending on the variety of Uno that you possess.
Addendum
I do wonder why the switch is there, if it doesn't end up working correctly. Regardless, I would still get a $3 explorer board clone to use with X-CTU. Be careful which one you buy as not all of them work with OS X, if you use a Mac, see the end of USB-TTL interface devices on OS X. That explorer,  XBee USB Adapter Bluetooth Bee FT232RL USB to Serial Port Module for PC Arduino, is good value for money and compatible with WinTel, LinTel and OS X machines:

About the microswitch- I do have it on the shield! It can either be set to micro or usb, but i've tried both of them and X-CTU still did not find the Arduino.. I guess the best I can do right now to use Xbee for my project is to just restart the board all the time to configure the xbee and then remove the wire from gnd to reset and see where that takes me... Hopefully i'll be able to use it in some way...

@L2PA - Interesting, so in that case the Arduino forums link in my answer, UNO + Sparkfun's Xbee Shield Always Reset if Receiving Data From X-CTU Terminal, is applicable to you. I do wonder why the switch is there, if it doesn't end up working correctly. Regardless, I would still get a $3 explorer board clone to use with X-CTU. Be careful which one you buy as not all of them work with OS X, if you use a Mac, see the end of USB-TTL interface devices on OS X. That explorer is good

Sorry for late response. I'll check out the links later and let you know if it worked. ;)

I guess I understood that there's no other way how I'll be able to access the Xbee without resetting the board (because of the resources that I have). Thanks for the answer and research you did!