Arduino (or clone) powered with one or two AA batteries or one CR2032, but still able to give +3.3V or +5V Are there Arduinos (or clones) that can be powered with one or two AA batteries or one CR2032 3V battery? (it would sleep 99% of the day, and only send a few bytes per day)

If so, will they also have a +3.3V or even +5V output (produced by an internal step-up chip) that can be used by another chip?

(I know it might sound like having one's cake and eat it too, but maybe it exists?)

The modern low voltage versions of a bare ATmega chip can run from either 2xAA or a lithium coin cell - you wouldn't want to use a voltage regulator, as that is not only unnecessary but introduces losses but increases the required input voltage by its dropout meaning your circuit will fail earlier in the discharge curve that in it would without.

Bypassing the regulator on an Arduino Mini style of board is possible.  You probably do not want a board with an on-board USB-serial solution.

You'll need to make sure the clock rate is low enough for operation at the rated voltage (and for sleep efficiency).  This might involve using the fuse for the internal oscillator and ignoring a crystal/resonator that might be present, though if your board was originally intended for 3.3v operation it might be okay.

You will also need to set the brownout detector to the lowest voltage or disable it entirely - this again is in the fuses.

A boost converter to a higher voltage is possible but may not be a good idea, especially from a coin cell.  This is because to supply 1 milliamp at 5v, a boost converter must draw 2 milliamps at 2.5v - and then a bit more, to account for its own losses.  If you go shopping for a boost converter to use, make sure it has an enable, look at the quiescent power consumption when disabled and enabled without load, and look at the minimum input voltage.


Redirecting Arduino Serial Output to a File I am integrating the MPU-6050 Accelerometer + Gyro sensor into a large project that contains 12 Arduino boards and 6 Raspberry Pis. At some point, I will have to load the output of my MPU-6050 sensor into another application through command line. The process is to be all done with Python and Bash (on the Raspberry Pi side), and so what I need is a way to store the output of my Arduino boards.

What I am currently looking at is the python program ino. I have used the product for about a year now, and as far as I am aware of, the only way to exit out of serial mode in ino is by closing the command-line window!

Is there a way I can achieve what I've discussed above? Essentially, all I want is a way to hold the output of my Arduino serial output so I can use it later in other parts of my project.

Well, I don't know about your ino program, but here's how I'd do it:

get_serial.py

import serial, sys

with serial.Serial(port=sys.argv[1], baudrate=sys.argv[2]) as ser:
    while ser.isOpen():
        print(ser.readline())

The idea, here, is to print on stdout the data coming on the serial line:

python get_serial.py /dev/ttyACM0 115200 > output.log

or you can do it this way:

get_serial.py

import serial, sys

with open(sys.argv[3]) as f:
    with serial.Serial(port=sys.argv[1], baudrate=sys.argv[2]) as ser:
        while ser.isOpen():
            f.write(ser.readline())

which is ran:

python get_serial.py /dev/ttyACM0 115200 output.log

Hope this helps!


5V FTDI cable for Arduimu V3 I just recently bought an Arduimu v3. Rather annoyingly they did not supply an FTDI cable. I'm going for an FTDI cable where the I/O pins are configured to operate at 5v. I assume this is the right but I don't want to fry this board. Is this cable OK?


LED Matrix Display with dissimilar brightness So far I have seen in LED matrix related projects that the brightness is controlled in an entirety manner. That means the   brightness of total display can either be reduced or increased. How can we display only a part of the display with more brighter than the remaining matrix? Appreciate if anyone provide some pseudo logic to achieve this.

There's two options:

Use a matrix driver that supports different brightnesses per pixel, or:
Rapidly display a different arrangement of pixels in quick succession. The pixels that are on more often are brighter.

Option 1 basically does option 2 in hardware.

The theory is simple:  For one LED you can vary the brightness by using PWM - that switches the LED on and off very rapidly. The longer it is on the brighter it appears.

You can do the same with a matrix of pixels. Instead of dealing with one pixel though you are dealing with, in effect, a series of "images". Each "image" has a different combination of pixels. The more "images" you have the greater variation you can get in your pixel brightnesses.

For example if you first display a frame of:

. . . . . . . .
. . # # # # . .
. # . . . . # .
. # . . . . # .
. # . . . . # .
. # . . . . # .
. . # # # # . .
. . . . . . . .

followed by the image:

. . . . . . . #
. . # # # # # .
. # . . . # # .
. # . . # . # .
. # . # . . # .
. # # . . . # .
. # # # # # . .
# . . . . . . .

then you will get a bright circle(ish) shape with a dimmer slash through it.

The only problem with this method is flicker. You have to have your matrix refreshing very fast. The more "images" you have to display in sequence the more it will flicker and the faster you will have to refresh your matrix to compensate.


Is a 9v battery appropriate for a piezo and 1 LED? I'm making a basic "door open" detector that, when a door is opened, it turns on an LED and then sounds an alarm via a piezo.

This is controlled via a 5v Adafruit Trinket.

Is a 9v battery the correct thing to power this with, if the goal is to change batteries as infrequently as possible?

Here's the code, incase that's relevant.

#include <elapsedMillis.h>
elapsedMillis timeElapsed;

const int switchPin = 2;
const int ledPin = 1;
const int piezoPin = 0;
const uint32_t openLength = 5 * 1000L; // X seconds
int notes[] = {862,294,730};

void setup() {
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  digitalWrite(switchPin, HIGH);
}

void loop() {
  if(digitalRead(switchPin) == LOW){
    digitalWrite(ledPin, LOW);
    timeElapsed = 0;
  } else {
    digitalWrite(ledPin, HIGH);

    if (timeElapsed > openLength){
      for (int n = 0; n < 200 ; n++){
        beep(notes[random(0,2)]);

        if(digitalRead(switchPin) == LOW){ break; }
      }
    }
  }
}

void beep(int delayAmount)
{
  for (uint16_t t = 0; t < 30*1000/2; t += delayAmount)
  {
    digitalWrite(piezoPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(piezoPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

UPDATE: I had a 9V plugged in to this for about 3 days before it used all the power in 9V. Is that an issue w/ voltage on the battery (i.e. I should be using AA's instead of a 9V)? Or does that point largely to some other inefficiency w/ the code or hardware?

A couple things to note:

Get rid of the PWR LED on the Trinket so it's not always drawing current.
Sleep the MCU whenever possible, only waking on interrupts.
Converting 9V to 5V with an LDO (in this case, the MIC5225) implies a 55% efficiency, max, which isn't great. But at least the LDO has a low ground current.

Also, ask yourself if you really need a micro for this task.

If you want a ballpark for runtime, find the capacity of your battery, estimate your current draw, and see what your upper bound on runtime is.


A1-A5 pins not declared in this scope error When I set my board to 'Generic ESP8266 module'  then only A0 pin of arduino is working while all other analog  pins are coming out of scope ,
 when I set the board to 'arduino /genuino uno' ,
 then "Error compiling for board Arduino/Genuino Uno." this error is coming how to set the board such that all analog pins with ESP8266 will work?

If you look at the ESP8266 pinout diagram (for example here), you will only find 1 analog input: A0. This is because the ESP8266 simply just has 1 analog input. The Arduino IDE states A1-A5 being out of scope, because on that board these inputs just don't exist. That is completely correct.

Also: When you try to compile code, that is meant for an ESP, for the Arduino Uno board, it will naturally fail, because it is just different hardware. The ESP basis code just cannot run on the Uno.

You will have to compile the code for the board, that you actually want to use AND you can only use codes/libraries, that are meant for your board. You cannot mix them in general. Only some function might be transferable (if so, it will not be easy) and WiFi is definitely not something to transfer to the Uno, which doesn't have the hardware for it.


Why does Arduino Tone example with 8 ohm speaker make USB port fail? I'm using an Arduino Nano and attempting to run the basic sample program at:
https://www.arduino.cc/en/Tutorial/toneMelody

When I build the circuit they way they show (extremely simple) using an 8 Ohm speaker and connect the power to USB the Nano begins to power (never fully powers up) and then the USB port fails (I believe as a protection mechanism).

Is the schematic provided with that sample incorrect?
They say it can be used with an 8 Ohm speaker but they show it hooked up with e piezo.
Here are the comments from the Sketch:

Is it possibly overdrawing current with the 8 Ohm speaker?
Is the circuit incorrect in some way?
NOTE: Without the speaker connected the Nano powers up with no problem. I am also building other circuits with the Nano and they work fine.

As already mentioned in your question, in the Arduino tutorial "Melody" under "Hardware Required" is stated "piezo buzzer or a speaker" and in the comment that heads the sketch is stated: "8 ohm speaker on digital pin 8". But the pictures under "Circuit" and "Schematic" show a piezo sound transducer.

In any case the word "buzzer" is wrong. A buzzer usually has a built-in oscillating circuit or mechanism and, when energized, produces sound at a more or less fixed frequency. Better would have been: a piezo speaker and a 'normal' (moving coil) speaker.

There is a big difference between a piezo and a speaker: under a dc-voltage the piezeo wil have a near infinitive resistance and the 8 Ohm speaker roughly 4 Ohms. At 400 Hz the piezo has an impedance of roughly 2000 Ohm (there is a huge range of piezo's with varying characteristics), while the impedance of the normal speaker will be roughly 10 Ohm.

One side of the buzzer/speaker is connected to Ground, therefore current is only flowing when the side connected to pin 8 is HIGH (pin 8, has to source the current and not to sink it).

The datasheet of the Atmega328P states at page 299 that the absolute maximum ratings (which is not the same as maximum allowable operational ratings) are 40 mA for an I/O-pin is 40.0 mA and 200 mA for Vcc and Ground pins.
The datasheet shows a graph (fig. 35-24 at page 600) showing "I/O Pin Output Voltage vs. Source Current (VCC = 5 V)". From this graph an internal resistance of about 26 Ohm can be derived. The graph does'n show what happens at pin-currents larger than 20 mA, but let's guess the internal resistance stays about the same 26 Ohm.

When pin 8 is constantly HIGH (5 V at 0 Hz) the current through the speaker would be about 5/(26+4) = 167 mA. This is far above the 40 mA maximum rating for the pin current, but not enough to trip the USB-fuse (trips at 500 mA). When this situation lasts the pin-driver will be destroyed. This could cause an internal open circuit (with no further consequences) or an internal short circuit which might cause a supply current higher than 500 mA which would trip the USB-fuse. In this case pin 8 would be permanently destroyed which is easy to establish. If pin 8 keeps working, this scenario doesn't happen.

Normally the sketch "Melody" would not output a dc-signal (0 Hz). At 400 Hz the pin current would be 5/(26+8)= 147 mA. This is still far above the maximum rating for the pin current and the scenario is the same as above.

So the only way the USB-fuse could be tripped is when the pin driver burns out and causes a short-circuit from Vcc to ground. Reading between the lines, my impression is that Raddevus tried this out more than once, which means that pin 8 keeps working. Also I don't think that it is likely that an burn-out of a (few) transistor(s) of an IC causes a short-circuit. Therefore the cause for tripping the USB-fuse must lie elsewhere.

A last consideration is that Raddevus mentions (in his comment of June 18 at 15:34) three input buttons which are not in the 'schematic' shown with his question. He also seems to use a dodgy board ("missed ground hole on bboard, hit 5v"). So may be we don't see all the factors involved.


Reading and Writing on different clock edges with Arduino SPI interface I'm trying to simulate a certain µController to characterize and measure a certain chip.

I need to write my data on the negative edge of the master clock and read the data coming from the slave in the positive edge of the master clock. Is there any way I can have this kind of freedom in my code? Or do I have to do it manually without using the predefined SPI interface?

Also, I would like to have my master clock running continuously without going idle… is there a way to do that too?

To set the spi to shift out on falling edge and shifting in on rising edge of the clock you need to set the spi mode to 0 or 2 (depends on idle clock polarity).

More info here

To continuously generate clock signal as far as I remember you will need to write to the SPI dummy values.


Cannot move TM1637 from Uno to Pro Mini I have a very simple setup which works fine with an Uno.

#include <SevenSegmentTM1637.h>
#include <SevenSegmentExtended.h>

const byte PIN_CLK = 2;
const byte PIN_DIO = 3;
SevenSegmentExtended display(PIN_CLK, PIN_DIO);

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

  display.begin();
  display.print(F("TEST"));
}

void loop() {}

When I use the very same setup with a Pro Mini (XCSOURCE ATMEGA 328P, 5V 16Mhz), the display doesn't light up. I get monitor outputs and can blink the onboard LED, but no reaction from the TM1637 display.

I get this output in the console:

�E%MA1e� 10001111
Acknowledged: 0
ADDR :  11000000
DATA0:  0
write byte: 84
ADDR :  11000000
DATA0:  1111000
write byte: 69
ADDR :  11000000
DATA0:  1111000
write byte: 83
ADDR :  11000000
DATA0:  1111000
write byte: 84
ADDR :  11000000
DATA0:  1111000

Does anyone have an idea how to debug or fix this?

Since you're using a Grove Display, I believe it will be using I2C.

For better debugging, try using the actual I2C pins on your Pro mini, which are A4 and A5.

  I2C: A4 (SDA) and A5 (SCL). Support I2C (TWI) communication using the
  Wire library.
  https://www.arduino.cc/en/Main/ArduinoBoardProMini

I2C may need pull-up resistors on your data lines.

(https://en.wikipedia.org/wiki/I%C2%B2C)

It can also be nice to use "verified to be working" code, like example code from the manufacturer.

/*
 * TM1637.cpp
 * A library for the 4 digit display
 */
#include "TM1637.h"
#define CLK 39 //pins definitions for TM1637 and can be changed to other ports
#define DIO 38
TM1637 tm1637(CLK,DIO);
void setup()
{
    tm1637.init();
    tm1637.set(BRIGHT_TYPICAL);//BRIGHT_TYPICAL = 2,BRIGHT_DARKEST = 0,BRIGHTEST = 7;
}
void loop()
{
    int8_t NumTab[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//0~9,A,b,C,d,E,F
    int8_t ListDisp[4];
    unsigned char i = 0;
    unsigned char count = 0;
    delay(150);
    while(1)
    {
        i = count;
        count ++;
        if(count == sizeof(NumTab)) count = 0;
        for(unsigned char BitSelect = 0;BitSelect < 4;BitSelect ++)
        {
            ListDisp[BitSelect] = NumTab[i];
            i ++;
            if(i == sizeof(NumTab)) i = 0;
        }
        tm1637.display(0,ListDisp[0]);
        tm1637.display(1,ListDisp[1]);
        tm1637.display(2,ListDisp[2]);
        tm1637.display(3,ListDisp[3]);
        delay(300);
    }
}

You will need to adapt the pin numbers.

But after these steps it should work just fine.

Source: http://wiki.seeed.cc/Grove-4-Digit_Display/


Not sure I'm understanding pipes for NRF24 I've started working with the NRF24 library for some fun little side projects. I have only gotten through some basic tests but I'm starting to look at ways to tinker with the code. I have more experience as a programmer so the hardware side is always new to me. Where I'm a little confused is how the pipes are used. Working from this example, I see that one pipe is used to listen and another is used to transmit. If there's just two devices, why don't they both use the same pipe? If you have multiple devices on the same pipe transmitting, can it jumble the signals? Is there a way to receive on multiple pipes? I'd love more information on how pipes are or should be used.

I don't see any reason for doing this.

Multiple devices sending data at the same time will cause collisions irrespective of the pipe-nr they are using.

Pipe is also a not very accurate name for what it actually is. It's just a number, that the receiving NRF can check, to see if the packet that was received was intended for it. Kind of like a MAC address on a network.

You can have two unique reading pipes. Then there are 4 more pipes you can use, that are identical to the second pipe, except for the last byte.

The first pipe is used to specify the pipe you are sending through. So if you send to different pipes, this pipe isn't ideal for listening, as you'd have to change it back every time you send a packet. Possibly loosing a packet that was send in between.

If you want more information, i'd suggest reading the datasheet, and read the documentation of one of the libraries. I personally checked the sourcecode of the library a lot while at the same time referencing the datasheet, to really understand what it's doing.


Getting external data to the Arduino I have a new Uno R3, it's pretty cool and I've enjoyed playing with it.

Now I want to build a couple of things:

1) a market price LCD tracker.

2) a servo motor type thing to open my electric gate.

Both of these either require input from an external website or some kind of message to initiate the action on the Arduino.

How do people generally get data onto the Arduino, I found a lot of conflicting information online.

Does this thing have Wifi or Bluetooth??

I got this pack, it doesn't seem to have either Wifi or Bluetooth, if not how do ppl generally get data onto the Arduino?

I have a raspberry pi spare, can I just use that, sending data from pins?

How do people generally get data onto the Arduino, I found a lot of conflicting information online.

There are various ways depending on what the data is and how you access it.

  Does this thing have Wifi or Bluetooth??

Not unless you add WiFi or Bluetooth to it, no.

  I have a raspberry pi spare, can I just use that, sending data from pins?

Yes, there are ways.

How you go about getting data on to an Arduino depends very much on how the data is accessed.  It is possible to add a WiFi interface to an Arduino, either through an official WiFi shield or through adding something like an ESP8266 on a breakout board (ESP-01 is popular) although interacting with the ESP8266 can be tricky.

You can do the same with Bluetooth or any number of other wireless protocols.

The simplest method of getting data to the Arduino, though, is through the USB serial port. Since you have a Raspberry Pi available the most logical option would be to plug the Arduino directly into the Pi's USB port. The Pi can then communicate through /dev/ttyACM0 (or /dev/ttyUSB0 for some clones) and the Arduino receive the data through the Serial object. Exactly how you arrange all that is entirely up to you.


Does SoftwareSerial use hardware timer? I'm asking this because I'm using a timer to generate a 38KHZ signal to drive an IR diode, and I also need to use SoftwareSerial to talk to an HC-12 radio using serial communication.

The code I'm using was written by Nick Gammon and is here:

//Setup Conter/overflow to create 38KHZ drive for IR38KHZ
//38khz, no interrupts
#define IR_CLOCK_RATE 38000L
// toggle on compare, clk/1
TCCR2A = _BV(WGM21) | _BV(COM2A0);
TCCR2B = _BV(CS20);
// 38kHz carrier/timer
OCR2A = (F_CPU/(IR_CLOCK_RATE*2L)-1);
pinMode(IR38KHZ, OUTPUT);

I'm not quite up-to-date on the timer use on an Arduino (I'm using a Nano), plus I've no idea what the SoftwareSerial library uses.

No. It uses pin-change interrupts to trigger reception, and both reception and transmission use calibrated delay loops.  However, interrupts are disabled during both transmission and reception so that the calibrated delay loops remain always the precise length - so if you do anything with any other interrupts they will not work at the same time as SoftwareSerial.


Error compiling Arduino I've just installed the last version of Arduino 1.6.7 plug my Arduino SmartEverything (http://www.smarteverything.it/) to OS X 10.11.2, try to compile this project: https://github.com/nicolsc/sigfox-weather-station/blob/master/sigfox_smart_weather.ino But i got this error

/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
Build options changed, rebuilding all
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/preproc/ctags_target_for_gcc_minus_e.cpp"
exec: "-w": executable file not found in $PATH
Error compiling.

Install Arduino SAMD Boards (32-bits ARM Cortex-M0+) board (using "Tools" -> "Board" -> "Boards Manager" menu).

Just search for "SAMD" in the search bar, choose the latest version and install.


Write array to serial port The Code Below now works:

void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  //Serial.write(cmd[i]);
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

Input is a series of ASCII-encoded hex digits and getting the output to print the byte values of the hex.

There's some logic slightly askew with your length calculations:

int clen = input.length()/2;

Ok, so for a (say) 20 character string you have clen=10.

for (int i=0; i < clen; i+=2)

Ok, so for the first 10 characters of your 20 character string you take alternate ones (0, 2, 4, 6, 8)

What about the last 10 characters?  clen is 10, not 20, since you divided it by 2 at the start.

Decide if you want clen to be half the string length, then count double, or is the whole string length, and you divide it by 2 where you want the final string length. Or have two variables - one before and one after dividing by 2.

Oh, and you should pass your String parameter by reference so you don't duplicate the object and end up fragmenting your heap.

void SendCTRL (String &input)

I haven't gone into depth about the working of your dehex function, but this is the function I always use and works well:

unsigned char h2d(char hex)
{
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

Also you should or your values together, not add them:

cmd[i/2] = (dehex(hin[i])<<4) | dehex(hin[i+1]);

This would go some way to fixing your current issue, since | has a different precedence to +. At the moment you have effectively:

cmd[i/2] = dehex(hin[i]) << (4 + dehex(hin[i+1]));

since the + happens before the <<, whereas what you want is:

cmd[i/2] = (dehex(hin[i]) << 4) + dehex(hin[i+1]);

However with | instead you get

cmd[i/2] = (dehex(hin[i]) << 4) | dehex(hin[i+1]);

because the << happens before the |

Here is your code written in pure C to run on a PC (faster to debug and test than an Arduino when you're on Linux):

#include <stdio.h>
#include <string.h>

unsigned char dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

void SendCTRL (const char *hin)
{
  int ilen = strlen(hin);
  int clen = ilen / 2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < ilen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
    printf("%02x\n", cmd[i/2]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  for (int i = 0; i < clen; i++) {
    printf("%c", cmd[i]);
  }
}

void main() {
    SendCTRL("010307E40001C549");
}


elechouse Voice recognition v3 module not responding when i send command using Access port serial tool I have this challenge of receiving data when I send a command to voice recognition v3 module. the uart connections are okay, but when I send a command I don't receive a response on the terminal. the prolific usb-ttl with drivers installed blinks when I send a command but still I get no response. please help in debugging.

The module can't communicate with Serial Monitor over a USB to TTL Serial adapter. It uses binary communication. Use Arduino, Arduino library and one of the example sketches of the library to communicate with the VR module.

And read the manual.


How do you make a switch case run until another serial input is detected? I am trying to create a Traffic Light Controller.
There are three modes to the controller:
Mode 1 - the traffic light operates RED-YELLOW-GREEN-YELLOW and should repeat
* (The other modes are not necessary apart from knowing the user can select the mode.)*

I want to loop the function of the mode until I receive an input from the serial monitor. If no input is detected, then it should continue with the current mode.
At the moment I am using Serial.read() at the start of the main loop function before my switch statement to select the mode. However, this needs an input, but I want the switch cases to loop until an input is received.

All help will be much appreciated.

Use something like this (it is pseudo code so convert it to your sketch):

enum EState { NORMAL, SPECIAL } _state; // States
enum ENormalState { RED, YELLOW1, GREEN, YELLOW2 } _normalState; // State only valid when _state == NORMAL
unsigned long _time; // _time only valid when _state == NORMAL

void loop()
{
   if ('serial input available')
   {
      if ('input == ...')
      {
         _state = NORMAL;
      }
      else if ('input == ...')
      {
         _state = SPECIAL;
      }
      ...
   }

   switch (_state)
   {
   case NORMAL:
       if (_time + ... > time())
       {
          // Change to next state
          switch (_normalState)
          {
          case RED:
              _normalState = YELLOW1;
              _time = time();
              break;

          case YELLOW1:
              _normalState = GREEN;
              _time = time();
              break;
          ...
          }

       setLight(_normalState); // Change the light according to the _normalState
       break;

   case SPECIAL:
       ...
       break;

   ...
   }
}

Ideas to improve/explain:

Try to make some specific functions for setting the light according to the current state
You do not need a delay
Split functions (like above, make a separate function for normal state, and specific state


How to use BlueTooth on mobile device to find AccessPt and enter PW for ESP8266 WiFi on an Arduino controller? How can I use BlueTooth on a mobile device to connect to my HC-05 equipped instrument to find the local WiFi AccessPt and enter the PW for my Arduino controlled instrument with ESP8266 WiFi?

I want to set up remote Arduino controllers with WiFi (ESP8288) connections in various locations where I have to log in to the Access Pt.  I want to use my phone to make the AP connection, connecting to my instrument's HC-05 via BlueTooth.  Does anyone have any code for this?  (RoboRemo?)  Or am I missing another simpler solution?

Consider the Amazon Echo:  You download the app to your phone.  You start the app and connect it to the Echo.  How?  Magic? No, BlueTooth.  Next step:  Use the app to enter your AP settings.  The Echo is now connected to your WiFi.  Delete the app.

I want to setup my Arduino devices the same way.

Don't overcomplicate things by adding bluetooth.

If you want to set the WiFi credentials at run time, use the WiFi Manager library. It's exactly what it was designed for.


How can I get my Arduino to recognize a specific object using some kind of sensor? This is my first question on this site, and I'm relatively new with Arduino. I do have some experience using the board to reprogram a robot that used infrared proximity sensors, servos, and switches.

I would like to add a sensor on to the robot that will allow him to recognize specific "obstacles" that I will put in his environment (not walls!) For instance, when he sees a red card, he needs to spin, but when he sees a green card, he needs to roll in the opposite direction. I do not want to spend much on the cards, but I would be willing to put a small battery and LED in them if I had to. The cards do not necessarily need to be colored, I was just using that as an example.

The robot will be in a well-lit room with noise in the background. He will be controlled by an Arduino Uno, an infrared sensor and a remote control. He can be pretty close to the cards if he has to (3 centimeters or so would be enough). It would be ideal if he could discern different types of cards, but that is not necessary as long as he's able to tell a card from the rest of his environment.

I am simply not sure how to go about implementing this. I have read about using photoresistors to differentiate color, and they're really cheap, but will they be accurate enough from a distance? This is the light sensor I was considering using:

http://www.mouser.com/ProductDetail/Adafruit/161/?qs=GURawfaeGuDpQ5XPTNqKUw%3D%3D&gclid=Cj0KEQiA6IC2BRDcjPrjm_istoUBEiQASrLz1rQNwZgntUcccnOmrFph-pCbu60R00GNozB_XbZxYz0aAn0j8P8HAQ

I'm willing to pay about 5$ for one if I need to.

If I use the light sensor method, can I just use brightly colored cards or will I need to use LEDs? Is there a better way to accomplish my goal that you are aware of?

Thank you for your time. If there is missing information in my question, please tell me and I will add it.

You can get an RFID reader for $7 from eBay:

Cards are around 30 cents:

I have example code for an entry control system which uses that reader.

The cards tend to activate at around 3 cm to 5 cm, so that sounds about right. Of course they aren't particularly directional, but if you are driving in a certain direction and it detects a card it is probably in front of you (however possibly off to one side).

You could combine card detection with simple range finding using an ultrasonic detector.


Arduino sending data over MAX485 I would like to introduce myself as a student from Czech Republic. I'm currently I'm working on a Meteostation project.

I've got Arduino set up, with plenty of weather sensors, as well as WH1080 sensors connected.

Right now, I'm only able to read the data via serial port on computer with Arduino IDE or show it on my 20*4 display.

Because of the distance between source of data and recipient of data, wireless data transfer is unsuitable for my application.

I found these MAX 485 modules on eBay for cheap:

I quickly got 2 pieces, as well as 5v-3.3v logic level shifter, as I was concerned about different logics on Raspi. I don't know much about Raspi and their pins, as the only thing I ever used with them was DS3231 real time clock module.

Now, the thing I'm trying to achieve is this - I want to be running a bunch of sensors at roof of our house, and have the Arduino send the data to Raspi over the rs485 (on request? as the sensor loop would be like 10-15min so maybe communicate on interrupt?)

What I'm planning to do with the data on the raspi would be running a software like WeeWx or wfrog to process them and possibly render a local website, that I could make public as port forwarding (I have public IP).

However, there are few questions I have, hopefully its not too much to ask

How would the wiring look like? I was unable to find any dumb-proof tutorial online, as I don't know whether or how to use the logic level shifter.
If I can read the data over serial port, would it be just a plain text (as shown on PC in Arduino ide serial monitor), or has each value its address that I could then easily accessing to a variable then being used to process the weather data?
If I'm completely wrong in something, or there's some completely different way how these things are being done by more experienced people, I'd love to hear some suggestions.

Thanks in advance for any kind of response, as this is at the moment causing me headaches, as I'm unable to do this on my own. I don't expect anyone to do all the work for me, maybe just point me in the right direction.

How would the wiring look like? I was unable to find any dumb-proof
  tutorial online.

I found this tutorial to be pretty usefull.

There really isn't much to it, I suggest trying a short range before going full range.
It's a "half duplex bus system" the ends of the bus should have a "end termination resistor", usually 120Ohms, between the A and B signal.
Since it's half duplex, the Pi and Arduino can't talk at the same time.
You'll have to pull the DE and RE pins high when you want to transmit (and keep them low for receiving).

Basic sketch would be something like:

#define TXEnablePin 13

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

void loop(){
  String data = "";
  Unsigned int sensorValue1 = Sensor.getValue();
  Unsigned int sensorValue2 = Sensor.getValue();
  data += str(sensorValue1) + ":" + str(sensorValue2) + ";\r\n";
  send(data);
  delay(10000);
}

void send(String data){
  digitalWrite(TXEnablePin,HIGH);
  delay(1);
  Serial.send(data);
  Serial.flush();//Wait for everything to be transmitted, before disabling transmitter.
  digitalWrite(TXEnablePin,LOW);
}

  I don't know whether or how to use the logic level shifter.

These things are pretty straight forward. You should actually be able to figure it out yourself (given you have the power of the internet).

LV to 3.3V of Pi
GND to GND of Pi
GND to GND of Arduino
HV to 5V of Arduino

Then, whatever 5V signal you want to connect to HVx and whatever 3.3V signal you want to connect to LVx

Example:
Arduino-TX -> HV1
Arduino-RX -> HV2
Pi-TX -> LV2
Pi-RX -> LV1

  If I can read the data over serial port, would it be just a plain text
  (as shown on PC in Arduino ide serial monitor), or has each value its
  address that I could then easily accessing to a variable then being
  used to process the weather data?

It would be ASCII (plain text) if you send strings.
You could make different types of requests.

Like; If you send: "Temperature" to the Arduino, it will respond with: "TEMP:10" or something.

But the easiest thing would be to send all values of all sensors in a combined string every 10 seconds or so. And let the Raspberry Pi unpack that string.

  If I'm completely wrong in something, or there's some completely
  different way how these things are being done by more experienced
  people, I'd love to hear some suggestions.

I think it's pretty good that you actually already know of the existence of RS485 and why you'd want to use it.

But I also feel that you feel a little uncomfortable with the project as it is.
It's important to handle problems one by one, to avoid getting overrun by problems.
Try to make it working over (short) USB first. Then try a short RS485 link and eventually try a long RS485 link. You can then more easily spot where the problem is. Use facts from multiple tutorials, to boost the confidence you have in the system ;). It may just work if you wire it as said. If it doesn't work, you can always post a question.

If possible, it may also be worthwhile to follow some tutorials on Arduino (get a starter kit and book with tutorial projects?). Within these tutorials they give examples of problems and show what there is to solve them. Without throwing yourself into a dark pit of a project.


3,6V DC motor spinning with L298N and Arduino I'm trying to control a re used DC motor from a drill (3,6V) with a L298N and a Arduino. It's powered with a 5V - 60A power supply.

I tried to follow this step by step tutorial (https://www.youtube.com/watch?v=dyjo_ggEtVU) but the motor is not spinning..yet. I can ear a noise, it starts to spin a micron and then stops.

I though that it could be something wrong with the power supply but I connected the 4V battery from the drill and the same thing is happening. If I connect the motor directly to the battery it is spinning nicely...

I though then that it was a code issue but I tried a no load test and measured the voltage without the motor -> I've the 4V required voltage. When the motor is connected I have 300mV instead of 4V.

Do you know what could go wrong? Is the L298 dead? just got it a few hours ago...

Would be nice if you have any clue.

Many thanks.

// Commande moteur
    int enA = 9;
    int in1 = 8;
    int in2 = 7;

void setup()
{
  // Définition des sorties

  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  //Sens de rotation du moteur

  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);

  //Vitesse de rotation du moteur

  analogWrite(enA, 200);

  //Delay

  delay(5000);

   //Arrêt du moteur

  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
}

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

}

The L239 is a terrible motor driver. It's the kind of motor driver Noah used to control The Ark.

It requires a power supply that is at least 2.5V more than the "logic input high" voltage, which is rated at 2.3V. That means an absolute minimum of 4.8V, which is borderline for the Arduino's 5V pin, especially if you are running off USB (which can drop as low as 4.75V and still be within specification) and way out when powered from the battery.  It's really designed for driving motors in the 12V+ range.

To drive a low voltage motor like yours you need to pick a more modern MOSFET based motor driver.


Direct port manipulation to write 40 bits I have 5 shift register changed in series and want to shift the data quickly. I have learned that the internal shiftOut function is slow and direct port manipulation can speed up the things.

However, I am not sure to write code in the specific way.

The current working code block is:

#define SensDataPin 4
#define SensClockPin 9
#define SensLatchPin 8
updateAllShifters()
{
digitalWrite(SensLatchPin, LOW);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_1);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_2);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_3);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_4);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_5);
digitalWrite(SensLatchPin, HIGH);
}

As the code shows, I have 5 bytes which are written by independent functions and just before the return statement, these functions call "updateAllShifters()" to mark the changes.

I have followed few tutorials over the internet and have re-written the logic like:

#define MSDATAHIGH PORTD |= (1<<PD4)
#define MSDATALOW PORTD &= ~(1<<PD4)
#define MSLATCHHIGH PORTB |= (1<<PB0)
#define MSLATCHLOW PORTB &= ~(1<<PB0)
#define MSCLOCKHIGH PORTB |= (1<<PB1)
#define MSCLOCKLOW PORTB &= ~(1<<PB1)
updateAllShifters()
{
MSLATCHLOW;
for(int i=0;i<40;i++)
{
HOW TO CODE HERE USING THE DEFINED MACROS!
}
MSLATCHHIGH;

Edit: Coding example of this (but want a more optimized way):

#define MSDATAHIGH PORTD |= (1<<PD4)
#define MSDATALOW PORTD &= ~(1<<PD4)
#define MSLATCHHIGH PORTB |= (1<<PB0)
#define MSLATCHLOW PORTB &= ~(1<<PB0)
#define MSCLOCKHIGH PORTB |= (1<<PB1)
#define MSCLOCKLOW PORTB &= ~(1<<PB1)
updateAllShifters()
{
MSLATCHLOW;
for(byte i=0;i<8;i++)
{
 if(!!(byte_1 & (1 << i)));// LSBFIRST
   {
   MSDATAHIGH;
   }else
   {
   MSDATALOW;
   }
}
 MSCLOCKHIGH;
 MSCLOCKLOW;
//DO ABOVE FOR ALL REMAINING 4 BYTES
MSLATCHHIGH;
}

I have few SPI ADC which have forced SPI bus down to 1 Mhz. I understand that the shiftout works at 14Khz which is too slow.

You can change the SPI speed at any time. Once the device is selected (Slave Select asserted) then reconfigure the SPI bus for high speed operation.

eg.

SPI.setClockDivider(SPI_CLOCK_DIV2);

SPI is definitely the fastest way you can communicate with a shift register.


Minimum circuitry required to program an AVR Where is the information what is the minimum-required circuitry to program any AVR via ICSP?

Sometimes I see schematics that show just the chip and the six wires for the ICSP header (RESET, VCC, GND, MISO, MOSI, and SCK).

Other times, I see some passive components connected to some of the pins.

So why is it different some times? How do people know when to use extra components when wiring up the chip for programming? Do the datasheet for these MPU's provide the details?

I have a page about a minimal board. The minimal circuit is the chip itself, and a couple of decoupling capacitors. A pull-up on /RESET is advisable (however the processor has a weak pull-up on it).

The six wires you mention are required for ICSP programming. An example from my page is:

That is using an Arduino as an ICSP programmer.

I think most designers would mandate the decoupling capacitors. You may get away without the pull-up on /RESET but probably at the expense of reliability.

The wires changed colour between the two photos because my earlier board (shown second) had the capacitors further away from the chip pins than they should have been. They really should be next to the chip for maximum effectiveness.

Note that, depending on the fuses, you may need to supply an external clock. In my case I did it like this:

The default chip fuses (from the manufacturer) does not require a crystal.


Soil moisture sensor, weird readings I'm  having a small problem with my soil moisture sensor

it gives me weird readings, in the second the smallest connection is made between the legs it just gives me 4096 (which is max possible value), its either about 0 or 4095

I can't really seem to see the problem, any help is appreciated

(the output voltage is read on an ESP32, almost visible in the bottom of the image)

It looks like you're trying to measure the resistance of soil by connecting an ADC input through the soil to VCC.  That is not the way to to it.

At the moment you effectively have this schematic for that portion:

simulate this circuit – Schematic created using CircuitLab

The voltage dropped across the soil is proportional to the current flowing through it. And there is no current flowing through it1 because there's no path to ground, only the very high impedance of the ADC.

So you never see anything except VCC (or a floating input when the probe is not in the ground).

To measure a resistance like that you have to have it as one half of a potential divider, just like you would for an LDR.

simulate this circuit

What actual value R2 should have depends entirely on the resistance range detected by your probe. It can be good to experiment with different values until you find one that works for you.

1: Actually there is some small leakage current through the ADC to ground, but that is so tiny we can ignore it.


src folder in sketch structure and include library from subfolder My Arduino/PlatformIO libraries folder

libraries
└── cleaner_robot
    └── TB6612_Dual
        ├── tb6612_dual.h
        └── tb6612_dual.cpp

I used this code to innclude it:

#include <TB6612_Dual/tb6612_dual.h>

But the compilation has errors like "undefinded variables, undefinded reference,...etc"

This is my sketch folder

Cleaner_Robot
└── src
    └── TB6612_Dual
        ├── tb6612_dual.cpp
        └── tb6612_dual.h

If i use this code, all is ok

#include "src/libs/TB6612_Dual/tb6612_dual.h"

So the question is how to include if header file is in a sub folder of a folder in libraries folder of Arduino/PlatformIO ?, i has searched for many things, but cant help.
I also read about src folder allowed in Arduino, but where can find an official announcement/manual for this structure ?, cant find much about this

Thanks  :)

I could include header files in subfolder after including root header file.

#include <TB6612_Dual.h>
#include <TB6612_Dual/tb6612_dual.h>

TB6612_Dual
└── src
    ├── TB6612_Dual.h << Add this empty file.
    └── TB6612_Dual
        ├── tb6612_dual.cpp
        └── tb6612_dual.h

Examples:

utils_asukiaaa/examples/string/string.ino
utils_asukiaaa/src/utils_asukiaaa/string.h
utils_asukiaaa/src/utils_asukiaaa/string.cpp
utils_asukiaaa/src/utils_asukiaaa.h


How to pull a pin low? On the instructions for this motor driver, it says that motors can be put to sleep by "pulling a pin low".

  SLP - Logic Input. When pulled LOW, outputs are disabled and power consumption is minimized.

I'm guess this means connect to ground? How could I trigger that via my Arduino board?

Connect it to an IO port and set it to OUTPUT and LOW. That's what it means to "pull low".

It helps if you understand how an IO port works. This may help you.


How to fix: Invalid conversion from 'const char*' to 'char*' [-fpermissive] I'm trying to upload the code from here to work with an ESP8266. So I copy/pasted the code to the Arduino IDE and I get this error:

  C:\Program Files (x86)\Arduino\libraries\WiFi\src/WiFi.h:79:9: error:   initializing argument 1 of 'int WiFiClass::begin(char*, const char*)' [-fpermissive]

  int begin(char* ssid, const char *passphrase);
         ^

  exit status 1
  invalid conversion from 'const char*' to 'char*' [-fpermissive]

Can anyone help me with this?

This begin() method expects a modifiable character array as its first argument. That's what you should provide:

char ssid[]           = "YOUR_SSID";      // this is changed
const char* password  = "YOUR_PASSWORD";  // this is fine
[...]
WiFi.begin(ssid, password);


How to use php file_get_contents with ESP8266 A part of my project need to get datas from an ESP8266 with php script. I tested this script and i don't know why i can get the datas in an iframe element and nothing with file_get_content function. In iframe element my browser displayes "Hello my friend!" as wanted:

The ESP8266 server mode at 192.168.4.1 address, part of code:

String webpage = "
Hello
";
webpage += "
my
";
webpage += "
friend!
";

String cipSend = "AT+CIPSEND=";
cipSend += 0;
cipSend += ",";
cipSend +=webpage.length();
cipSend +="\r\n";

sendData(cipSend,1000,DEBUG);
sendData(webpage,1000,DEBUG);
sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);

The php script:

 <?php

 $url="http://192.168.4.1/?cmd=SS,0,0,";
 $lines_string = file_get_contents($url);
 echo htmlspecialchars($lines_string);

?>

If i replace the url by:

$url=https://arduino.stackexchange.com

It works with php script,so what is the issue with the ESP8266 ?

To process the request by php, you must send valid HTTP response. The browser tolerates too much.

String webpage = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
webpage += "
Hello
";


How to calculate the needed voltage and current to supply for Arduino I have Arduino MEGA and I'm connecting to it 5 servomotors.

{ 3 TowerPro M995
Basic Information

Modulation:  Digital
Torque:  4.8V: 130.5 oz-in (9.40 kg-cm)
6.0V: 152.8 oz-in (11.00 kg-cm)

Speed:  4.8V: 0.20 sec/60°
6.0V: 0.16 sec/60°

Weight:  1.94 oz (55.0 g)
Dimensions:
Length:
1.60 in (40.7 mm)

Width:
0.78 in (19.7 mm)

Height:
1.69 in (42.9 mm)
Motor Type:  3-pole
Gear Type:  Metal

2 Towerpro M996R

Basic Information

Modulation:  Digital
Torque:  4.8V: 130.5 oz-in (9.40 kg-cm)
6.0V: 152.8 oz-in (11.00 kg-cm)

Speed:  4.8V: 0.19 sec/60°
6.0V: 0.15 sec/60°

Weight:  1.94 oz (55.0 g)
Dimensions:
Length:
1.60 in (40.7 mm)

Width:
0.78 in (19.7 mm)

Height:
1.69 in (42.9 mm)
Motor Type:  3-pole

}

So how can I calculate the voltage and current needed to supply this Arduino?

Voltage is simple - a device has a requirement and that is what you have to provide. In the case of the servos that is a range of voltages that it can use. So 5V is a good voltage.  The Arduino can take 5V if you feed it in to the 5V pin or the USB port, or 7-12V if you feed it in to the barrel jack.

The current you cannot calculate. You haven't provided enough information. The calculation, when you have the information, is quite simple: for all the devices on the same power supply add the currents requirements together. The supply has to be able to provide at least that amount of current.


Power 4 leds with max7219 and LedControl.h So this is my first arduino (or embedded for that matter) project. I am trying to power 4 leds with max7219. Max7219 seems easy to use, but for some reason after I upload the code, nothing happens. I've looked over my breadboard, and the connections seem right. My confusion arises from the fact that all the projects I have found on google use matrices for the leds. I am using 4 separate leds. Does this even matter?

Here is the code I use:

#include "LedControl.h"

LedControl ledControl = LedControl(12, 9, 10, 1);

void setup()
{
    //should be waking ledcontrol
    ledControl.shutdown(0, false);
    ledControl.setIntensity(0, 8);
}

void loop()
{
    ledControl.setLed(0, 0, 0, true);
}

No it shouldn't matter that you are using separate LEDs, but you will have to connect them in a way that is acceptable to the 7219, they will have to share either a common anode or cathode (can't remember which of the top of my head).

I find its always best to check the basics (Based on personal experience)

Have you got the LEDs the correct way around?
Are you using the correct voltage for everything?
Do the LEDs work when controlled directly by the Arduino, try "Blink"?
Have you tried changing the intensity?
Have you got the required resistors in?
Try inverting the index of the LEDs, i.e. led(x=0,y=0) might be wired (x=7,y=7)?

You loop() is not pausing, so all it is going to be doing is calling that one statement repeatedly.  Now that might not be a problem or the second call may be blocking the first from completing.  So I suggest add a delay for a second or so and see if that changes anything.  Also to prove you are running you Loop() code flash the LED on the board (pin13?).

Hope that helps.


Why my ISR is giving impossible values? I have a very simple ISR:

const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;
volatile uint32_t count = 0;
volatile uint32_t toggle = PATTERN_A;

// My ISR
void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

The idea is that the toggle variable takes values 0xFF00FF00 or 0xFF00FF00 depending on the evenness of the count variable. This is the only place where toggle is changed, but it's used (read-only) in the sketch.

I don't know why, but toggle gets all sort of random values during execution.

What is happening here?

The problem is a combination of several causes.

Assignments are not atomic

An atomic operation is something that is completely done or not. The opposite is some operation that can be disrupted while executing, leaving thing in a inconsistent state.

This is how the count++ works at machine level in Arduino:

void callback()
{
    count++;
  fa:   80 91 0a 02     lds r24, 0x020A
  fe:   90 91 0b 02     lds r25, 0x020B
 102:   a0 91 0c 02     lds r26, 0x020C
 106:   b0 91 0d 02     lds r27, 0x020D
 10a:   01 96           adiw    r24, 0x01   ; 1
 10c:   a1 1d           adc r26, r1
 10e:   b1 1d           adc r27, r1
 110:   80 93 0a 02     sts 0x020A, r24
 114:   90 93 0b 02     sts 0x020B, r25
 118:   a0 93 0c 02     sts 0x020C, r26
 11c:   b0 93 0d 02     sts 0x020D, r27

The first four instruction loads the four count bytes into four separate register, the laboriously increment it by one and then store it back in RAM.

Now, toggle is a variable of interest and you want to use it inside loop, like this:

void loop()
{
    uint32_t x = toggle;
    ...
}

And at machine level you get

    uint32_t x = toggle;
 414:   60 91 04 01     lds r22, 0x0104
 418:   70 91 05 01     lds r23, 0x0105
 41c:   80 91 06 01     lds r24, 0x0106
 420:   90 91 07 01     lds r25, 0x0107

Here we are simply copying the toggle variable into our x variable. As you can see, the copy takes four machine instructions to get completed.

Now, what happens if an interrupt comes while you are copying (or using) toggle?

An interrupt suspend the assignment, go to the ISR (callback in this case and change toggle value. Upon return, copying continues, mixing bytes from the old and new value.

You must use volatile

Any global variable used inside an ISR must be declared volatile. This is an hint to the compiler that the variable could change unexpectedly. Therefore, the volatile variable must be always read afresh, discarding any cached value.

Critical section

The rule for using values changed by ISR is simple:

Always copy the ISR's global variables to your own temporary variable.
Before coping, disable interrupts and reenable it after the copy is done. This prevent the ISR from executing while your are copy the values.

Demo

This little demo shows you all of this in action.

The sketch collect all the values from toggle (not disabling interrupts) during one minute and after that print a table showing what it got.

/*
 * This sketch show how to deal with variables shared between ISR and main thread.
 *
 * By Look Alterno 2018
 */

#include "TimerOne.h"

volatile uint32_t count = 0;
const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;

volatile uint32_t toggle = PATTERN_A;

#define MAX_CASES 16
struct {
    unsigned long value;
    int count;
} found[MAX_CASES];
int freeFound = 0;

#define PRINT_INTERVAL 60000L

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

    while(!Serial);

    Serial.println("");
    Serial.println("Test assignment under interrupts");
    Serial.println("");

    Serial.print("Value A=");
    Serial.println(PATTERN_A, HEX);
    Serial.print("Value B=");
    Serial.println(PATTERN_B, HEX);

    Timer1.initialize(500);
    Timer1.pwm(9, 512);
    Timer1.attachInterrupt(callback);

    pinMode(A0, INPUT);
    randomSeed(analogRead(A0));
}

void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

void loop()
{
  static unsigned long prev = 0;

  //  A random delay to simulate some real, variable work being done.
    delayMicroseconds(random(250));

  // This is the critical section.
//  noInterrupts();
    uint32_t x = toggle;
//  interrupts();

  // Now, let's see what value we got.
    if(x != PATTERN_A && x != PATTERN_B) {
        insert(x);
    }

  // Print values found
  unsigned long now = millis();
  if (now - prev > PRINT_INTERVAL) {
    printFound();
    prev = now;
  }
}

/*
 * Add a value to a table for counting.
 */
void insert(unsigned long x)
{
    int index = 0;

    while(index < freeFound && found[index].value != x) {
        index++;
    }

    if(index < MAX_CASES) {
        if(index == freeFound) {
            found[index].value = x;
            found[index].count = 1;
            freeFound++;
      Serial.print(freeFound);
      Serial.print(". Add=");
      Serial.println(x, HEX);
        } else {
            found[index].count++;
        }
    } else {
        Serial.print("*** Table overflow. value=");
        Serial.print(x, HEX);
        Serial.println(" ***");
    }
}

/*
 * Print the table of found values so far.
 */
void printFound() {
  Serial.println("");
  Serial.println("Values found");
  Serial.println("");
  Serial.println("Value - Count");
  for (int i=0; i < freeFound; i++) {
    Serial.print(found[i].value, HEX); Serial.print(" - "); Serial.println(found[i].count);
  }
}

If you uncomment noInterrupts and interrupts, every thing works just fine.

Other CPU

More powerful CPUs have atomic assignments, but following this practices makes your code portable across platforms, no matter what. Think of defensive programming


Esp8266 + Atmega328p as flash Being clear I'm not talking about How to flash ESP8266 using arduino.
I want to ask how can I use atmega328p as flash with esp8266 (instead of that 8 pin small chip on ESP-01) so that I can burn Webserver code on Atmega328p and it simply works with esp8266?

Thanks in advance.

It can't be done (also, why would you think that would ever be a good idea?!)

The 8 pin chip on the ESP-01 is a 512kB SPI flash that runs at (at least) 40MHz.  So to emulate that you would need:

More than 512kB of flash,
A slave SPI interface that can operate at a minimum of 40MHz, and
The knowledge, time and energy to write the firmware to emulate an SPI flash chip

The first two are certainly beyond an ATMega328P with 32kB flash and an 8MHz maximum speed SPI interface. The third is probably beyond you since you have to ask the question in the first place (which shows a certain lack of knowledge on what it is you are proposing).

There are plenty of examples for creating a web server using an ESP8266 using either the standard AT firmware or by directly programming the ESP8266's flash chip through the ESP8266's built-in UART bootloader.  Personally I find the use of AT firmware clumsy at best and prefer to always program my ESP8266's directly.  If you feel the need to also add an ATMega328P into the mix for some reason then the communication protocol that you use between them is entirely up to you.


Problem with action that should happen in loop(continuously) I’m using WeMos D1 R2 and latest Blynk library and app. I am also using Arduino IDE 1.6.13. I am trying to read a button from the app, which works fine, but i want to read it continuously. Through the Serial Monitor I can see that the board changes modes as it should. However, even if sensors read values when we get through the first “if” states, the values do not continue to show up in Serial Monitor. I believe that’s happening because it is not working as a loop. Also, the relays are not working(they start as open as they should, but their state never changes), as I believe program freezes at some point.

Here is the code:

//Start of program
#include <dht11.h>
#define BLYNK_PRINT Serial//
#include <ESP8266WiFi.h>
#include <Blynk.h>
#include <BlynkSimpleEsp8266.h>
#include <NewPing.h>
#include <SimpleTimer.h>

#define TRIGGER_PIN2 D4 // Arduino pin tied to trigger pin on the ultrasonic sensor 2.
#define ECHO_PIN2 D5     // Arduino pin tied to echo pin on the ultrasonic sensor 2.
#define MAX_DISTANCE2  23// Height of the Water Tank 2 (in centimeters).
#define DHT11_PIN D6

char auth[] = "****";
char ssid[] = "8888";
char pass[] = "psw";

int Relay1 = D1;
int Relay2 = D2;
int val2 = 0;
int tankwater1 = 0; //water in tank 1 in liters
int tankwater2 = 0; //water in tank 2 in liters
int fieldsize1 = 0; //size of field1 in m^2
int fieldsize2 = 0; //size of field2 in m^2
int sensor_pin = D7;
SimpleTimer timer;
//NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE1); // NewPing setup
of pins and maximum distance.
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2); // NewPing setup of
pins and maximum distance.

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT); //Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT); //Setup Relay pin as output pin
  //pinMode(led_pin, OUTPUT);
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
}

