I need help with U8GLIB library I have a project which uses a 128x64 oled display. I have to use the U8GLIB as the available displays change from SSD1306 to SSH1106 depending on when you buy it which that library covers both displays.
I don't want the program for the display to eat up the memory of the arduino so I use u8glib instead of u8g2! for this project I need to display numbers 0 to 9, decimal point, omega (ohm symbol) and metric prefixes such as μ,m,k,M, etc...
I first tried to create a bitmap font (.bdf) and convert it to a C file because that was what was hinted at on a few posts. There were no tutorials and after messing about with the different formats and trying to add the font to the library I just gave up because I couldn't figure it out. Instead I decided to use this website which generates bitmaps from TTF files:
https://littlevgl.com/ttf-font-to-c-array
Now I can use those bitmaps and have my few characters which use very little memory (about 20% as opposed to more than 70% using a complete symbols font in u8g2!) but this makes things really awkward as I have to translate every number I get into separate digits and then into a bitmap! also I can only use font sizes which have a height in multiples of 8 because for some weird reason this library expects width in number of bytes and height in number of pixels!

cnt: Number of bytes of the bitmap in horizontal direction. The width
of the bitmap is cnt*8.

so I can do fonts of size 48 for example, but not 50 or 52 which would be more suitable for my application!
I'm not sure if anyone else has had this issue but there must be a way to display the characters you want without destroying your entire memory space like u8g2 does! Just getting to this point took me 2 days (on the left there is a 0.96" SSD1306 and on the right there is a 1.3" SSH1106):

Please help if you have any idea on how to deal with this library as it's driving me insane at the moment!

While this may not exactly answer your question, there may be some information about u8g2lib that you have not seen. The library source code is linked here: u8g2lib

Within that repository is the FAQ documentation which includes such gems as:

  Q: U8g2 requires a lot of memory. How to reduce this?
  - Visit https://github.com/olikraus/u8g2/wiki/u8g2optimization
  - Disable U8g2 features if possible (see u8g2.h)
  - Limit the font size. If possible avoid "f" fonts, instead use "r" or "n" fonts
  - If the I2C interface is not required, then uncomment #define U8X8_HAVE_HW_I2C in U8x8lib.h   (Background: Due to a problem in
  Wire.h, the I2C Arduino lib is always included)