void loop()
{
  Blynk.run();
  timer.run();
}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8, 23 - val2); // virtualpin 8 distance
}

BLYNK_WRITE(V1) {
  int pinValue = param.asInt();

  if (pinValue == 0)
  {
    val2 = sonar2.convert_cm(sonar2.ping_median());
    Serial.println("Irrigation mode is active");
    Serial.println("Water level is at:");
    Serial.println(23 - val2);

    if (digitalRead(sensor_pin) == HIGH)
    {
      if (val2 <= 15) //Water level reaches the Top of the Tank2
      {
        digitalWrite(Relay2, HIGH); //Pump2 off
        delay(500);
      }
      else if (val2 > 15) // Water is empty on the Tank2
      {
        digitalWrite(Relay2, LOW); // Pump2 ON
        delay(500);
        //delay(86400000); one day delay. not suitable for experiment
      }
      else if (digitalRead(sensor_pin) == LOW)
      {
        digitalWrite(Relay1, LOW);
      }
    }
  }
  else {
    Serial.println("Fertilize mode is active. This does nothing now");
    //val3 = sonar2.convert_cm(sonar2.ping_median());
    //tankwater2 = (10-val3)*fieldsize2; //calculation of water in tank2
  }
}
//End of program

The BLYNK_WRITE(V1) function is only called when a Blynk app widget sends data to your hardware. It does not run in a loop. If you want something to run in a loop, put it in loop().

The WRITE aspect is from the point of view of the App, not of your hardware, so your hardware uses BLYNK_WRITE() to receive information from the app. And it's only called when the app chooses to send that information. For example, when a button in the Blynk smartphone app is pushed.


Maximum frequency of digital signal in Arduino Uno? As Arduino Uno has a 16 MHz oscillator but while running program it has less frequency because some of the processing power is used for running the program.
I have used the delay(1) but it is giving me around 500 Hz.

My questions:

Is there any way to achieve more than 500 Hz?
What would be the maximum frequency of digital signal for below program?

void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(13, LOW);
}

Yes, use the hardware timers.
You can achieve 8 MHz.

Example sketch which outputs 8 MHz on pin 9 on a Uno:

#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

If you change OCR1A you can get lower frequencies. If you change the prescaler you can get lower frequencies again.

See my page about timers for more details.


All four of my ESC motors stutters when I run it on my Arduino, how can this be fixed? I am creating a drone and when I run it with my arduino all 4 motors stutters.

This is the ESC and the motor i bought:

hobbyking.com/en_us/mt1806-brushless-combo-include-esc-5030cw-ccw.html

I put the 3 motor wires in the esc directly. (This is already presoldered by the company i bought it from). Then I have soldered bullets myself on the end of 2 connections of the ESC and then I enter them to my power distribution board:
hobbyking.com/en_us/hobby-king-quadcopter-power-distribution-board.html)!