and

  Q: How can I generate my own font. A: The font must be available in
  bdf file format. Then use bdfconv to generate the font data. The font
  data can be pasted into an existing file of your project. There is
  also a nice Windows Bitmap Font Editor "Fony"
  (http://hukka.ncn.fi/?fony)  which can export .bdf files. A copy of
  Fony 1.4.7 is available here:
  https://github.com/olikraus/u8g2/tree/master/tools/font/fony

The tools/font directory includes several utilities, including what looks like one that converts OTF fonts to BDF format

Once you get a BDF format font, you use bdfconv to create the C file that holds the font array. One of the arguments for bdfconf is the -m 'map' option. You can place in there a list of Unicode ranges that limit which characters get included. So, you can create a font that has ONLY the characters you need.

For example -m '45-46,48-57,77,107,109,181,937' gets you minus, decimal, 0-9, 'M', 'k', 'm', mu, omega. Unicode character map at https://unicode-table.com/en/

The benefit to creating a font is that the u8g2lib library itself does all the mapping to bitmaps and calculating the character widths, etc. so you don't have to.


Flash Arduino Due via UART I would like to write code in Arduino language, compile it in the Arduino IDE, grab the resulting binary code, and flash it to the Due via the TX/RX UART pins, bypassing both the USB Programming Port and Atmel16U2 chip. Before the UART flash, I am manually toggling the Erase and Reset pins on the Due to initiate a hard reset of the SAM3X chip, and SAM-BA now waits for the code. I would like to know: can I directly grab the binary code compiled by the Arduino IDE and give it to SAM3X via UART or is there extra code baked into that binary by the Arduino compiler that would cause this method to fail?

It depends
This may not have been the answer the question was originally asked, but now it appears to be: it depends on which revision of the Due you have.
The V03 schematics on the website show a 74LVC1G125DCK part designated IC10 that is being used to translate the 5V TXD signal from the ATMega16u2 (being used as a serial transceiver) to the 3.3V logic needed for the ATSAM3X8.  As drawn the TXD line is connected to the buffer/level converter input but it is also connected to its active-low output-enable line.  In effect, they're not just using it to convert logic levels, they are also converting the signal to a kind of open collector signal.  Looking at the ATSAM3X8 datasheet shows that, yes, there is an internal pullup in the pin receiving the signal.
If your Due is of this design, then yes, you can program the chip by attaching a USB->logic-level-serial adapter to D0 and D1 (USART) pins and program using the SAM-BA protocol. You need to make sure you are not sending over the on-board serial transceiver while this is happening so as to not have it wired-ORing its data with your adapter. The ATMega16U2 has code in it that controls the ATSAM3X8's erase pin, as well as reset pin, by request of the PC via serial-over-USB's DTR and RTS.  Since the erase signal is not routed to outside of the Due (on its headers), you would need to use the erase button, barring some modification to the board.
However, not all Due are of this design. Some DUE boards have the output-enable of 74LVC1G125DCK hard-wired active rather than connected to the transceiver TXD; so on these designs it does not behave as open-collector, and the ATMega16u2 serial transceiver is actively driving the line when idle.  This destroys the ability to program the board over UART via pins D0 and D1.  It does however make cleaner rising edges.  Without modifying the board, no, you can't do it with this design.
Identification
So far as I can tell, whether or not your ATMega16U2->ATSAM3X8 connection is open collector/UART-programming-friendly follows the location of the buffer part.  The chip is an SC70 package, a small 5-pin thing that looks a bit like SOT23-5.  If it is located off the ATMega16U2 itself it seems you have a open-collector configuration, again so far as I've been able to tell.  If it is located next to D0, between D0 and the "COMMUNICATION" header, then you have one that drives-high.
If you have a scope, you can put it on D0 and watch the edges generated when you send traffic from the PC over the ATMega16U2 at higher baud rates.  You will either see characteristic open-collector rising edges or you won't and that will answer the question.


Thermistor value correct on Uno backwards on Nano EDIT: upon further investigation: I found out that if I wired it Thermistor > resistor > GND values go one direction. If I wired it Thermistor > Resistor > 5v, it goes the other direction. So my new question: Which way is correct? One sketch assumes it works one way, and one the other.

I have some Thermistors from here. I have an Arduino Nano and an Arduino Uno, both set up identically with pictures of the wiring below. On the sketch below, when I heat up the thermistor the value increases on the Uno and decreases on the Nano.

// which analog pin to connect
#define THERMISTORPIN A0
// resistance at 25 degrees C
#define THERMISTORNOMINAL 10000
// temp. for nominal resistance (almost always 25 C)
#define TEMPERATURENOMINAL 25
// how many samples to take and average, more takes longer
// but is more 'smooth'
#define NUMSAMPLES 5
// The beta coefficient of the thermistor (usually 3000-4000)
#define BCOEFFICIENT 3950
// the value of the 'other' resistor
#define SERIESRESISTOR 9800

int samples[NUMSAMPLES];

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

void loop(void) {
  uint8_t i;
  float average;

  // take N samples in a row, with a slight delay
  for (i=0; i< NUMSAMPLES; i++) {
       samples[i] = analogRead(THERMISTORPIN);
   delay(10);
  }

  // average all the samples out
  average = 0;
  for (i=0; i< NUMSAMPLES; i++) {
     average += samples[i];
  }
  average /= NUMSAMPLES;

  Serial.print("Average analog reading ");
  Serial.println(average);

  // convert the value to resistance
  average = 1023 / average - 1;
  average = SERIESRESISTOR / average;
  Serial.print("Thermistor resistance ");
  Serial.println(average);

  float steinhart;
  steinhart = average / THERMISTORNOMINAL;     // (R/Ro)
  steinhart = log(steinhart);                  // ln(R/Ro)
  steinhart /= BCOEFFICIENT;                   // 1/B * ln(R/Ro)
  steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
  steinhart = 1.0 / steinhart;                 // Invert
  steinhart -= 273.15;                         // convert to C

  Serial.print("Temperature ");
  Serial.print(steinhart);
  Serial.println(" *C");
  Serial.println();

  delay(1000);
}

On the sketch below, the Uno is backwards and the Nano is correct. I'm sure there's something simple I'm missing, but I sure can't find it. Any suggestions?

#include <math.h>

double Thermistor(int RawADC) {
 double Temp;
 Temp = log(10000.0*((1024.0/RawADC-1)));
 Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
 Temp = Temp - 273.15;
 Temp = (Temp * 9.0)/ 5.0 + 32.0;
 return Temp;
}

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

void loop() {
  int val;
  double temp;
  val=analogRead(7);
  temp=Thermistor(val);
  Serial.print("Temperature = ");
  Serial.print(temp);
  Serial.println(" F");
  delay(1000);
}

Nano Wiring

Uno Wiring

There is no "correct" way. The thermistor and the resistor combine to make a voltage divider. Whether the thermistor is connected to +5V (AKA R1) or to GND (AKA R2) determines the formula to use to calculate the resistance.

The general form is:

          R2
Vout = ------- x Vin
       R1 + R2

To solve for R2 (thermistor connected to GND) you re-arrange to:

                 1
R2 = R1 x --------------
          (Vin/Vout) - 1

To solve for R1 (thermistor connected to +5V) it's:

     R2 x Vin
R1 = -------- - R2
       Vout

Vin, of course, is 5V, and Vout is a voltage you calculate from the analog reading on the Arduino.

Once you have the resistance you can then calculate the temperature. That part doesn't change regardless of the orientation of the thermistor.


Working on a simple door lock this is my first project on an Arduino platform. My aim is to build up a door lock unlockable by playing a short melody on a one-octave piano keyboard. I think the idea is cool!
I'm thinking at everything, but I can't figure out how to make Arduino move something (which in my case would be the proper door lock). I thought about a little motor, but I don't know if it is or not  feasible...
To be clear, what I want to do is a simple door lock like this
(or even simpler) being moved from an Arduino program. How can I do that?

You want a solenoid.

Looks like people sell ones which are specifically made for door locks.


digital input pins on arduino nano with standard firmata and pyfirmata are always 'None' I have connected pin D2 on my arduino nano to high, and tried it out with an arduino c program and it works.  However, when I load standard firmata onto the the controller from the arduino IDE and try the following python program:
import pyfirmata

board = pyfirmata.Arduino('/dev/ttyUSB0')

for x in range(2,14):
    print("%s %s" % (x, board.get_pin("d:%s:i" % x).read()))

I get this:
$ venv/bin/python test.py
2 None
3 None
4 None
5 None
6 None
7 None
8 None
9 None
10 None
11 None
12 None
13 None

I can write digital pins with fermata and pyfirmata, but I can't read.
I have also tried this:
import pyfirmata

board.digital[2].mode = pyfirmata.INPUT
board.digital[3].mode = pyfirmata.INPUT

for x in range(2,14):
    print("%s %s" % (x, board.digital[x].read()))

and other combinations, and always get None
(disconnecting the wire in the picture doesn't change anything either)

I have also just repeated the experiment with an arduino uno and get the same result

so I guess my questions are:

Can anybody spot anything obvious that I am doing wrong?
Can anybody confirm that pyfirmata input ever works?
What did you do that I am not doing?

"None" indicates that there is no data to be found by read() because the incoming serial stream has never been serviced.  Launch an Iterator to start a new Python thread that services the serial port in the background.
it = pyfirmata.util.Iterator(board)
it.start()


What is the I2C address of a sensor? I have connected BMP180 sensor:

to Arduino and was able to read its values with appropriate samples (from Adafruit BMP085 Library and Adafruit BMP085 Unified).

Apparently, this sensor is sending information via I2C bus.

However, I2C protocol assumes addresses of connected devices.

What are addresses in my case? How to know and/or change them?

Is it possible to connect several BMP180 to a single Arduino?

Line 30 in Adafruit_BMP085.h clearly give you the address of sensor. Looks like the address is fixed meaning the only way you can connect several of these sensors is using a i2c multiplexer


3-instruction remote machine coding Arduino Atmel chip over a serial line from a tethered (host) PC I'm trying to write a program for AVR Atmel 328 chip on Arduino Nano board that will allow me to send machine code instructions to the chip over a serial line, run/execute them on the chip, and interrogate the results by reading chip memory and sending the contents back over the serial line.  This is the genesis of the idea: 3-instruction Forth by Frank Sergeant.
The remote-store and remote-fetch instructions appear to be working fine, but I've not been able to get the remote-call instruction (XCALL() function) to work. The approach I've taken is to coerce a 16-bit address into a subroutine by casting it as a function pointer.
Below is the code that is running on the Arduino Nano (compiled in the Arduino IDE and uploaded using the USB cable via the bootloader)
Any insight would be greatly appreciated!  (I can add diassembled code, my remote instructions etc, if that helps).
Thanks in advance!
// Remote serial development platform for machine coding ArduinoNano/ATmel328, AKE, Jun 9, 2020

// global variables
unsigned char byt;                  // command token from host
unsigned char mem[255];             // memory window under programmatic control
unsigned char dat;                  // data byte from host
unsigned char adr_lo;               // address from host, low byte first
unsigned char adr_hi;
unsigned short adr;                 // combined 16-bit address
typedef void (*GeneralFunction)();  // template to call memory address (as a subroutine)

void setup() {
  Serial.begin(9600);              // Turn UART serial protocol ON for comms with host PC
  Serial.write(0xFF);              // magic number to verify transmission
  Serial.write(0xFE);
  Serial.write((int) mem);         // Informs you of the writeable address space available (LSB, MSB) for tethered memory access
  Serial.write((int) mem>>8);
}

char get_byte(void) {
    while (!(Serial.available()>0)) { delay(50); }
    return Serial.read();
}
short get_adr(void) {
    adr_lo=get_byte();
    adr_hi=get_byte();
    return ( (short)adr_hi<<8 )   |   (short)adr_lo;
}
void xstore() {             // Instruction 1 = xstore(data,adr_lo,adr_hi).  Store byte from host at indicated address in target.
    dat=get_byte();
    adr=get_adr();
    *(char *)adr=dat;
}
void xfetch() {             //  Instruction 2 = xfetch(adr_lo,adr_hi).  Read byte from target memory and return to host.
        adr=get_adr();
        dat=*(char *)adr;
        Serial.write(dat);
}
void xcall() {              //  Instruction 3 = xcall(adr_lo,adr_hi).  Execute subroutine in target memory from indicated address.
                            //  WARNING!  User must have stored RET instruction to send control back to serial monitor.
        adr=get_adr();
        GeneralFunction fGf=adr;
        fGf;
}

void loop() {
    byt = get_byte();               // user specified instruction token (1,2,3)
    if(byt == 0x01 )      { xstore(); }
    else if (byt == 0x02) { xfetch(); }
    else if (byt == 0x3 ) { xcall(); } // else ignore any other serial inputs
}

The AVR CPU cannot execute instructions from RAM. It's not a question of what the compiler can do or should be able to do, the physical chip itself cannot do it. There is simply no physical pathway between the RAM and the instruction decoder in the CPU.
Instructions can only be executed directly from Flash memory. That is how the chip works. You can only execute code that you send over serial if you first erase a page (or more) of Flash memory then burn the incoming code into that page. You can then call the start of that page's address and your code will execute.
But there is another caveat there: only code running in the bootloader flash area is allowed to modify the flash memory. That means your code can't do it, only the bootloader. That doesn't mean that the bootloader has to be running, but the code that you execute has to reside there.
There is an alternative version of the Optiboot bootloader that can provide flash writing facilities to a user program, but I have no experience using it so can't assist with that.


Switching external power supply to 5V cooling fan with an Arduino and 2N2222 transistor I'm using a 2N2222 transistor as a low-side switch to turn a 5V computer fan on and off with an Arduino digital pin, which responds programmatically to a button press - i.e. the relevant digital pin is switched from LOW to HIGH for a determined time in response to a button press recorded on A0.

My circuit looks like this:

And here's my code:

#define btnPin A0
#define signalPin 6

void setup() {
  pinMode(btnPin, INPUT_PULLUP);
  pinMode(signalPin, OUTPUT);
  digitalWrite(signalPin, LOW);
}

void loop() {
  if(digitalRead(btnPin) == LOW){
  digitalWrite(signalPin, HIGH);
  delay(5000);
  digitalWrite(signalPin, LOW);
  }
}

For simplicity, I'm showing a separate button component in the diagram, but I'm actually using a button that's wired into an LCD shield.

My expectation is that, when I press the button, the digital pin wired to the transistor's base will cause the transistor to close the circuit and turn the fan (and LED) on for five seconds.

The problem that I have is that the Arduino's digital pin doesn't seem to be able to saturate the base, so not enough current passes through the transistor to power the fan. It does turn the LED on and off as expected, but the fan needs much more current than the LED. If I take a wire directly from VIN or the 5V pin and touch it to base (through a resistor, of course), it does succeed in saturating the base, and the fan turns on. Measuring the current from VIN (or the 5V pin) to base, I get 4mA, so my assumption is that 4mA is sufficient to saturate the base. My understanding is that an Arduino digital pin should easily supply this. But in my case, the current from the relevant digital pin to the transistor's base never goes higher than 1.4mA. I've tried different pins on the board, but always get the same result.

So the question is, why does the circuit work as expected for the LED, but not for the fan? Any help/suggestions will be greatly appreciated!

To fully turn the transistor on you should give the base somewhere around 1/10 to 1/20 of the collector current. If you read the datasheet for the PN2222 (a highly recommended activity) you will see that Vce(sat) is specified with Ic/Ib = 10.

Now, the Microchip ATMega328 MCU chip in many (but not all) Arduinos is capable of sourcing 10mA or 15mA with minimal drop (assuming a 5V supply), again this information is available in the MCU datasheet (Figure 31-71 on page 355).

So it appears you are using an "Arduino" with some other MCU. In which case you can either use another transistor to boost the current or substitute a logic-level MOSFET.


Having problems with I2C - Slave is receiving "b ~ ,,," so I'm facing a pretty large problem. I'm experimenting with I2C and using one Arduino that acts as a countdown timer to send the current reading on the timer to another Arduino. I'm pretty new to electronics in general so bear with me.

The way the countdown timer works is it stores the time as a String, and uses substring and toInt() to adjust the timer.

I know that with I2C you can only send some data, Strings not included, so I tried converting the String to an array of characters using toCharArray(). My conversion seems to be working well, as I have tested it with the Serial.println() and it displays the time correctly.

Therefore, I am convinced the problem lies with the Slave code. I'm not sure how to set up the Slave Arduino to receive the actual time. Below, I've pasted links to the code of both the Master and the Slave respectively.

Master: https://pastebin.com/AFjTDZB7

Slave: https://pastebin.com/viNGWn9c

How should I change my slave code so everything works?

Also, when I changed the datatype of "time" in the Slave code from char* to int, all I got in the Serial Monitor was 48. Weird.

Would really appreciate any help and guidance cause I'm pretty stuck. All the tutorials I find online are pretty complicated.

Thanks!

Master Code:

#include < Wire.h >
String time = "10:11";
boolean doubleDigits = false;

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

void loop() {
  Serial.println(time);
  sendTime(time);
  int First2 = time.substring(0, 2).toInt();
  if (First2 > 9) {
    doubleDigits = true;
  }

  int Last2 = time.substring(3).toInt();
  if ((time.substring(3) == "00") && (time != "00:00")) {
    First2 = First2 - 1;
    Last2 = 59;
    if (doubleDigits == false) {
      time = "0" + String(First2) + ":" + String(Last2);
    } else {
      time = String(First2) + ":" + String(Last2);
    }
  } else if (time != "00:00") {
    Last2 = Last2 - 1;
    if (Last2 < 10) {
      if (doubleDigits == false) {
        time = "0" + String(First2) + ":0" + String(Last2);
      } else {
        time = String(First2) + ":0" + String(Last2);
      }
    } else {
      if (doubleDigits == false) {
        time = "0" + String(First2) + ":" + String(Last2);
      } else {
        time = String(First2) + ":" + String(Last2);
      }
    }
  }
  if (time.substring(1, 2) == ":") {
    time = "0" + time;
  }
  delay(1000);
}

void sendTime(String time) {
  Wire.beginTransmission(9); //transmit to device 9
  char buffer[32];
  time.toCharArray(buffer, 32);
  Wire.write(buffer);
  Serial.println(buffer);
  Wire.endTransmission(); //stops transmitting
}

//master

Slave Code:

#include <Wire.h>
char* time;

void setup() {
  Wire.begin(9); //start as slave on address 9
  Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
  Serial.begin(9600);
}

void receiveEvent(int bytes) {
  time = Wire.read(); //read one character from the I2C

}

void loop() {
  Serial.println(time);
  delay(1000);
}

//slave

Edit: added code

In the slave code.  receiveEvent takes a number of bytes as a parameter, presumably you are supposed to read this many bytes, can you call read with that number?  Even if you did you are reading to a char pointer, which will cause issues unless read is allocating the memory, which you should then be releasing.  Basically you have a couple of issues here and you need to look at them.

In the Master code. sendTime doesn't look right.  I would expect you to have to send a certain number of bytes using the Write function.  You are just sending 32 chars, the fact you are sending signed char's rather than unsigned char's shouldn't be an issue (but its technically incorrect).

I don't really understand what you are trying to achieve in the rest of loop, annotation would help :)

OK, If you take this as a new version for the slave you should be able to see it working.  It might not be 100%, but you should get something.  (I haven't even compiled this code, so you might have to sort out a few bugs)

#include <Wire.h>

#define MaxTimeBufferSize (33)
#define MaxReadSize  (MaxTimeBufferSize - 1)
char timeBuffer[MaxTimeBufferSize];

void setup()
{
  Serial.begin(9600);  // Init first so you can see any issues during setup.
  Wire.begin(9); //start as slave on address 9
  Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
}

// Assumes the bytes are actually printable ASCII characters.
void receiveEvent(int bytes)
{
  const int bytesToRead = (bytes < MaxReadSize) ? bytes : MaxReadSize;
  for (int index = 0; index < bytesToRead; ++index)
  {
     timeBuffer[index] = Wire.read(); //read one character from the I2C
  }
  timeBuffer[bytesToRead] = 0; // Null terminate the bytes (so they will print as a string)
}

void loop()
{
  if (timeBuffer[0])  // Only print the buffer if there is new data
  {
    Serial.println(timeBuffer); // The buffer is NULL terminated.
    timeBuffer[0] = 0;  // Stop the buffer  printing again.
  }
  delay(1000);
}


Power supply affecting sensor readings ESP8266 and JSN-SR04T-2.0 I have an ESP8266 Wemos D1R2 Board with a JSN-SR04T-2.0 ultrasonic range finder and everything works perfectly when I have the device connected to my computer USB or via a 12V battery into the onboard regulator via the external power jack. However when I use a 240V AC to 12V DC transformer to power the setup my readings become quite erratic. I have checked the voltage coming out of the power supply (12.48v) and the voltage going to the sensor (3.28V,  I have it coming off the 3.3V pin) and it is the same on each type of power supply so the onboard regulator is working. Can anyone advise what might cause this? The transformer provides 1A which is more than enough as I have measured the peak usage at <100ma

The JSN-SR04T-2.0 ultrasonic range finder is rated to 5Volts. giving it 3.3 volts may not be enough. from my limited knowledge it should work if you give it a separate power supply and not depend on the 3.3 volts of the ESP.


4 bit to Decimal Converter IC im using arduino and im out of pins.

I need something like a decoder but the problem is that the decoders only change one output pin I.E. for 0011 the output will be 0001000000000000 what i need is to have the first outputs on I.E for 1000 the output will be 111111111000000000 i basically need to light up to 16leds and im out of pins so i was wondering is there is any IC that does this for me if i have 1111 it will output 16 ones.

You can use one (or more, daisy-chained) shift register for that.

It will normally take you 3 pins and provide 8 outputs, or 8n where n is the number of chained shift registers still using only 3 Arduino pins.

One example of a shift register that fits your situation is the 74HC595.

On Arduino, you can use shiftOut function to help handle those ICs.


Strange values on Serial Monitor even with matched baud rate I am using the Adafruit Flora, connected with a Max 4466 microphone sensor. When I read values from the pin numbered 12 (which is marked as a11 for analog input on the schematic of the flora) I get random characters in the serial monitor as shown in the attached image, with my code. Trying to read other pins that are connected to nothing doesn't read any information. My baud rate in the serial monitor and the code are the same as you can see in the image.

Looking at the max 4466 explanation on the Adafruit website it says you don't need a capacitor or anything and can just directly plug the out pin on the MAX 4466 to the analog pin on an Arduino. I'm not sure if a different protocol has to be followed for a Flora instead of an Arduino. It also says to convert the information to an actual signal I need to use the FFT libraries, but I don't think this input being read is even correct.

If the FFT library is the problem here, I would need help on how to use it because there is no clear value being read in the example code. I had to set up a delay in the code otherwise the IDE would crash from all the info.Additionally, the VCC on the max is connected to 3.3V, the GND to GND, and the OUT to the #12 pin on the Flora.

You can't concatenate string and value inside Serial.println().

Print them using two different Serial.println().

int pin12;
int A12 = A12;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  pin12 = analogRead(A11);

  Serial.print("pin 12 is ");
  Serial.println(pin12);

  delay(5000);
}


Error 101 Server Did Not Report Size from OTA Upgrade framework via git hub I have tried this video:
ESP8266 Self Update OTA from GitHub
Instruction and made this GitHub repo:
And changed the main code to this type, but I get this error:
HTTP_UPDATE_FAILD Error (-101): Server Did Not Report Size

when the    FirmwareUpdate(); code is running.
So I don't know why GitHub don't answer to the esp8266, as said here:

The error has nothing to do with your sketch. Also, the error code is
not a HTTP 101 error. The problem is that your server does not send
the response header 'Content-Length'

I have some dupt about the bin URL file address which have many dot on the end of it (https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay.ino.esp8285.bin) on it, could it be the reason for none answering and giving the 101 code form GitHub server!
Any suggestion would be good help to fix this bug.
Update 1:

I have changed the bin file name to this kind :
 BlinkWithoutDelay.ino.esp8285.bin  ---->      BlinkWithoutDelay_ino_esp8285.bin

But I have again the same GitHub 101 error.

Update 2:
Based on the timemage answer, I have changed the address of bin and TXT file by finding the download link of those files form the GitHub. And it has been working by changing the blob part of address to raw, so the bin address changed form https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay_ino_esp8285.bin to https://github.com/soheilpaper/ota_github_blink/raw/main/BlinkWithoutDelay_ino_esp8285.bin And the https://github.com/soheilpaper/ota_github_blink/blob/main/version.txtto  https://raw.githubusercontent.com/soheilpaper/ota_github_blink/main/version.txt
And now that error has been fixed as you can see below:

Although I gave some dupt about upgrading the main code by getting this output via serial port:
Device already on latest firmware version

And I would check it after some resting!.
Thanks.

The ESP8266httpUpdate library wants to know in advance how large the file is before it starts downloading it.  It wants to know this so it can tell, before trying to download (and program), whether or not there's enough space for it. If the size of the file isn't provided by the server it will report the error that you are seeing.
The size of the file is provided by the web server by means of the Content-Length HTTP response header read by HTTPClient.  This header is received in advance of the file content.
Your main code appears to contain a correct link to raw .bin file,
#define URL_fw_Bin "https://raw.githubusercontent.com/programmer131/otaFiles/master/firmware.bin", and reports the following headers:
cache-control: max-age=300
content-security-policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
content-type: application/octet-stream
etag: "b2ecfb5dc91587c089acdaace446b0d7b00863c9f42dffb36c7983c103d3a98a"
strict-transport-security: max-age=31536000
x-content-type-options: nosniff
x-frame-options: deny
x-xss-protection: 1; mode=block
via: 1.1 varnish (Varnish/6.0), 1.1 varnish
x-github-request-id: 8728:2B67:9AFD3:AD0EC:6008FCFF
accept-ranges: bytes
date: Thu, 21 Jan 2021 04:03:32 GMT
x-served-by: cache-bos4651-BOS
x-cache: MISS, HIT
x-cache-hits: 0, 1
x-timer: S1611201812.154162,VS0,VE1
vary: Authorization,Accept-Encoding
access-control-allow-origin: *
x-fastly-request-id: bfc9702929b91be55d7aa040465a230436918e01
expires: Thu, 21 Jan 2021 04:08:32 GMT
source-age: 20
content-length: 270016

The content-length: 270016 at the bottom shows that this should work.  But your changed code that uses #define URL_fw_Bin "https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay_ino_esp8285.bin is to the HTML page for downloading the file, which does not report Content-length, for me anyway, but then it's the wrong URL anyway.
Regarding the "101 error", it's -101 (negative) defined here, and like they said, it is not an HTTP status code,  it is just a value used by the ESP8266httpUpdate library.


activate a relay with two esp8266 -12e pins I have an esp8266-12e that I want to activate the reset side of a latching relay.  The problem is that the 12e only puts out 12mA/pin and the relay needs more than that.  I am using a transistor on the set side from a rf antenna signal.  I only have one 3.3v power source.  Is there a way to have two pins go HIGH at the exact same time and be connected to the reset side of the relay so there is enough current?  Would this work, would it hurt anything, and how would I write the code for it and how would I wire it up?

I have tried the code where one pin is written HIGH right after the other like this

digitalWrite (5,HIGH);
digital Write (6,HIGH);

but I think pin 5 goes of before pin 6.
Any way to get them to go off at the same time?

Thanks for the help

That is not a good idea.

Isolating the relay from the IO pin is not just about the current limit of an IO pin, it's also about preventing back-EMF spikes from the relay coil(s) from damaging the delicate internals of the chip.

Instead you must at least use a transistor and a back-EMF protecting diode.

However - if you did want to theoretically have two pins safely controlled to provide double the current (though I stress again, do not do this for driving a relay), it is possible.

But it's not straight forward.

It's not possible on the ESP8266 to use port manipulation to make two pins change state at the same time. However it is possible to go via a third state that makes it safe.

Note: this will only be "safe" for IO pins that do not do strange things at bootup, and many of the pins on the ESP8266 do strange things.

IO pins actually have three states, not two:

High
Low
High Impedance

The latter is the state the pin is in when in INPUT mode. And we can use that to our advantage.

When in High Impedance mode it's like the pin is disconnected.  So we could:

Make sure both pins are in INPUT mode
Switch one pin to OUTPUT and set it to the desired state
Switch it back to INPUT mode (keeping the desired state latched)
Switch the other pin to OUTPUT and set it to the desired state
Set the first pin back to OUTPUT mode again.

This can be slightly compressed as we don't really need to set both pins to INPUT at the start, only one.  So here's some code that might do it:

void digitalDoubleWrite(int pina, int pinb, bool level) {
    pinMode(pina, INPUT);
    pinMode(pinb, OUTPUT);
    digitalWrite(pinb, level);
    pinMode(pinb, INPUT);
    pinMode(pina, OUTPUT);
    digitalWrite(pina, level);
    pinMode(pinb, OUTPUT);
}

You might ask why we'd want to switch to OUTPUT just to latch a level into the pin. Well, that's because of a quirk of the Arduino API. A historical artefact that is lingering in there to this day:

digitalWrite() on a pin set to INPUT mode was used to turn the internal pullup resistor on and off

It's actually how the AVR's IO ports control the pullup resistors internally, and that has most often been copied in software for other chips to maintain backward compatibility with old code. So as a result we have to switch to OUTPUT mode so that the API code knows that we mean to set the output latch state and not the pullup resistor state.


Overview of compiled code size When I compile my code, the Arduino IDE returns the binary sketch size in byte.

Is there a good way to find out (approximately) what function or what part of my code takes up how much memory in flash, so that I get a feeling what feature takes most of precious flash memory or where I may be wasting flash and should start optimizing?

One approach is to look at the assembly listing of the program.

After compiling the program (via the Verify or Download button) locate the directory where the .cpp, .hex, and .elf files for the program have been stored.  (If you have trouble finding them, briefly turn on verbose compile options in the arduino IDE and look at the directory names in the output.)
In that directory, run avr-objdump -S fn.cpp.elf > listing.txt where fn.cpp.elf is the name of your sketch with .ino taken off and .cpp.elf added on at the end.  For example, with sketch serialecho.ino:

avr-objdump -S serialecho.cpp.elf > listing.txt
View the listing.txt file, and subtract each function's starting address from its ending address, using hex arithmetic.  For example, with setup code

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

in the listing we will see

00000144 <setup>:
...(6 lines snipped)...
 144:   26 e0           ldi     r18, 0x06       ; 6
 146:   40 e8           ldi     r20, 0x80       ; 128
 148:   55 e2           ldi     r21, 0x25       ; 37
 14a:   60 e0           ldi     r22, 0x00       ; 0
 14c:   70 e0           ldi     r23, 0x00       ; 0
 14e:   80 e1           ldi     r24, 0x10       ; 16
 150:   92 e0           ldi     r25, 0x02       ; 2
 152:   db c1           rjmp    .+950           ; 0x50a <_ZN14HardwareSerial5beginEmh>

00000154 <loop>:

The calculation 0x154–0x144 = 0x10 shows this portion of setup is 16 bytes long.

These examples were generated on a linux system.  I think the approach is the same on a MSWindows system except you may need to say avr-objdump.exe instead of avr-objdump, and may need to specify its path.  See, eg, the Assemler results, where? thread at forum.arduino.cc.


Using Air Quality Sensors like MQ135 to sense dust particles Using MQ135 (or similar) to sense dust particles in PM

I was building a Air-purifier system. So, I need to monitor dust particles present in the air. Is it possible to use a gas sensor like the MQ135 to sense dust particles? Since, It can sense very small gas particles. Would it be possible to sense dust particles with it(MQ135 {Cheaper to buy}) or I need to buy a special optical dust sensor {Costly!}

The MQ sensors can not be used to sense dust particles. They are Electrochemical gas sensors which are sensitive for certain gasses. They are not sensitive for dust particles. Dust is not a gas, but tiny solid particles.


How to convert four uint16_t to double float IEEE754? I am working in a Modbus project where I have to read modbus Holding and Input registers using ESP8266, I am using ModbusMaster232 library. I returns a response buffer array of uint16_t. I need to convert the uint16_t to double precision float. A quick test in ESP8266 shows double datatype in ESP8266 stores 8 bytes.Does anybody know how to convert four uint16_t to double in Arduino. If so please share your knowledge.

Here's a code fragment for converting a uint16_t. Expand this to work with your array of ints from the library.
Remember that on Arduino, - Uno and Mega, at least - doubles are implemented as floats. You won't get the precision you might be expecting.

double xAsDouble;    // ** only float precision despite 'double' declaration
uint16_t xAsInt;

xDouble = xInt;      // the compiler knows how to make this conversion.

Update: After re-reading your question, I realize you're using an ESP8266. My comments about Uno's float precision may not apply.

Update 2: After some discussion, I've learned that the Modbus return is not 4 integers, but a double being passed as 4 words, which need to be reassembled to recreate the original double. The solution will depend on the order in which the words comprising the original double are sent.

Update 3: I suggested the OP try using this general scheme:

// A union lets you look at memory as either (in this case) 4 ints or 1 double
union {
   uint16_t data_out[4];
   double x;
} buffer;

// Assign the data from modbus using the 'int' way of viewing menmory.
// Note I might have the ordering wrong but this is the idea:
buffer.data_out[i] = data_in[i];

Then reading 'buffer.x' would get the 4 words of memory as a double.

... After trying both orderings, the OP reports he is obtaining the expected result,


Arduino powering from 9V battery Yesterday afternoon I have left my Arduino running on a fresh Alkaline 9V battery (+ connected to Vin, - connected to GND). Today morning (16 hours later) the LCD display was no longer visible, and when I measured the volatage, I saw the battery was depleted to my surprise - its idle voltage was only 7 V.

My device is Arduino Uno with LCD 2x16 with LCD backlight and 2 DS18B20 sensors. Is it normal for such device to deplete 9V battery this quick?

I have read an answer to What are (or how do I use) the power saving options of the Arduino to extend battery life? question and I think what I see might be related to this, however I am not sure. If it is, is there some common schematics how to connect Arduino to be powered by a battery efficiently?

Power consumption

The Arduino boards use a fair bit of power compared to other embedded systems with similar functionality.

There are three main factors:

The NCP1117 (datasheet) 5V linear regulator in the Arduino UNO
R3 (schematic) has a quiescent current of around 6mA.
The ATMega328P (datasheet) draws around 5mA @ 8MHz and 5V, and probably more than double that at 16MHz.
user2973: The ATMega16U2 used for USB communications also draws approximately 13mA.

LEDs and other peripherals also draw some current. In your circuit, the LCD backlight is probably drawing 4mA as well.

When dropping 9V to 5V via a linear regulator, almost half of the power is lost by the regulator due to its 4V drop. Duncan comments that this nearly doubles the quiescent power draw from 9V as well as the power needed for every mA of 5V, since 4/9ths of the power gets wasted as heat by the voltage regulator. An efficient switching regulator would put out 5V with little wasted energy, effectively reducing the current draw seen by the battery by 4/9ths.

A duracell 9V battery (datasheet) drops from 9V to 7V in around 7.5 hours with a 50mA current draw. Therefore, a rough guess is that your circuit draws around 25mA, which sounds about right based on the description of your circuit.

Note, alkaline battery life is non-linear with respect to current. For very small currents (<1mA) the life of an Alkaline approaches that of a lithium battery.

Getting current down

Here are some tips to get the current consumption down:

Regulator: Replace the regulator with one with a low quiescent current, or better yet, a switching regulator (also with low quiescent current). A switching regulator uses 'pulses' of current and some external inductor and capacitors to give a reasonable steady voltage output. It doesn't waste energy like with the voltage drop of linear regulator and efficiency in the high 90% are possible.

There are buck (step down) converters that take the battery as input, then connect directly to 5V and GND, bypassing VIN and the regulator. This one from Pololu both steps up and down, and has 0.1mA quiescent current.
Alternatively, you could use some 1.5V alkaline batteries, and a boost (step up) converter to get the voltage up to 5V (e.g. this product from Sparkfun). It seems boost converters are more commonly stocked.
Finally, you could buy a rechargeable lithium battery with charging shield. This advantage of this is not having to buy new batteries, and for a tiny bit bigger than a 9V battery the lithium one has much greater capacity. A really cool product is the seeeduino stalker waterproof kit that includes a charging circuit, battery, solar panel and other goodies.

ATMega328P: Rather than using delay for timing and spinning in loop endlessly waiting for something to happen, re-write your code so that it goes to sleep in between sensor reads, etc. There are a few low power libraries out there that use the watchdog timer for periodic wakeup from sleep which are handy. You can get the current consumption of the ATMega328P below 0.1mA during sleep.
LCD: Turn off the backlight, or even the entire LCD. Add a button to the design that the user can push to activate the LCD and have it turn off after a set amount of inactivity.
Peripherals: Most peripheral chips also have a sleep mode that drastically reduces their power consumption. Remove power LEDs and other indicators that are not necessary.
ATMegu16U2: user2973 comments It seems this chip is quite power hungry (user2973). It could be removed to save power and just use the UART instead, but that seems like overkill. There are Arduino Pro boards that are just the bare bones Arduino without the USB interface that could be used instead of the UNO.
Batteries: Other alkaline cells have much greater capacity. For example, a 1.5V AA has over 2000mAh for low currents. Using AA cells plus a boost converter can increase the time before battery replacement. Use D cells (16000mAh) and it will run for quite a while. :D

Summary

With appropriate power supply and coding you can get a reasonable amount of life out of a battery. Using the above principles, I have made an Arduino derivative board that measures a few sensors and stores the readings to an SD card every half a second. It can last for about 4 months on 2 AA batteries, so it is definetly possible to have low power and remain in the Arduino ecosystem.

The chip I used for the low power in my board is the LTC3525-3.3V. It takes an input voltage as low as 0.8V and boosts up to 3.3V and a 5V version is also available. I designed a PCB for this chip as there was no ready-made breakout, and in the datasheet there are reference designs. The main critera for choosing this chip was it still had high efficiency at very low currents. Some other converters need a small minimum current draw.

The biggest consumer of power on the board ended up being the micro SD card. It can vary between 0.1mA and 1.5mA of idle current depending on the manufacturer. I have found Verbatim and Lexar cards to consume the least amount of power. I will this EE.SE question up to date with the results of my micro SD card power consumption tests.


Why serial communication does not work on atmega168/328p? I expect from the following program serial.c to light the led on if I send key 1 from terminal, and light the led off when I send key 0 from terminal:

#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data;
void main(void) {
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE;
  UBRR0L = UBRRL_VALUE;
  UCSR0B |= (1<<RXEN0);
  UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
  DDRB |= (1<<PB1);
  while(1) {
    while(!(UCSR0A&(1<<RXC0)));
    data = UDR0;
    if (data=='0') PORTB &= ~(1<<PB1);
    if (data=='1') PORTB |= (1<<PB1);
  }
}

I use the following commands to compile and burn all the programs:

avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

The output of avrdude is the following:

$ avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x1e950f
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "serial.hex"
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: writing flash (12 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 12 bytes of flash written
avrdude: verifying flash memory against serial.hex:
avrdude: load data flash data from input file serial.hex:
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: input file serial.hex contains 12 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 12 bytes of flash verified

avrdude: safemode: Fuses OK (E:07, H:DE, L:FF)

avrdude done.  Thank you.

For serial connection I tried PL2302 and FT232RL usb-com adapters - the effect is always the same.

Terminal settings on the computer are correct (9600,8N1).

avr-gcc version 4.8.1
avrdude version 6.1

Why the very first program in this question does not work as needed and what should be changed in it to achieve the desired behavior?

The problem you have is that your baud rate is not being set right.

You only have part of the settings you need.  There is a third macro in the setbaud.h file that you need to take account of:  USE_U2X.

That defines whether or not you need to set or clear the U2X0 bit of UCSRA0.  If that is set wrong then your baud rate will be either twice or half what you want it to be - in this case it's coming out as twice.

Modify your code to assign the baud rate like this:

#include <util/setbaud.h>
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
#if USE_U2X
UCSR0A |= (1<<U2X0);
#else
UCSR0A &= ~(1<<U2X0);
#endif
UCSR0B |= (1<<RXEN0);
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);

Then you should be able to receive characters.

In the actual header file in question there is a large number of comments and instructions, including this:

  Assuming that the requested BAUD is valid for the given F_CPU then
     the macro UBRR_VALUE is set to the required prescaler value.  Two
     additional macros are provided for the low and high bytes of the
     prescaler, respectively: UBRRL_VALUE is set to the lower byte of
     the UBRR_VALUE and UBRRH_VALUE is set to the upper byte.  An
     additional macro USE_2X will be defined.  Its value is set to 1 if
     the desired BAUD rate within the given tolerance could only be
     achieved by setting the U2X bit in the UART configuration.  It will
     be defined to 0 if U2X is not needed.

My resulting UART configuration, which may be being affected by the bootloader, is:

UBRR0H: 0x00
UBRR0L: 0x67
UCSR0A: 0x20
UCSR0B: 0x10
UCSR0C: 0x06

That equates to data register empty, RX enabled, 8-bit.

To my mind that is equal to the values being manually set in the code, so shouldn't be a problem.


Add a watermark to text message in an Arduino I'm trying to add a watermark to the text in the Arduino and there are several levels of watermarks (fragile, semi-fragile, robust). What is the difference between these levels in terms of algorithms used?

"Robustness", in the context of digital watermarking, specifies the ability to detect the watermark after some signal processing modification (for images, this might be translation, rotation, scaling, compression, etc.) Some digital watermarking techniques are robust against some operations but not against others. The classifications are:

Robust: The watermark should be able to survive against any and all
modification. This is often used in copyright protection, for
example.
Fragile: This kind of watermark is designed to be destroyed by any
modification to the original. This allows any manipulation, even
slight changes, to be detected. Fragile watermarks are generally used
to enable authentication and integrity verification.
Semi-fragile: The watermark should be "robust" against certain,
defined, modifications, but "fragile" against others. In other words,
the watermark should survive intact under the operations you want to
allow, but be destroyed by anything else. Again, these are used to
enable authentication.

For more information, you might find the 2005 paper A Review Study on Digital Watermarking by L. Jian and H. Xiangjian (in the journal Information and Communication Technologies) useful.


How can write a single data into spiffs? typedef struct book {
char title[20];
 char author[20];
 int pages[10];

} Book;

Book b1 = {"The Zahir","Paulo Coelho",336,0};

while writing this structure into SPIFFS of ESP8266, I am using function

filename.write( (const uint8_t*)&b1, sizeof(b1));

but how can write a single data like name of book into structure of spiffs?

For this kind of situation it's best to treat your data as records in a database. To change one part of a record you read the entire record, change the value, then write that record back.

int record = 4; // which record you want to change

struct book b; // Temporary storage for editing the data

// Go to the record and read it in
filename.seek(record * sizeof(struct book));
filename.read( (const uint8_t*)&b, sizeof(struct book));

// Change the data
strcpy(b.title, "Winnie The Pooh");

// Go to the record again and write it out
filename.seek(record * sizeof(struct book));
filename.write( (const uint8_t*)&b, sizeof(struct book));


PMS5003 Serial Output Data to SD Issues I'm trying to save the output of an air quality sensor to a SD card, but I'm having a few issues.

The sensor I'm using is a Plantower PMS5003 which puts out its data via serial. I've heavily tweaked the example sketch from Adafruit (here) as I'd like to use the Low Power library to sleep the unit, take a sample and note the time, write it to SD, then return to sleep.

I am getting the timestamp written no issue, but the data is coming out repeated as below:

22:13:10 - 34,55,61
22:13:18 - 34,55,61
22:13:27 - 34,55,61
22:13:36 - 34,55,61
22:13:44 - 34,55,61
22:13:53 - 34,55,61
22:14:1 - 34,55,61
22:14:10 - 34,55,61
22:14:18 - 34,55,61
22:14:27 - 34,55,61
22:14:35 - 34,55,61
22:14:44 - 34,55,61

The 8s timer appears to be working fine, but the repetition of data has me confused. I've tried adding delays and the like in case it was a lack of data but when I run that example sketch it comes screaming in over serial.

I also ditched using the software serial as I couldn't get it to stop messing with the low power library, it wouldn't ever sleep.

That and any general advice on the sketch is appreciated, it seems like its not the best way to accomplish this.

#include "LowPower.h"
#include <SdFat.h>
#include "RTClib.h"
#include <Wire.h>

SdFat SD;
RTC_DS3231 rtc;

File test;
String tString = "";
String sString = "";

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

  pinMode(10, OUTPUT);

  if (!rtc.begin()) while (1);

  if (!SD.begin(10)) while (1);
}

struct pms5003data {
  uint16_t framelen;
  uint16_t pm10_standard, pm25_standard, pm100_standard;
  uint16_t pm10_env, pm25_env, pm100_env;
  uint16_t particles_03um, particles_05um, particles_10um, particles_25um, particles_50um, particles_100um;
  uint16_t unused;
  uint16_t checksum;
};

struct pms5003data data;

void loop() {
  //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART0_OFF, TWI_OFF);
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

  DateTime now = rtc.now();
  test = SD.open("test.txt", FILE_WRITE);

  tString = String(now.hour()) + ":" + String(now.minute()) + ":" + String(now.second()) + " - ";

  readPMSdata(&Serial);
  sString = String(data.pm10_standard) + "," + String(data.pm25_standard) + "," + String(data.pm100_standard);

if (test) {
  test.print(tString);
  test.println(sString);
  test.close();

  delay(250);
}
}

boolean readPMSdata(Stream *s) {
  if (! s->available()) {
    return false;
  }

  // Read a byte at a time until we get to the special '0x42' start-byte
  if (s->peek() != 0x42) {
    s->read();
    return false;
  }

  // Now read all 32 bytes
  if (s->available() < 32) {
    return false;
  }

  uint8_t buffer[32];
  uint16_t sum = 0;
  s->readBytes(buffer, 32);

  // get checksum ready
  for (uint8_t i = 0; i < 30; i++) {
    sum += buffer[i];
  }

  //debugging
  for (uint8_t i = 2; i < 32; i++) {
    Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
  }
  Serial.println();

  // The data comes in endian'd, this solves it so it works on all platforms
  uint16_t buffer_u16[15];
  for (uint8_t i = 0; i < 15; i++) {
    buffer_u16[i] = buffer[2 + i * 2 + 1];
    buffer_u16[i] += (buffer[2 + i * 2] << 8);
  }

  // put it into a nice struct :)
  memcpy((void *)&data, (void *)buffer_u16, 30);

  if (sum != data.checksum) {
    Serial.println("Checksum failure");
    return false;
  }
  // success!
  return true;
}

There is a mismatch in the code.
The Arduino loop function assumes that readPMSdata needs to be called just once for valid data but the function readPMSdata itself assumes that it will be called over and over again until a enough bytes are received and are valid.

The solution is to let the Arduino loop call readPMSdata over and over again, until it has valid data. It returns true when it has valid data, so that can be used in a if statement.
This might cause troubles with the rest of the code in the loop. The delay(250); may no longer be used and I don't know the best place to go into sleep mode. Therefor I removed the powerdown.

void loop() {
  if( readPMSdata(&Serial))        // call it many times to collect data
  {
    // there is valid data from the sensor
    DateTime now = rtc.now();
    test = SD.open("test.txt", FILE_WRITE);

    tString = String(now.hour()) + ":" + String(now.minute()) + ":" + String(now.second()) + " - ";

    sString = String(data.pm10_standard) + "," + String(data.pm25_standard) + "," + String(data.pm100_standard);

    if (test) {
      test.print(tString);
      test.println(sString);
      test.close();
  }
}


Gnd pins at the power pin strip VS Gnd pin at the IO pin strip I noticed there are two Gnd pins at the lower pin strip, and another on the upper strip.
Is there a difference in their purpose?

In short, all the UNO ground pins are the same.

They are just there to make your life easier. At the end of the day, GND is GND. There is no technichal difference. Just note that is is sometimes better if you share the 3 GND ports. Overloading a port might damage it. Check the datasheet for current limitations of the pins.

EDIT

The pins (literal pins of the IC) themselves are also different on the ATmega IC.


Where do I find the enclosures for an Arduino and a bunch of sensors? I recently started playing with Arduino in order to do several projects, including:

A system which will measure some characteristics of the indoor air and could alert me if something goes wrong (for instance if the percentage of CH4 goes beyond a threshold).
A system I can bring with me on a walk which will measure the pollution and other characteristics of the air outdoors.

While the quantity and the diversity of the sensors for such projects, as well as the ease of use is mind blowing, I'm blocked at one aspect: the casing. Both of the projects require to put the electronics within a plastic case with:

Enough space for not only Arduino, but also the sensors. Some, such as MQ2/MQ5, can be quite large.
Holes for air flow, which are large enough to let small particles, but small enough to keep insects and large dust out of the electronics.
A hole for an USB cable and possibly a hole for the LED.

Unfortunately, the popular sites selling Arduino-related stuff have practically nothing when it comes to the cases. In most cases, the choice is limited to (1) the enclosures for Arduino itself (or other boards), with no holes in them and (2) the multicolored modular systems which look like LEGO bricks.

Outside Arduino-related sites, the only idea I have is to buy somewhere an old smoke detector, throw away the electronics and put Arduino and the sensors inside. For now, most smoke detectors I've seen seem too small for the task, and have to be modified in order to accommodate the USB cable.

Am I missing something? How other people do when they need an enclosure which fits Arduino and sensors and doesn't look geeky?

I think your problem is that you are looking specifically for Arduino enclosures. Such a search tends to lead you to boxes for just an Arduino and nothing else - maybe with the headers poking out the top.

Instead, you should be looking more generically. There are thousands and thousands of "project enclosures" from many manufacturers (Hammond is a big name in these).

You take a generic project box of the right size and shape for what you want to create and in a material suitable for your needs, and cut / grind / drill / glue it to be what you want.

Most electronics suppliers will have an "Enclosures and Housings" section on their website. Have a browse through your favourite.

As far as air vents go, one good trick I have used is to simply drill holes (with a steady hand so you get them lined up nice and straight) and glue some fine mesh on the inside.  One good source of fine mesh is to go to your local smoking supplies reseller (tobacconist) and buy some "pipe meshes" (the flat ones, not bowl shaped ones) - also available from low-cost online resellers of any old junk (eBay, etc), which look like this:

(Also available in brass).  They typically come in different mesh sizes to suit your needs.


LED Strobe based on switch press through Arduino I have a problem I can't see to solve. I'm trying to program my Arduino, which I just got. I have read a lot of programming scenarios, but can't seem to find one that fits my problem.

I can get the LED to turn off and on like I want.

Assume a switch is pressed or even two wires to the LED are put together. Once the switch is pressed I'd like the LED to flash briefly, even though the LED has power to it. Is there a way to do this with Arduino code?

(1) Press switch
(2) Flash LED briefly
(3) Switch is still being pressed
(4) LED remains off until switch is pressed again
(5) loop through routine again.

This is a modified Example program that i have tested and seems to do what you expect. I have used a 2 position switch instead of a button. using a pointer "ledState" to indicate that the LED has flashed and have then combined 2 conditions with the "&&" in the IF statement.

/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int ledState = 0;
void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if ((buttonState == HIGH)&&(ledState == 0)) {
    // Flash LED:
    ledState = 1;
    digitalWrite(ledPin, HIGH);
    delay(500);
    digitalWrite(ledPin, LOW);
    delay(500);
  } else if ((buttonState == LOW) && (ledState == 1)){
    ledState = 0;
    delay(50);
    }
}


Dimming 6W (24V DC 0.25A) LEDs using Arduino I want to dim 24 LEDs which are powered by a transformer outputting 24V 6W at 0.25A

I am worried about temperatures, especially considering the circuit has to stay on for several hours keeping the LEDs off.

Would a TIP122 transistor be ok?

Any tips for keeping the transistor off until the dimming process starts?

I would suggest using the CAT4101 constant current sink PWM LED driver.  It can handle up to 1A at up to 25V and deals with the constant current regulation for you - just provide at least the 24V you need and enough current capacity and connect the correctly calculated current setting resistor and the CAT4101 will do the rest for you.  You can then control it through the PWM input pin direct from the Arduino.


function returning String-Array i'm still new to arduino and also to C++ and have a short question.
What i want to do is to write a function (in my case to parse the query-string of an URL) to get the parameter names and values (varying number of parameters).

My function looks like the following:

String function readParams()
{
   String params[x]; // x: number of params

   // fill params[0]... params[x] with parameter names

   return params;
}

void loop()
{
   // do some stuff

   String params[x] = readParams();

   for(int i=0; i < x; i++)
   {
      debug(params[i]);
   }
}

What is the correct return-type for the readParams() function in this case?
And how to access the params in the main (loop) -function?

I hope the code makes it clear what i want to do.

Thanks,
Marius

Some tips:

Don't use String.
Use char * and slice the string in-place.
Pass a pointer to an array of pointers and fill that with pointers to the portions of the string you have sliced.
Return the number of entries in the array you used.

I do something similar in my CLI library.  I use a custom "getWord" function, but similar can be done with strtok().

You can read more about working with C strings here.


A question about Continuous Rotation Servo and Arduino We have this project that uses a Continuous Rotation Servo and we have a slight problem controlling it. We're planning to attach a Rack Gear to the Servo to slide a stainless steel to the right, and vice versa.

The Question: Is it possible to stop the continuous rotation servo when the stainless steel hits a bump or it already made its proper position accurately?

This idea is like the Power Windows of cars.

You can track the servo rotation with an encoder and after reaching a specific position, you can send different instructions to execute other actions.

Other alternative is maybe you can place a limit switch at the position where you want it to stop.


Why is the nRF24L01 not working with Arduino Esplora? I am working on a remote control car from an Arduino Esplora board and the Mega 2650 Board. My problem lies with the Esplora board as the nRF does not transmit like it is supposed to or does not even transmit at all.

I am using the pingpair_test.ino from the RF24 library to make sure the transceiver is working, and when I try to transmit on the serial monitor, I get the following output:

Configuration = t

STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0

RX_ADDR_P0-1 = 0x0000000000 0x0000000000

RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00

TX_ADDR = 0x0000000000

RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00

EN_AA = 0x00

EN_RXADDR = 0x00

RF_CH = 0x00

RF_SETUP = 0x00

CONFIG = 0x00

DYNPD/FEATURE = 0x00 0x00

Data Rate = 1MBPS

Model = nRF24L01

CRC Length = Disabled

PA Power = PA_MIN

Now sending length 4...No responses received. Are interrupts connected?

I have no idea what any of this means besides the interrupts part.

Even using interrupts(); the Arduino Esplora still refuses to send data. I am sure my wiring is correct because the status light on the nRF is on and I triple checked all of the SPI pins.

On the Esplora:

CE = 0
CSN = 1

On the Mega:

CE = 51
CSN = 50

I have a fritzing sketch here for those who want to see my wiring.

Looking at your output either you have a wrong wiring or, more probably, you need a capacitor between the nRF24 positive and negative pins: anything between 10uF and 100uF will do.


Is it possible to start audio playback when headphones gets plugged in? I want to have 6 audio jacks IN waiting for connection to start some WAV/OGG playback as soon as a headphone plugs in. In fact, I'd like to have simultaneous playback in 6 lines.

I've seen in the market some stuff that you can add buttons to different actions (play, pause, stop, etc). So far I believe this might be possible and affordable with Adafruit's Audio FX (which are stand-alone, Arduino-programmable WAV/OGG decoder circuits).

But,

  Is it possible to start audio playback when headphones gets plugged
  in? HOW?

Is that an event? like pressing a button?

Does it need some "hacking" between GND lines maybe?

A lot of 3.5mm jacks come with built-in normally-closed contacts, and their state can be tested through the pins of the jack with a multimeter or sensed by your MCU like any other switch. There are usually 2 pins each for the ring (pins 2 and 4 below) and the tip (pins 3 and 5), each pair connected to the other and one pin for the sleeve. The insertion of the headphones' connector breaks the connection between each pair, so that only one pin of each pair is actually connected to the connector's tip and ring.

You can connect the tip (pin 3) of each jack to digital input pins and connect the other pin of the pair (pin 5) to Vcc; you only need to read the tip because if the tip contacts are closed, it means nothing is fully plugged in yet. When no connector is plugged in, input pin reads HIGH from the tip since it is connected to Vcc through pin 5. When the headphones are plugged in, it breaks the 3-5 connection, and the tip now floats. Its voltage is indeterminate; it will probably sit somewhere near the middle of the 0-5V range, but we can't be sure.
To remedy this, there are 2 possible approaches I can see:

You use an analog input pin, instead of a digital pin. This way, you can read the very voltage at the tip; if its ADC value is above 900 perhaps, you can conclude that its HIGH and therefore nothing is plugged in, whereas if its below 600, you can conclude that the tip is floating and a headphone is plugged in. However, this method will require an input pin per headphone. The Uno has 6 analog pins, so this will take up all of them. If you aren't already using any of them, this method may be good enough. You could also use an analog GPIO expander.
You can use a digital input pin for the tip (pin 3) but instead of pulling pin 5 to Vcc, you connect it to a digital output pin. You can connect the pin 5 of each headphone set to this common output pin. To test if a particular jack has headphones plugged into it, you read the associated input pin and check if this is the same as the current value of the common output pin (saved to some variable). If it is, you toggle the output pin and again check the input pin to see if it mirrors the new value of the output pin; just additional confirmation. If everything checks out, then nothing is connected to the jack yet. If either test fails, you can reasonably conclude that headphones are plugged in.

Now that you know headphones are plugged in, you can call the appropriate function to begin playback through the right jack. Of course, all this assumes you'll be working with the jacks directly and not through some module. If you use the Adafruit Soundboard, you can check out the L (Left Channel) pin, which corresponds to the tip. I don't know if it's actually connected to the jack so you'll have to experiment and find out.


Can the ESP-1 use SPI to communicate with sensors? I wonder if I can use SPI to communicate between ESP-1  ESP8266 module and SPI sensors and other slaves.

If so, do I need to install a library?

ESP-01 was designed as WiFi network adapter, not as a controller board. The are 4 pins on esp-01. RX (io 3), TX (io 1), io 0 and io 2.

SPI requires 3 pins: clock, MISO, MOSI plus one pin for every device connected to the bus. So you could in theory use one SPI device on this 4 pins. The esp8266 Arduino SPI library works only with hardware SPI on esp8266 pins io 12, 13, 14 so you would have to use some software SPI implementation for esp8266.

To connect sensors, actuators or display to the esp-01, I2C is a feasible option. It requires only two digital pins and the esp8266 Arduino Wire library can work on any pair of io pins.

To use esp8266 as MCU with Arduino, there are many development boards with all usable pins broken out (9 pins) and USB chip for simple connection to computer and flashing (Wemos, NodeMCU). Or you can use an esp8266 module with more or all pins of the esp8266 (esp-07, esp-12).


CC3000 - Send GET request to an app on heroku I'm struggling to get the CC3000 to connect to a heroku hosted app, and other examples posted online haven't turned on the light bulb quite yet for me.

The gist is that I collect some temperature and humidity readings, and then send those via a GET request using the CC3000. The heroku app then reads the parameters and displays them on a page.

The CC3000 hardware is A-OK, as I've tested it using the test sketches. The sketch I've put together (on github: https://github.com/jsimms/compost_monitor) works except for the last bit where it needs to connect to the server and send the HTTP request. Which makes me wonder if this is a heroku quirk, or if I'm just screwing something up right at the finish line.

First, I define everything

#define WEBSITE      "myapp.herokuapp.com"
String route = "/sensor";
uint32_t ip;
int port = 80;

Then during setup, I use getHostByName to assign the ip variable. I print it out, just to confirm it was able to snag an ip. I then close it to make sure I don't screw up anything during the loop.

  ip = 0;
  Serial.print(WEBSITE); Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }

  cc3000.printIPdotsRev(ip);
  Serial.println("");

  // Close the connection
  Serial.println(F("Closing connection..."));
  cc3000.disconnect();
  Serial.println(F("Connection closed."));

During the loop, I create a String with the request, and then call a function that actually does the request.

String request = "GET " + route + "?temp=" + temperature + "&hum=" + humidity + " HTTP/1.0\r\n";
send_request(request);

Finally, the send_request function is supposed to take care of connecting via TCP and sending it.

void send_request (String request)
{
  // Connect to server
  Serial.println("Connecting to server...");
  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, port);

  // Send the request
  if (www.connected()) {
      www.println(request);
      www.println(F("User-agent: CompostMonitor/1.0\r\n"));
      www.println(F("\r\n"));
      Serial.println("Connected & data sent successfully...");
    }
    else {
      Serial.println(F("Connection failed."));
    }

    while (www.connected()) {
      while (www.available()) {

      // Read answer
      char c = www.read();
      Serial.println(c);
      }
    }

  // Disconnect
  Serial.println("Closing connection...");
  Serial.println("");
  www.close();
}