After this I put jumper cables on the ESC cables (ground + signal, not the powercable). The signal I just use a regular jumper cable on each ESC and put it to the arduino board and when I use ground I use a jumper cable on the all the ground ESC wires and then I solder them together with another jumper cable and put that on the GND on the arduino uno.

Have I done a bad soldering job and is that the reason why the motors are stuttering? And if so is it the GND pins soldering or is the bullets I solder to the ESC and connect to the power distribution board? Or is it maybe something else? The three motor wires are all black meaning i have just randomly put them on the ESC. If I swap them around a bit might that solve it?

This is how the soldering looks:

This is how I solder different jumper cables together to one jumper cable and put it on the GND on the arduino uno. (I added a shrinking tube after that).

This is another one I did with the GND to see if the first one above was a bad soldering job:

Appreciate every help and tips :)

Push more current. You probably using the same 5V as the Arduino. This may cause "lag".

As I said in an other answer to one of your other questions, connect the battery's + directly to the + of that power distribution borad.


Passing pointers between setup and loop I'm new to the Arduino world. The last time i was programming microprocessors, was back with the Z80 in assembly language.

I am also teaching myself C++ and seems to be going quite well.

I have decided to write my own 'library' for driving 7 segment LED's. The reason for writing my own, rather then using an existing one is to aid with the learning process. I'm quite pleased to say it works ( it may not be the most efficient code)

The books I have on C++ are great, but i do find sometimes the explanation of concepts seem to get lost.

what I would like to know, how do you go about initialising an object class in setup() and using it in loop()? I have this sneaky suspicion that it involves creating the object on the heap, and passing a pointer to the object over somehow.

I could just initialise it once in loop(), and make my own continuous loop afterwards, but there are other things done between the and of a loop() and the beginning of the next loop() (things like timer interrupts).

I will post the code im using, but not the library unless asked to, as it is quite a few lines.

# include "Leddisplay.h"
void setup() {

    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };

    Leddisplay *pRightDigit = new Leddisplay(Digit);

}

void loop() {

    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();

}

^^  Obviously this does not compile  ^^

# include "Leddisplay.h"
void setup() {

}

void loop() {

    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    Leddisplay *pRightDigit = new Leddisplay(Digit);

    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();

    for (;;);   // or do.. while within which has other code to repeat
                // but wont allow anything to be executed between loop() iterations

}

^^  This does, and runs fine, but may not achieve what I want  ^^

I'm not sure if I have used the right wording, or even asked the right question.
Thank you for any help in advance.
Dave

What you have to understand is the concept of scope.

Everything (well, almost everything) in C and C++ is enclosed in { and }. Those define a scope, and everything defined within that scope is available to any other scopes defined within that scope.