However, I never get anything but connection failed.

Any insight and help would be wonderfully appreciated. :)

UPDATE: Ok. So, through the comments below, I was able to identify by telnet'ing the web app, that there was something wrong with the HTTP requests. I made a small tweak to the app, but the real issue was that I wasn't including Host: weathervane.herokuapp.com in the header. FML! I'm going to test out sending the request with the Arduino later tonight. Hopefully that puts an end to this HTTP 101 lesson I've been doing.

Have a look at this code:  https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/examples/SendTweet/SendTweet.ino

There is a delay after cc3000.connectTCP to wait for connection. Your code does not wait for the connection and thus gives 'connection failed' straight away.

Serial.print(F("OK\r\nConnecting to server..."));
t = millis();
do {
    client = cc3000.connectTCP(ip, 80);
} while((!client.connected()) &&
    ((millis() - t) < connectTimeout));

if(client.connected()) { // Success!

etc

Edit based on comment:

getHostByName returns positive value on success and negative on failure. Therefore the check should be

if (cc3000.getHostByName(WEBSITE, &ip) < 0)

Also try putting http:// in the website address


The servo sweep library code - "delay" versus "in steps of" This is a pretty basic question - essentially I want to know the difference between adjusting the basic sweep code (from the library) in terms of the "delay" instruction and the "pos += 1" (in steps of 1 degree) instruction.

For my project I want my servo to move 60 degrees at the same frequency as a heart beating relatively fast (lets say two beats a second). I.e., the servo moves from zero to 60 degrees twice in one second. Should I adjust the 'delay' or the 'position' instruction from the library? What's the difference? Does it matter which one I adjust as long as it does what I need it to?

Thanks for your time!

Changing the delay and leaving the increment to one generally gives a "smoother" movement. In fact, if you want for instance to move (roughly) five times faster than the example you can either move the delay to 3ms or increment the position by 5. This is what happens at the position request:

Time   0  3  6  9 12 15 18 21 24 27 30 33 ...
Delay  0  1  2  3  4  5  6  7  8  9 10 11 ...
Incr.  0  0  0  0  0  5  5  5  5  5 10 10 ...

Now, usually I try to use the delay approach as much as I can; the limitations on that approach are that it becomes more CPU consuming if you should also perform other actions between two movements (which is not your case, since you are using delays).

In order to perform four 60° movements in one second you should wait roughly 4ms between calls.

In any case, even if the single increment is the best solution, as long as you perform one movement every 10-20ms you won't be able to see any differences, so even increasing the position by 3 every 12ms or by 5 every 20ms is fine. If you start hearing a "pulsed" noise or see the motor going "jerkily" reduce the increments and the delay.

Note: You can also use multiple increments in order to have "fractional" delays. For instance, if you want to have one increment every 3.5ms, instead of using delayMicroseconds you can perform two increments every 7ms.


How to serially communicate arduino uno to PIC18f4550? I am new in PIC programming

my question is, how can i communicate arduino UNO with  PIC18f4550. i am using THIS programmer board for PIC controller and it has a builtin RS232 serial interface.

Can any body tell me how to communicate between them. I want to communicate in such a way that only Rx & Tx pins and the power pins of arduino will be used.

yeah you can quite easily do the Serial communication between Arduino and PIC Microcontroller. You need to connect the below pins:

Arduino TX will be connected to PIC RX.
Arduino RX will be connected to PIC TX.
GND of Arduino must be connected to GND of PIC.

Next thing you need to remember is to have same baud rate for both Arduino and PIC. Now you should check these two posts:

Arduino Serial Communication.
PIC Serial Communication

First one is explaining the Serial Communication of Arduino while the second one is Serial Communication of PIC Microcontroller. You should also read What is Serial Port? to get more idea about Serial communication.

I hope they will help you out. If you still got into some issues then let me know.


Invalid conversion from 'const char' to 'uint8_t*' I am just a newbie, don't know how to solve this issue

void loop()
{
  UdpSend("Test", "192.168.0.240", 4210);
}

void UdpSend(const char* message, uint8_t * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

Arduino IDE can't compile.

The error message:  invalid conversion from 'const char' to 'uint8_t* {aka unsigned char*}' [-fpermissive]*

Trying to change with this code:

void UdpSend(uint8_t * message, uint8_t * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

Also doesn't work, the error message: invalid conversion from 'const char' to 'uint8_t* {aka unsigned char*}' [-fpermissive]*

Please help...

In ESP32 Arduino package the WiFiUdp.h doesn't pull in all Print class write functions. As consequence the WiFiUdp class doesn't know write(const char *str).

Use Udp.print(message); if message is a zero-terminated char array

or Udp.write(message, size); if message is a byte array


Arduino simple resistors in series Silly question but how would a circuit be set up with Arduino where two different resistors are in series but one has an unknown value (i.e. is just a piece of metal for example) and so how would we be able to find the current through each, collage through each and thus find the value of the resistance of the unknown wire.

Just a math exercise really.

Say you had a 5V source, two Resistors R1 and R2, and an Arduino.
5V - R1 - R2 - Gnd, with R1/R2 junction feeding the Arduino.
R1 is unknown.

Vout is what the Arduino sees. Vout = 5VxR2/(R1+R2)
Vout (R1+R2) = 5VxR2
R1+R2 = 5VxR2/Vout
R1 = 5VxR2/Vout - R2

Vout = ~ 0.00488mV x Analog In reading. (5V/1024)
If you select R2 of say 5K ohm, and you determine Vout to be 3V (analogRead returns 615), then you can calculate R1:
(5V x 5000)/3V- 5000 = 3333 ohm.

Checking with Vout = 5VxR2/(R1+R2), 5V x 5000/(3333 + 5000) = 3.000V


Does ADC conversion to a voltage rely on the actual value of the +5 V pin? Questions:

Does the conversion of the ADC count to voltage depend on the actual voltage of the +5 V pin?
If yes, what is the accepted method of getting that voltage from the board?

Background/Detail:

I have a circuit in which I have an Arduino Nano (clone) running from a USB connector (from a hub). The job of the Arduino is to measure the voltage on a battery which will drive a second circuit switched on/off by the Nano. For reference it is a battery tester.

There is a Nokia 5110 screen which displays the voltage from the very simple sketch below.

void setup() {
  Serial.begin(9600);
  display.begin();
  // Init done

  // You can change the contrast around to adapt the display
  // for the best viewing!
  display.setContrast(50);

  // Text display tests
  display.setTextSize(1);
  display.setTextColor(BLACK);
}

void loop() {
  display.clearDisplay();   // Clears the screen and buffer
  display.setCursor(0,0);
  display.print("Vin=");
  int rawVIN = analogRead(VIN);
  float floatVin = (rawVIN*4.75)/1023.0;
  display.println(floatVin);
  Serial.println(rawVIN);
  display.display();
  delay(1000);
}

I measured the voltage of the battery using a DVM and it is 4.13 V, yet
the Nano reports 4.35 V.
I have a common ground between the battery and Arduino.
Because the connection to test the voltage can float, I have a pulldown resistor to stop wild fluctuations (>10 kΩ)

After some investigation I found that the +5 V was actually outputting 4.75 V and changed my sketch from

float v = (rawVIN*5.0)/1024.0;

to

float v = (rawVIN*4.75)/1024.0;

and the voltage reading on the Arduino was now correct. I did this not because I understand what I did, I did it because I had a hunch it might change the value to the correct one.

The ADC inside the Arduino does not measure voltage, but rather a
voltage ratio. Namely the ratio from the voltage at the analog input
to the voltage at the Vref pin.

In the default configuration, the Vref pin is internally tied to the
+5 V line. You can select to use instead an internal reference as
Vref:

analogReference(INTERNAL);

This reference  is about 1.1 V, and is is quite immune to
fluctuations on the +5 V. The problem is that you cannot measure
voltages higher than the reference.

For your battery tester, if you want some sort of “absolute”
measurement, you could use the internal reference and a voltage divider
to ensure the measured voltage is below 1.1 V.

Edit: Another option which does not require a voltage divider is to
use Vcc as a reference to measure both the analog input and the
internal 1.1 V “bandgap“ reference. Measuring the 1.1 V
against Vcc is an indirect way to measure Vcc. This is not supported by
the Arduino core library, but you can do it by programming directly the
control registers of the ADC:

// Return the supply voltage in volts.
float read_vcc()
{
    const float V_BAND_GAP = 1.1;     // typical
    ADMUX  = _BV(REFS0)    // ref = Vcc
           | 14;           // channel 14 is the bandgap reference
    ADCSRA |= _BV(ADSC);   // start conversion
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait until complete
    return V_BAND_GAP * 1024 / ADC;
}

Beware that the very first reading after boot may be bogus.


Flashing ESP8266 ESP-12E/12F I'm pretty new to Arduino programming and i'm trying to connect this ESP8266 module to my FTDI programmer but constantly getting this error on my ARDUINO IDE:  esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header.
My guess is that its not in flashing mode and that i have to connect GPIO0 to ground or sompthing else.

On my version of this "Adatper" adapter the io pins were not connected. I patched io 0 to the esp-01 like header, to be able to put the ESP in bootloader mode. On the picture you see a paperclip jumper connecting io 0 to ground for flashing mode.

Back then I could leave the jumper connected, because the esp8266 run the sketch after upload. In new versions of esp8266 arduino boards package the esptool hard resets the esp8266 so it returns into flashing mode. This can be changed in platform.txt.

I recommend you to buy an esp8266 dev board with USB (Wemos, NodeMcu and similar)


How to reset ATmega328P fuses using USBasp programmer? I think I bricked two ATmega328Ps when I was trying to burn new bootloaders using Arduino Pro Mini, the USBasp programmer and the Extreme Burner AVR software. I had two ATMega328p with bad booloaders and I intended burn the correct bootloader to the chips.

First I connected the USBasp programmer to my Arduino Pro Mini equipped with an ATmega328P. I verified that communication was good as I could read and write to EEPROM. All was excellent.

I was using the following fuses:

LOW Fuse Byte=0x62
High Fuse Byte=0xD9
Extended=0xFF
Lock = 0xFF
Calibration = 0xFFFF FF8A
Then the following happened:

I killed the 1st chip when I only pressed button ERASE CHIP on the programmer.

I killed the 2nd chip when I wrote the following fuses to it:

LOW Fuse Byte=0xFF
High Fuse Byte=0xDA
Extended=0xFD
Lock Fuse = 0xCF
In both cases I had the following error message:

Cannot Communication with chip
Power On failed
avrdude output similar messages:

RC=-1. No answer...
(avrdude -c usbasp -p m328p -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m )
How can I solve this problem?

How can I reset all the fuses to factory default to make the chips respond again?

Its possible you may have disabled the SPIEN or the RSTDISBL fuses. The only way to check and fix is to use a High Voltage Programmer like the STK500, STK600 or AVR Dragon and see. I have the AVR Dragon and it saved me a few times.

Also, do a search for AVR Fuse Doctor. Its a homemade fuse repair device. Pretty cool. But save yourself some time and invest in a programmer/debugger that has HVPP (high voltage parallel programming) and HVSP (high voltage serial programming). You won't regret it.


data classification with arduino I want to classify my data from 3 sensors with arduino so that every time i enter the specific date or hour, or also it can be a period of time like 10 days ago, it shows me the exact data. In other word i want to classify my data so that whenever i want every detail of data, i would be able to get it by entering the information of year,date,time. I also didn't want my data to be in separate files and time stamps. I want to be able to do that within one file and search inside that file...

#include "RTClib.h"
#include <SD.h>
#include <SPI.h>

RTC_DS1307 rtc;
const int chipSelect = 10;

File dataFile;

String print_time(DateTime timestamp) {
  char message[120];

  int Year = timestamp.year();
  int Month = timestamp.month();
  int Day = timestamp.day();
  int Hour = timestamp.hour();
int Minute = timestamp.minute();
      int Second= timestamp.second();

      sprintf(message, "%d-%d-%d %02d:%02d:%02d", Month,Day,Year,Hour,Minute,Second);

      return message;
    }

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

      pinMode(chipSelect, OUTPUT);
      if (!SD.begin(chipSelect)){
        Serial.println("Error: SD card would not initiate.");
      }

      rtc.begin();
      if (!rtc.isrunning()){
        Serial.println("Clock is not running");
      }

      dataFile = SD.open("log0.csv", FILE_WRITE);
      if (!dataFile){
        Serial.println("Could not open file.");
      }

    }

    void loop(){
      Datetime now = rtc.now();
      dataFile.println(print_time(now));

      delay(3000);
    }

If you plan to continuously take data at a fixed rate, I suggest you
don't timestamp the individual records. Instead, store the initial
timestamp and the data sampling period in a binary header, followed by
fixed-size binary records. Then, when you want to retrieve the record
for time t, you can fseek() right to

uint32_t offset = header_size
                + record_size * (t - initial_time) / sampling_period;

If there is a slight chance that you may fail to record some data
points, you may want to have a boolean in each record that tells whether
the data is valid. You can then fill the missing data with invalid
records.

If your Arduino is likely to be turned on and off unpredictably, then
timestamping every record may be a better option, but finding a specific
record will likely be very slow.


No Battery Microcontroller Operation - (Motion, heat, induction etc) I am using an ATtiny85 to sleep for a long period of time, collect some data, send it over radio, and go back to sleep, after disabling everything possible. The ATtiny is currently powered by a coin cell. I can get quite some time off that coin cell, but it's simply not enough, and the coin cell cannot be changed once the board is deployed. Peak current draw is around 10-15 mA.

My aim here is to find an alternative power source for my board. Some good news is that the boards are never more than one or two feet from a receiver, so rf-like power transmission may be possible. Some other options may be motion or heat (it's a wearable device). The amount of power could be pretty small, as I only need it at peak periods, so I could just charge up a supercapacitor for a while and drain it when power is needed after the Attiny wakes up for less than a second.

The ideal situation would be to have a means of power transmission or generation that provides enough current to continuously power the microcontroller without the need for sleep, but I recognize that this is probably not feasible. However, due to the limited range it might be. Another concern is radiation to the wearer.

If anyone has any experience in this kind of power transmission or generation or just any ideas I would love to hear it. Thanks!

10mA is quite a lot for a coin cell. And of course the duration is really low.

As for wireless power transmission, I highly discourage you. Since you are using coin cell batteries I think that size is a must for you, and for wireless power you will need a really big antenna. If it is a wearable I think that the receiver is on the body too, and so much power is not a good thing.

In my opinion and according to my experience you have two possibilities:

use alkaline batteries (e.g. AAA). Use a step up driver to get 3.3V from 1.5V (since the current you need is low you can use simple charge pump regulators, so with a 10pin TSSOP integrate and three small capacitors you are done) and you will get a really long lasting circuit. Drawback: AAA batteries are a bit large, so probably you'll have to make a bigger receiver
use lithium batteries (usually I use LiPo). You will then be able to recharge the battery with any power supply (I usually use an IC which can charge LiPos with a 5V source - USB - and a couple of other components (two capacitors and a LED with its resistor).

Personally I struggled with coin cells for a long time before giving up and sticking with lipos forever.


Arduino Pro Mini I2C Problem I am trying to connect a distance sensor VL6180x to Arduino Pro Mini via I2C. Yesterday it was working without any problems, but today it refuses to work, even though I haven't changed anything. The sensor has a logic level shifter and pullup resistors onboard. I tested it with Arduino Uno and works perfectly again. However I can't get it to work with Pro Mini again. I am using the Wire library and the VL6180x library. Pins are A4-SDA, A5-SCL, VCC-VIN, GND-GND. Here is the code I am using. It is giving TIMEOUT all the time. I am using an FTDI USB to serial converter to program the Pro Mini.

#include <Wire.h>
#include <VL6180X.h>

VL6180X sensor;

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

  sensor.init();
  sensor.configureDefault();

  // Reduce range max convergence time and ALS integration
  // time to 30 ms and 50 ms, respectively, to allow 10 Hz
  // operation (as suggested by Table 6 ("Interleaved mode
  // limits (10 Hz operation)") in the datasheet).
  sensor.writeReg(VL6180X::SYSRANGE__MAX_CONVERGENCE_TIME, 30);
  sensor.writeReg16Bit(VL6180X::SYSALS__INTEGRATION_PERIOD, 50);

  sensor.setTimeout(500);

   // stop continuous mode if already active
  sensor.stopContinuous();
  // in case stopContinuous() triggered a single-shot
  // measurement, wait for it to complete
  delay(300);
  // start interleaved continuous mode with period of 100 ms
  sensor.startInterleavedContinuous(100);

}

void loop()
{
  Serial.print("Ambient: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }

  Serial.print("\tRange: ");
  Serial.print(sensor.readRangeContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }

  Serial.println();
}

This is the code bit I suspect the problem originates form in the VL6180x library:

uint8_t VL6180X::readRangeContinuous()
{
  uint16_t millis_start = millis();
  while ((readReg(RESULT__INTERRUPT_STATUS_GPIO) & 0x04) == 0)
  {
    if (io_timeout > 0 && ((uint16_t)millis() - millis_start) > io_timeout)
    {
      did_timeout = true;
      return 255;
    }
  }

  uint8_t range = readReg(RESULT__RANGE_VAL);
  writeReg(SYSTEM__INTERRUPT_CLEAR, 0x01);

  return range;
}

Here is my serial monitor:

   Range: 255
 TIMEOUT
   Range: 255
 TIMEOUT
   Range: 255
 TIMEOUT
   Range: 255
 TIMEOUT
   Range: 255
 TIMEOUT
   Range: 255
.....

Any help would be greatly appreciated.

The Pro Mini has a 3.3 volts regulator rated to 150mA, as you can see here https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf, it´s rated to work from 16V but by personal experience a 5V~5.1V 200mA power supply is the best option to power it without burning it, even if it burns, you can search at the internet something like

"Desoldering led and voltage regulator on Arduino Pro Mini"

Regards


Is it possible to extract the firmware of an Arduino BLE or IoT board wirelessly? I've looked at previous questions regarding sketch extraction and know that it is possible to extract the hex code from an Arduino board using avrdude from the command line.
However, I want to see if the following is possible:

Connect to Arduino 33 IoT board
Extract onboard Firmware as a hex file
Disconnect from Arduino 33 IoT board.

I understand that getting the initial source code is not possible, but I am in particular looking to just get the hex code in a wireless manner. If it is not possible via the Arduino 33 IoT board, is there any Arduino board with which this can be done? Any help or guidance would be appreciated.

Technically, the firmware can read its own application section, but it won't send it to you wirelessly (or via any interface) if such a feature isn't implemented in that firmware. If you were to implement the firmware yourself, you can do (almost) anything. But if it is a third party firmware, this will not be possible.
The reason this works with arduinos and avrdude is, because firmware up- and download are implemented in hardware (ISP, works without a bootloader).


Reading Arduino Serial Input I am reading an input from my Ohaus weighing scale using it's RS232 output using this code:

#define HWSERIAL Serial1

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

void loop() {
  int incomingByte;

  if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("USB received: ");
    Serial.println(incomingByte, DEC);
    //HWSERIAL.print("USB received:");
    //HWSERIAL.println(incomingByte, DEC);
  }
  if (HWSERIAL.available() > 0) {
    incomingByte = HWSERIAL.read();
    Serial.print("UART received: ");
    Serial.println(incomingByte);
    //HWSERIAL.print("UART received:");
    //HWSERIAL.println(incomingByte);
  }
}

When pressing the print button on the scale, I was expecting data to come over in single burst with just the readings, but what I am getting is the expected data, but the scale keeps sending data afterwards (ES over and over). I need to parse out just what's needed. The below is the output from the console on my computer.

UART received:
UART received:
UART received:
UART received:
UART received: 0
UART received: .
UART received: 0
UART received: 0
UART received:
UART received:
UART received:
UART received:
UART received:
UART received:
UART received: ?
UART received: (This is a CR)

UART received: (This is a LF)

UART received:
UART received:
UART received:
UART received:
UART received: 0
UART received: .
UART received: 4
UART received: 0
UART received:
UART received:
UART received:
UART received:
UART received:
UART received:
UART received: ?
UART received: G
UART received:
UART received:
UART received: (CR)

UART received: (LF)

UART received: E
UART received: S
UART received: (CR)

UART received: (LF)
... (The ES loops over and over until the print button is pressed again)

0.00 is the current scale reading and 0.40 is the tare weight. That's all I need and I can't figure out how to parse it. The blocks aren't the same length so how do I pull out the needed information and ignore the repetitive 'ES'? I'm not 100% sure if I'm even going about this the right way?

Output as DEC

UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 48
UART received: 46
UART received: 48
UART received: 48
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 63
UART received: 13
UART received: 10
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 48
UART received: 46
UART received: 52
UART received: 48
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 63
UART received: 71
UART received: 32
UART received: 32
UART received: 13
UART received: 10
UART received: 69
UART received: 83
UART received: 13
UART received: 10
UART received: 69
UART received: 83
...

From the manual:
http://dmx.ohaus.com/WorkArea/showcontent.aspx?id=4294974226

  The balance will return “ES” for invalid commands.

Check to make sure you're using the correct serial parameters that the RX line is wired correctly.