You can also assume that the whole sketch is surrounded by { and }. This scope is called the global scope.  Anything defined within it is available anywhere in your sketch.

So by defining the object in the global scope it is available everywhere:

# include "Leddisplay.h"

Leddisplay *pRightDigit;

void setup() {
    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    pRightDigit = new Leddisplay(Digit);
}

void loop() {
    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();
}

However the use of new etc is discouraged in low-memory systems. Better is to statically define the object:

# include "Leddisplay.h"

const byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
Leddisplay pRightDigit(Digit);

void setup() {
}

void loop() {
    pRightDigit.setDigit(5);
    pRightDigit.displayDigit();
}

Note that, when statically defined like this, things in the constructor aren't guaranteed to be run at the right time. They should be moved into a .begin() function that you then call from setup():

# include "Leddisplay.h"

const byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
Leddisplay rightDigit(Digit);

void setup() {
    rightDigit.begin();
}

void loop() {
    rightDigit.setDigit(5);
    rightDigit.displayDigit();
}


Serial printf implementation Based on this approach I wanted to implement a function for formatted printing data to the serial monitor. I tried the code below:

int PIN = 12;

void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  sprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

void setup() {
  Serial.begin(9600);
  Serial.println("serial monitor has been set up");
  char buf0[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf0, "pin %i configured to output", PIN);
  Serial.println(buf0);
  _printf("pin %i configured to output", PIN);
  char buf1[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf1, "pin %i configured to output", PIN);
  Serial.println(buf1);
  _printf("pin %i configured to output", PIN);
  pinMode(PIN, OUTPUT);
  char buf2[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf2, "pin %i configured to output", PIN);
  Serial.println(buf2);
  _printf("pin %i configured to output", PIN);
  char buf3[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf3, "pin %i configured to output", PIN);
  Serial.println(buf3);
  _printf("pin %i configured to output", PIN);
}

void loop() { }

But it gives me some weird output:

serial monitor has been set up
pin 12 configured to output
pin 2263 configured to output
pin 12 configured to output
pin 2234 configured to output
pin 12 configured to output
pin 2205 configured to output
pin 12 configured to output
pin 2176 configured to output

What do 2263 and 2269 mean? Why does it happen only inside the function? What is my mistake and how can I fix it?

The problem with your code is that you are mixing the "normal" and "variadic" forms of the printf functions.

Any printf function starting with V takes a variadic argument list pointer as its last variable. Any printf function which doesn't start with V takes a variadic list of individual variables.

When calculating your buffer size from a list of variables in your main loop you are incorrectly using vsnprintf - you should be using snprintf since you aren't passing it a va_list, but individual variables. In your _printf function you are correctly using vsnprintf to calculate the length of the buffer, but then incorrectly using sprintf with a va_list instead of individual variables.

So your two forms should actually be re-written as:

// Inline version
char buf0[snprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
sprintf(buf0, "pin %i configured to output", PIN);
Serial.println(buf0);

and:

void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  vsprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

Remember: if you have a va_list then it goes with a v*printf function. If you have individual variables they go with a *printf function.


Pixy(CMUcam5) robot Distance code Can anyone help me with the code-ing to allow the robot to stop at a certain distance when the robot is approaching the tracked object. I am trying to implement it as a colour tracking wheel chair. For Example, the motorized wheelchair is able to track the colour of the shirt of the person infront is wearing and follow the person, and at the same time it is able to leave a distance between the person infront and the wheelchair to prevent collision.

the pixy robot : https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/overview

The code :https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code

Currently the code is only able to track the object till it reaches the object. But my objective is to let it chase the object, but at the same time, leaving a 1 metre distance
away from the object.

Please help me. Thank you

Try to play with this one:

int forwardSpeed = constrain(400 - (size/256), -100, 400);

By changing the value of 256 and 400, not at the same time though, you better use 2 potentiometer to change those values. That's a trial and error though, I hope this will give you an idea.


Error on sending AT+CWJAP_DEF commands to ESP8266 I am trying to send AT commands to ESP8266 to get connected with internet with the Wifi.

When I am sending AT and AT+RST command on serial monitor then I am getting OK and ready response which seems perfect.

Then I am sending AT+CWLAP to get list of available wifi networks which is also executing correctly.

AT+CWLAP

+CWLAP:(3,"Moto",-42,"a4:70:d6:7a:fa:6c",1,25,0)
+CWLAP:(4,"PRANJAL",-95,"1c:a5:32:3d:f5:c4",1,-16,0)
+CWLAP:(2,"VIHAN",-94,"c8:3a:35:2f:1d:81",1,-21,0)
+CWLAP:(3,"Tenda",-93,"c8:3a:35:20:a9:b1",9,-4,0)

OK

Then I sent AT+CWMODE? which is also perfect.

AT+CWMODE?

+CWMODE:1

OK

Now I am trying to connect ESP8266 with above listed Wifi with this command, it is sending an ERROR on serial monitor.

  AT+CWJAP_DEF="Moto","reset1234"

Error

⸮=IRe"Moto","reset1234"

ERROR

Can anyone suggest me what could be the reason of this issue ?at

Based on the gibberish echo, the possible causes are:

Insufficient power. You need a source that can supply up to 300mA which is about the max consumption for the module. A good-sized capacitor across the ESP power rails (10uF maybe) wouldn't hurt.
Baud rate is too high. If you're using an Arduino as 'middle-man' and talking to the ESP8266 through a SoftwareSerial port, you're likely to face this sort of issue if the baud rate is as high as 115200; SoftwareSerial is unreliable at such rates.


Programming an ATmega328P by holding it on an Uno's I was looking at this Uno clone, the Nanino and then happened to read this article on "Manhattan style" circuit design. Anyway, that got me thinking...

If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

It's easy enough to use a Uno to program a bootloader onto another chip. I describe this process here.

The idea of holding one chip on top of another is likely to fail for various reasons. Both chips will try to respond to the programming attempt at slightly different times, probably making them both fail to be programmed.

See my post about making a breadboard Arduino. It only takes a few wires to program the target chip.

However this isn't just "paralleling the pins" - it is using one chip to program another, in the way it is designed to do.


Interrupts Within Critical Statements I've redone a previous Arduino sketch I posted in which I was having trouble capturing encoder counts within critical statements, having no luck properly attaching and detaching interrupts.  I've studied various ISR sketches but haven't been able to produce anything that caters to my needs.
I now have a switch case in which a DC motor with CPR encoder correctly rotates back and forth between specified boundaries if it alone is in the void loop.  However, once enclosed within a critical statement (I want this action to occur only if a button is pressed), the DC motor continues to rotate only one direction.
I need assistance in where to properly attach and detach these interrupts and how to correctly pass the encoder value to the next action.  Below is what I've done so far and any help would greatly be appreciated.
#define enA 9
#define in1 6
#define in2 7

const int button1Pin = 8;

int button1State = 0;

volatile long temp, counter = 0;

long local_counter=counter;

enum {IdleState, ForwardState, BackwardState} State;

void setup() {

  Serial.begin(9600);

  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  Serial.begin (9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  attachInterrupt(0, ai0, RISING);
  attachInterrupt(1, ai1, RISING);

  pinMode(button1Pin, INPUT);

  State = IdleState;
}

void loop() {

  button1State = digitalRead(button1Pin);

   if( counter != temp ){
   Serial.print("counter = ");
   Serial.print (counter);
   Serial.print("     local counter = ");
   Serial.println(local_counter);
   temp = counter;
   }

   //if (button1State == HIGH) {

          switch (State) {

              case IdleState:
                halt ();

              if (counter<2000)
                State = ForwardState;
              break;

              case ForwardState:
                clockwise();

              if (counter>=2000)
                State = BackwardState;
              break;

              case BackwardState:
                counterclockwise();

              if (counter <=0)
                State = ForwardState;
              break;

          } // end switch
   //  }

}

void ai0() {
  if(digitalRead(3)==LOW) {
  counter++;
  }else{
  counter--;
  }
  }

void ai1() {
  if(digitalRead(2)==LOW) {
  counter--;
  }else{
  counter++;
  }
  }

void clockwise (){
    analogWrite(enA, 255);
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
  }

void counterclockwise () {
    analogWrite(enA, 255);
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
  }

void halt () {
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
}

An explanation of my setup is as follows:
My button is a tactile button on breadboard (connected to pin 8 of an Arduino Uno),  with 5V supply from Arduino. Pins 6 of the Arduino is connected input 1 of the L298N motor driver, pin 7 of Arduino connected to input 2 of the motor driver, and pin 9 of the Adruino connected to the enable of the motor driver.  Them motor driver is being supplied by an external 12V supply which is also power the 12V DC geared motor with encoder.  The encoder outputs are connected to pin 2 and 3 of the Arduino.

The way I see it, the state should go back to IdleState if the button is not pressed. Just putting the switch-case inside the if-statement will result in the motor continue rotating the way it was rotating when the button is released.
if (button1State == LOW ) {
  State = IdleState;
  counter=2000;
}
else if(button1State==HIGH && State==IdleState ) {
  counter = 0;
}

switch(State) {
  ...

Depending on what it is you want to do, you might want to add another state (say StoppedState), where the motors are halted, just like IdleState, but you don't get a state change if counter<2000. Then you don't have to change the counter variable.
if (button1State == LOW ) {
  State = StoppedState;
}
else if(button1State==HIGH && State==StoppedState ) {
  State = IdleState;
}

switch(State) {
  case StoppedState:
    halt ();
    break;
  case IdleState:
    ...

PS please indent the if statements inside you cases.


Can I use an accelerometer to measure the velocity of a car in a curve? I am making an application that is used to measure the velocity, it has an accelerometer that measures the component acceleration in the XYZ-axis. When the car is moving just straight the measurement is ok, as only linear components are involved.
My doubt came when the car is on a curve, I am not sure if the accelerometer can measure correctly in such situation or if it is necessary to apply a gyroscope to measure any missing component.
The code snippet for measure the total acceleration is shown below, I measure the acceleration in each axis and I remove the gravitational to finally calculate the velocity and the speed
    float AccTotal_X = ((AcX - grav_X)*9.81);
    float AccTotal_Y = ((AcY - grav_Y)*9.81);
    float AccTotal_Z = ((AcZ - grav_Z)*9.81);

    float Vx = vx_0 + AccTotal_X*dt;
    vx_0 = Vx;
    float Vy = vy_0 + AccTotal_Y*dt;
    vy_0 = Vy;
    float Vz = vz_0 + AccTotal_Z*dt;
    vz_0 = Vz;

    speed_dt = sqrt(pow(Vx,2)+pow(Vy,2)+pow(Vz,2))*3.6;

I found out the answer to the question in the following article SenSpeed: Sensing Driving Conditions to Estimate Vehicle Speed in Urban Environments
According to the article

When a vehicle makes a turn, it experiences a centripetal force, which
is related to its speed, angular speed and turning radius. Thus, by
utilizing the accelerometer and the gyroscope, we can derive the
tangential speed of a vehicle.

Therefore, just with the accelerometer is not possible to measure the velocity when an object is making a turn, it is necessary a gyroscope also.
The equation to measure the tangential velocity is:
v = Rω (1),
Where v is the tangential speed, R the radius of the curve and ω the angular speed.
As the centripetal acceleration is given by a = ω²R (2), reformulating (2) and substituting in (1), it is obtained:
v = a/ω (3).
Both a and ω are given by the accelerometer and the gyroscope respectively.


Recommendations For High Capacity Microcontrollers For a new project I'm working on, I'm turning an old Casio Personal Mini into a Speak & Spell (with possibly other functions). However, the speech library I plan on using is Talkie, and it takes up quite a bit of program space. I've been trying to look around for some microcontrollers I could use that have high program storage capacity, but I really don't know much about what I should look for, nor how to find ones that are compatible with the Arduino boot loader. Would any of you have any good suggestions? I'd probably need one with over 256KB of program storage.

In a comment, Juraj wrote:

the ATmega MCUs are similar so a port to Arduino Mega should be
possible

This seems indeed to be very much the case.
Looking at the source code of the library, it appears it uses
timer 2 for generating the PWM signal and timer 1 for
scheduling the samples. These timers are almost identical between the
ATmega328P of the Uno and the ATmega2560 used in the Arduino
Mega 2560. The only relevant difference between these boards, as
far as the library is concerned, is the output pin, which is the “OC2B”
pin of the microcontroller:

on the Uno, OC2B is digital pin 3
on the Mega, OC2B is digital pin 9

So my guess is that the library should work on the Mega with just this
tiny change:
--- a/Talkie/talkie.cpp
+++ b/Talkie/talkie.cpp
@@ -71,7 +71,7 @@ void Talkie::say(uint8_t* addr) {
        //
        // Enable the speech system whenever say() is called.

-       pinMode(3,OUTPUT);
+       pinMode(9,OUTPUT);
        // Timer 2 set up as a 62500Hz PWM.
        //
        // The PWM 'buzz' is well above human hearing range and is

Also, make sure you plug your headphones on pin 9 rather than
pin 3.
If you try this and it works, please report that either here or directly
to the author of the library. It should then be easy to modify the
library to support both boards out of the box.

Edit: If you download Talkie through the Arduino library manager,
you will get this version, which does supports the Arduino
Mega 2560.


7 segment display blinking I want to display the DHT22 temperature and humidity sensor in a 3 digit 7 segments display. It's always showing the  sensor value and after 2 or 3 sec the display turns off, and then the display turns on, and so on.
I need help to understand where is the mistake on the code to make the display always turned ON.

#include <SevSeg.h>
#include <EEPROM.h>
#include "DHT.h"
#define COMMON_ANODE 0
#define DHTPIN A0     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value
SevSeg sevseg;

void setup(){

byte numDigits = 3;
byte digitPins[] = {1,2,3};
byte segmentPins[] = {4,5,6,7,8,9,10,11};
sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
 dht.begin();
}

void loop(){
   temp= dht.readTemperature();

   sevseg.setNumber(temp,1);
   sevseg.refreshDisplay();
}

A good way to avoid display flicker is to only update the display when needed.  The display update is what causes it to flicker.  If you change your main loop as below, the display will only update when needed (when the current reading is different than the last reading).  It's probably also a good idea to only read the temperature every 2 seconds or so which can be controlled with a simple delay().

float temp, last_temp = 0;

void loop() {
    temp = dht.readTemperature();
    if (temp != last_temp)
    {
        sevseg.setNumber(temp,1);
        sevseg.refreshDisplay();
    }
    last_temp = temp;
    delay(2000);
}


Can I support all these sensors? I'm new to arduino's and am currently working on a project which requires a lot of different sensors. I was just wondering if its possible to use all the following sensors on a single Arduino Uno:

2 Separate Load sensors (i.e giving different readings) controlled with an load cell amplifier
a Gyro Sensor
an Accelerometer
and an ESC

If its not possible, could someone please tell me what hardware I would need to run all these sensors together. Thanks :).

Yes, it should work. The HX711 need two pins each (one for clock and one for shifting out the data). The MPU6050 seems to have an I2C interface, which needs two lines (SCL and SDA). And lastly an ESC uses a PWM pin.

All in all this needs 7 pins, way less than an Arduino UNO has.

Note that having enough pins doesn't mean, that you can usw all the sensors at the same time. You might habe to disable one for a short time to do something else.


How to keep warm arduino uno board with 12v dc supply I have an arduino uno board with ESP8266 module and i have done all connection using breadboard.

Now when i run arduino uno with USB cable for long time then its not getting hot ! but when i supply power with 12v dc adapter in black barrele then its getting too much hot (i cant touch with my fingure).

Now when i remove the ESP8266 module power and test it again with 12v dc power supply then its not getting hot !

So what is the problem with ESP8266 module ? Is my wiring creates heat ?

See Can I use arduino's 3.3 V output directly to esp8266?

From that page:

  The specs for the Uno say that it does not provide as much current on the 3.3V line as the specs for the ESP8266 requires. You will need to provide another regulator that can supply enough current.

Also, putting 12V into the barrel jack is making work for the on-board voltage regulator (located near the barrel jack) because it has to convert 12V to 5V (making heat in the process). You would be better off putting a lower voltage into the barrel jack, ideally around 7V (but not lower).

Alternatively, just power through the USB port as you have been, and plug the USB cable into a USB charger.

To summarize, both the 5V and 3.3V voltage regulators are probably working very hard, thus getting hot.


esp8266 garbage out only when using SoftwareSerial I'm trying to operate the esp8266. When I connect RX+TX pins to pins 1+2 on the Arduino, everything works fine. but when I'm trying to use software serial all hell breaks loose and the recieved data is garbadeged (It seems like everything is ok but I can't read the output data...
more interesting, the output is not consistent!

example:

#include <SoftwareSerial.h>
SoftwareSerial esp8266(11, 10); // RX, TX
void setup() {
    // put your setup code here, to run once:
    esp8266.begin(19200);
    Serial.begin(115200 );
}

void loop() {
    esp8266.write("AT\r\n");
    String buffer;
    Serial.print("SENDING AT...");
    for(uint64_t time = millis();(time+1000) > millis();)
       for(;esp8266.available();buffer+=(char)esp8266.read());
    buffer.replace("\r\n"," ");
    Serial.println("RESPONSE:" + buffer);
}

And the output:

I've tried changing the SerialMonitor baud rate, the input pins, but results are all the same.

I've recently changed the MCU(uno) to a different and even a different esp module from a different supplier,
I am still getting the same results! I can't be the first one to encounter such phenomena...

Try dropping the SoftwareSerial connection speed to 19200. Ie, esp8266.begin(19200). 115200 it is the absolute max the SoftwareSerial can theoretically handle.
Also if you are not using all the change interrupt pins on your MCU (Uno/Nano?) then use any 2 pins from 10, 11, 12 or 13 rather than 3, 2 // RX, TX.
Not sure about sendCommand function. If you just want to test the connection then it should be as simple as:

SoftwareSerial esp8266(10, 11); // RX, TX

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

    char buffer[50];
    esp8266.write("AT\r\n");
    esp8266.readBytes(buffer, sizeof(buffer));
    Serial.println(buffer);

...
}

Obviously once you need to open web pages and recieve responses then you will need a libary to handle IDP+ data. With a bit of coercion I got Adafruit_ESP8266.h working with SoftwareSerial.


Is there any way to catch the response of SIM800L after sending the at command? I am using sim 800l with arduino. I am successfully sending AT command from arduino, not in serial monitor but I am unable to catch the response after each successful command execution if its ok or not. I want to do that because, if there is an error in a certain command the next command will not be executed unless its successful. Can you tell me is there any way to do so?

for a polling serial read I use this method :
bool tSim8_sendCommand(uint8_t sim_cmd[])
{
    uint8_t simOK[2] = {0}, i=20;
    tSoftSerial1_write(sim_cmd);
    tSoftSerial1_write("\r\n");
    while (i--)
    {
        simOK[0] = simOK[1];
        simOK[1] = tSoftSerial1_readChar();
        if(simOK[0] == 'O' || simOK[1] =='K')
        {
            return true;
        }
    }
    return false;
}

the variable i i the while loop, is used just for retries, so the program doesn't get trapped in an infinite loop. the code is self-explanatory. the incoming characters are "pushed" into an array till the array reads "OK".
for a non-blocking one, it's a bit complicated as you have to define state-machines and concurret loops. here is a method I use for finding out if the last transmission was OK:
void tsim_phase_ok_routine(uint8_t inChar)
{
    if(tsim_aux_buff[0] == 'O' && tsim_aux_buff[1] =='K' && tsim_aux_buff[2] =='\r')
    {
        tsim_status_flag |= (1<<PHASE_OK);
        tsim_status_flag &=~(1<<PHASE_CON_ERR);
        return;
    }
    else
    {
        tsim_aux_buff[0] = tsim_aux_buff[1];
        tsim_aux_buff[1] = tsim_aux_buff[2];
        tsim_aux_buff[2] = inChar;
        err_timeout--;
    }
    if(!(tsim_status_flag & (1<<PHASE_OK)) && !err_timeout)
    {
        tsim_status_flag &=~(1<<PHASE_OK);
        tsim_status_flag |= (1<<PHASE_CON_ERR);
    }

}

I define "PHASES" to find out which phase is sim800 in. the whole function would be written in RX interrupt service routine and the input character would be fed to it.


How to make an arduino button to forget his past purpose? For my school project im making an arduino speedometer for a bicycle. I will be using a reed switch sensor to get the speed. There will also be an clock and a termometer, it will be on a 16x2 lcd screen. To get the speed I will need the user to type in his bike size, in zoll. I managed to let the user tap the button until his size and then double tap the button to confirm it. Alright, fine. Now I need the same button to FORGET his last purpose. Because I want to use the same button to change the screen between speed, clock and termometer. SPEED -> tap -> CLOCK -> tap -> TEMPERATURE -> tap -> SPEED ........

I hope you get the idea. After the user picks his size, if he keeps tapping the number it would just keep on growing. So, im trying to make the button forget, or make him go trough that loop only once.

Pick your size tap tap tap double tap, thank you. And stop! I want him to do that only once and never again. I will need the same principle when the user will adjust his clock, he will have to tap to set it, save the number but reset the buttons function.

#include <LiquidCrystal_I2C.h>
#include <LiquidCrystal.h>
LiquidCrystal_I2C lcd(0x27, 16,2);
#define buttonPin 7
int a = 16;
int b = 0;

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.print("RADGROESSE IN");
  lcd.setCursor(0, 1);
  lcd.print("ZOLL EINGEBEN");

   // Set button input pin
   pinMode(buttonPin, INPUT);
   digitalWrite(buttonPin, HIGH );
}
void loop() {
   int b = checkButton();
   if (b == 1) clickEvent();
   if (b == 2) doubleClickEvent();
}
void clickEvent() {

   lcd.setCursor(14, 1);
    lcd.print(a);
    delay(100);
    lcd.print(" ");
    delay(100);
    a++;
    delay(100);
    if(a >= 23){
      a = 16;
      }
}
void doubleClickEvent() {
      b = a - 1;
      Serial.println("Button was idle for one second or more");
      lcd.clear();
      lcd.print("ZOLL = ");
      lcd.setCursor(7, 0);
      lcd.print(b);

}

//=================================================
//  MULTI-CLICK:  One Button, Multiple Events

// Button timing variables
int debounce = 20;          // ms debounce period to prevent flickering when pressing or releasing the button
int DCgap = 420;            // max ms between clicks for a double click event
// Button variables
boolean buttonVal = HIGH;   // value read from button
boolean buttonLast = HIGH;  // buffered value of the button's previous state
boolean DCwaiting = false;  // whether we're waiting for a double click (down)
boolean DConUp = false;     // whether to register a double click on next release, or whether to wait and click
boolean singleOK = true;    // whether it's OK to do a single click
long downTime = -1;         // time the button was pressed down
long upTime = -1;           // time the button was released

int checkButton() {
   int event = 0;
   buttonVal = digitalRead(buttonPin);
   // Button pressed down
   if (buttonVal == LOW && buttonLast == HIGH && (millis() - upTime) > debounce)
   {
       downTime = millis();
       singleOK = true;
       if ((millis()-upTime) < DCgap && DConUp == false && DCwaiting == true)  DConUp = true;
       else  DConUp = false;
       DCwaiting = false;
   }
   // Button released
   else if (buttonVal == HIGH && buttonLast == LOW && (millis() - downTime) > debounce)
   {
           upTime = millis();
           if (DConUp == false) DCwaiting = true;
           else
           {
               event = 2;
               DConUp = false;
               DCwaiting = false;
               singleOK = false;
           }
   }
   // Test for normal click event: DCgap expired
   if ( buttonVal == HIGH && (millis()-upTime) >= DCgap && DCwaiting == true && DConUp == false && singleOK == true && event != 2)
   {
       event = 1;
       DCwaiting = false;
   }

   buttonLast = buttonVal;
   return event;
}

Thank you! I would really appreciate it!

What you likely need is a state machine. The behavior of the actions depends on the state the program is currently in.

In your case, the state machine might look like this:

What does it mean?

black circle: this is where the system powers on
rectangle: a state
arrow: a transition from one state to another
green text: action

For the problematic double click action, you can see:

it changes the state from "set size" to "speed"
in all other cases, it does not change the state (actually it changes the state to the same state)

I always recommend drawing the state machine before implementing it. It makes mistakes much more obvious.

There are several ways to implement it. The easiest one being a switch/case. More advanced implementations may use object orientation. When using switch/case, I prefer to have one method per state, like so:

void loop()
{
    switch(state):
        case setsize:
             setsize();
             break;
        case speed:
             speed();
             break;
        ...
}

If you know about function pointers, it gets even easier:

enum State {
  setsize = 0,
  speed,
  clock,
  temperature
};

State state;

void setup() {
  state = State::setsize;
}

typedef void (* functionPointer) ();
functionPointer process[] = {do_setsize, do_speed, do_clock, do_temperature};
void loop() {
  process[state]();
}

void do_setsize()
{
  state = State::speed;
}
void do_speed()
{
  state = State::clock;
}
void do_temperature()
{
  state = State::speed;
}
void do_clock()
{
  state = State::temperature;
}