Driving single-character alphanumeric (16-segment) displays I would like to drive three sixteen-segment displays (https://www.sparkfun.com/products/retired/9934) using an Arduino Micro. These displays would output an alphabetic character that a user would scroll through using rotary encoders, and constitute a subsystem of a larger project where the user enters a "combination" made from the three letters to "unlock" functionality in the larger device.

The best option, if it could be called that, is this retired product from SparkFun: https://www.sparkfun.com/products/retired/10103 that would allow me to drive the displays without a huge wiring mess, and spares me a lot of pins on the Micro to use on the rotary encoder. Unfortunately, the product is retired because the A6282 IC it was based on reached end of life, so even the schematics available on the product page aren't much use to me.

I am aware that four-character 16-segment displays are available, but for "aesthetic" reasons I am constraining myself to using single-character 16-segment displays. I do wonder how possible it would be to run three or four individual 16-seg displays from one of those LCD backpacks, but I don't think that would be trivial to do (I'd need to, probably, fabricate some sort of printed circuit board that spaced each display as far out as I need them to be, hook the pins of each display into a key matrix, and then at that point it'd be substantially easier to just get a MAX6954 (https://www.maximintegrated.com/en/app-notes/index.mvp/id/3212) and try to figure that out). It would be very clumsy to prototype.

So, I'm looking for a solid method of prototyping this "combination entry" subsystem and its 16 segment displays without needing to put each dial and alphanumeric display on its own AVR or something.

If you need additional IO lines, a typical “LCD backpack” supplies at most eight additional lines of IO; 16-channel TLC59116 LED Driver Board as mentioned by Majenko would be more elegant than using several backpacks.

You might try an approach like the following to see if it works well enough.

Use 16 IO lines to pull down 16 segment lines.  Use three IO lines to drive three digit-select PNP or PFET transistors for digit multiplexing.  Use pin-change interrupts on two IO lines to read rotary encoder (RE) data.  Use one input to read the RE pushbutton.  Use one IO line to notify the bigger unit of success.  Total 23 IO lines.

In operation, your code will need to implement a state machine that frequently refreshes the multiplexed digits while keeping track of digit values, selected digit, etc.  Each time you click the RE have your sketch go on to the next digit.  To tell the user which digit is working, blink the selected digit a couple of times after the RE press.  Each time that selection wraps around to the first digit, check if the combination is correct.

If you feel it's necessary to have three different digit-setting knobs, vs clicking through to each digit, you could use one less IO line by using three pots instead of one RE.  The pots would be read in analog.  A6 and A7, IIRC not usable for output lines, could be used as analog inputs for two of the pots.


Arduino with 12 bit DAC (MCP4725) Not Working I have an Arduino Mega AT2560 and need to have real DAC. I purchased the Sparkfun 12 bit DAC, however I don't think it is working properly.

I am using the Arduino wire library to communicate with the DAC. When I write 0, I am expecting to see 0v from the DAC's OUT pin. However, I see some seemingly random constant voltage. In reverse, when I write 4095 to the DAC I see the same voltage as when I write 0. I expected to see 5v.

Can someone verify that I hooked it up correctly?
Can someone verify the code I am using?

#include <stdint.h>
#include <stdio.h>
#include <Wire.h>

#define MCP4725_ADDR 0x60 // [0000 0110]
/*
* 12 Bit DAC MCP4725 gives a range of 4096 possible values.
*
*/
void setup() {
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MCP4725_ADDR);
  Wire.write(64);            // cmd to update the DAC [0100 0000]
  Wire.write(4095 >> 4);        // the 8 most significant bits...
  Wire.write((4095 & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();
}

you want to make sure that there are pull-ups on the SCL/SDA lines;
you want to make sure that the address is correct. some routines use 7-bit notation for that, and others use 8-bit notation for that. end of the day, you want the transmission to be 0xc0 | (A2:A1:A0:R/W). so check the write.write() and see what it expects. I suspect that it expects 0xCx, rather than 0x6x.

having said that, here is your code running on an uno, with the dac configured as per sparkfun spec.

so I think it is fair to say that the code is ok but something happened on your end that prevented it from working.


Button box wiring sanity check I am building a flight sim button box and I would like someone to please check my proposed wiring diagram.
I will be using 12 buttons, 4 rotary encoders, each also with a push button and 4 (on)-off-(on) toggle switches as well as one additional toggle switch to use as a modifier for the buttons.

Any comments or suggestions appreciated.

Edited to suggest driving the outputs low.
To use a multiplexed grid of switches like that you'll need to write code that sets all the columns to open, sets all the input rows to INPUT_PULLUP, drives one column at a time low and scans the rows for low output to figure out which buttons are pressed. (You could reverse the rows and columns, or add external pull down resistors and pull the rows/columns high rather than grounding them, but you get the idea. You'll need to write code to scan the grid of buttons in nested for loops.)


Voltage divider arduino 5v and Ethernet board 3.3 I have an Arduino Nano 5v module and I just received an Ethernet Interface Board - ENC28J60 that runs at 3.3v. (https://www.sparkfun.com/products/765)

Might sound a dumb question but I will power the Ethernet board from a Voltage regulator that can deliver 3.3v but then I have to connect via SPI to my Arduino controller. I guess I can't connect my Arduino pins directly to the Ethernet board right? because HIGH in the pin will be 5v instead of 3.3v.

  Do I need to add a Voltage divider for those pins connections? And in case I need to what resistance values are the right ones to use?

Thanks

From experience with 3.3v ESP8266es with 5v Arduinos, only the signals to the 3.3v device need to be converted (5v high -> 3.3v high). A 3.3v level to the Arduino is high enough for 5v logic to still read it as HIGH. That means you can get away with just a voltage divider on each of the Arduino -> ENC28J60 pins.


Problem with power supply ws2812b Arduino 5v vs 12v I have an Arduino wired to ws2812b with 10 100uF capacitors and 2 1000ohm resistors(picture). When I'm plugging 5v power supply everything is working when I plug 9v battery everything is fine but when I'm plugging 12v power supply in one moment leds stops.(NeoPixel standardtest example. How I can power the ws2812b by 12v

The regulator on an Arduino is likely analog.  On this Arduino Uno the regulator is an analog NCP1117ST50T3G as seen in this schematic.  On page 2 of the NCP1117ST50T3G spcification it is stated:

  Internal thermal shutdown protection limits the die temperature to
  approximately 175°C. Proper heatsinking is required to prevent
  activation.

Being an analog power regulator, the difference between the input voltage and the regulated output voltage eventually turns into heat.  This may explain why a 9 volt source may work (drop is only 9V - 5V = 4V) while a 12 volt source may not work (drop is 12V - 5V = 7V).

Consider using a 5 volt power source avoiding the Arduino analog power regulator.  Or, if the only source is 12 volts (for example an automobile), consider using an external switching or buck power supply to convert the 12 volt down to 5 volts and again avoiding the Arduino analog power regulator.  Lastly, it should be possible to still power the Arduino with 12 volts and use its internal power regulator to only power the Arduino. Then independently power the LED strip using an external power regulator.  This last option will likely have the benefit of eliminating the capacitor bank seen in the question and associated components.


Arduino connection to brainwave analyzing module I want to connect a TGAM module (detecting brainwaves) to an Arduino Uno. I know little of electronics, can someone advise me? To which pin of the Arduino should I connect the TGAM? How to get the right electrical supply from the Arduino to the TGAM? Here is data about the TGAM module: http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf

The R pin on the TGAM module is providing digital data as an asynchronous serial stream of bytes: http://developer.neurosky.com/docs/doku.php?id=thinkgear_communications_protocol

As per the datasheet you provided, it is quite straight forward.
It can be connected to RX (pin 0) and TX (pin 0) pins of the Arduino Uno.
But, the pins have to be crossed;

Arduino RX (0) <> TGAM T (TX)

Arduino TX (1) <> TGAM R (RX)

Arduino 3.3V <> TGAM + (VCC)

Arduino GND <> TGAM - (GND)

Good luck.


H_Bridge with PWM gets too hot I'd like to use an H-Bridge  AND send PWM signal.
I've used this schematics: http://itp.nyu.edu/physcomp/Labs/DCMotorControl
and use the PWM signal inside the enablePin. But the H_Bridge is getting very hot.
Am I wrong?
EDIT:
I'm using and H-Bridge but not for driving a motor, instead I'm driving a peltier cell (like this one: https://www.sparkfun.com/products/10080). What I'm trying to achieve is to have a fixed peltier cell and to have in the same side sometimes hot, sometimes cold. This behaviour is done by switching the positive and negative with the H-Bridge. To control how much cold and how much hot I'm using PWM.

Short answer: You're drawing too much current through the H-bridge.

Longer answer: The H-bridge is most efficient when fully on and that's when the chip gets rated for the maximum current. The rating also, probably, states that a heat sink is attached to the chip. Using PWM to slow down the motor decreases the current going through the bridge, but also incurs inefficiencies because the transistors / MOSFETs are partially on, and thus acting somewhat as resistors. This inefficiency manifests as heat.

So you have several options.
1. Choose a smaller motor.  This reduces the overall current needed.  Only feasible if this is a learning project.
2. Choose a beefier H-bridge.  This increases the ratings of the bridge to handle current for this motor.
3. Add a heat-sink to the existing bridge.  This will help dissipate the heat generated.

Generally I'd recommend both 2 and 3, but it depends on your ultimate goal of the project.


Control 5V from ESP8266 Wemos D1 mini I am making a simple heater with the help of ESP8266 wemos d1 mini. Heaters will use 12V DC power suply and ESP8266 must turn the heater on and off with the help of 5V DC relax. I want to avoid the use of anything else then ESP8366 and relay. I will need 2 such relays. So the question is, can i control 5V output on ESP8266 ? Or do i need to find a 3V DC relay and use that ? If the latter is the case, can i get some ebay link to 3V DC relay ?

Voltage is only part of what a relay uses.  Check the current requirements for the relay coil/input as well.

For example the common result for "3V relay arduino" will produce results for relay MODULEs that contain something akin to a SRD-03VDC-SL-C relay (labeled on the relay itself).  Spec for the RELAY (separate search by relay part no) yields a data sheet that says the coil resistance is 25 ohms for a 3V and would use 120 mA at that voltage (25 Ohm * .120A = 3).  Note if the same coil were run on 5V it would draw 200 mA (25 Ohm * .200A = 5V).

120 mA is bloody high to be coming from a logic pin which is why the MODULE has more than just the relay.  What the MODULE likely contains is an additional gate device that takes less current that then supplies the relay (with 120mA) from another port.

You might also be looking at a solid state relay that uses less input current but generally has some slight leakage when "Off"


Initialize and read from a PROGMEM array of pointers to PROGMEM arrays I'm working on a project for the arduino uno for which I need multiple constant arrays of bytes. Such an array is initialized like so:

const byte charR[] PROGMEM = {
  B01111111,//top half
  B01111111,
  B01000100,
  B01000110,
  B01101111,
  B00111001,
  B00000000,
  B01111000,//bottom half
  B01111000,
  B00000000,
  B00000000,
  B01111000,
  B01111000,
  B00000000
};

This array represents the capital letter R. I read the nth byte of this array like so:

nth_byte = pgm_read_word(charR+n);

This is all fine and good so far, but now I need to take it a step further. I need to create the array message[]. I need to use message[] to read byte arrays in a certain sequence. For instance:

message[] = {
  charR,
  chare,
  charp,
  charl,
  chary,
  charspace,
  charp,
  charl,
  chare,
  chara,
  chars,
  chare
};

Each entry in message[] refers to a byte array that represents a character. Notice how multiples appear. This is kind of like a 2-D array, but I want to save progmem by only defining each character once.

How do I properly initialize message[]? Will I need to use pointers for this? How do I properly get the array size or yth byte of the xth entry in message[]?

const byte* const message[] PROGMEM =

to use an item, load it in RAM

strcpy_P(buffer, (byte*)pgm_read_word(&(message[i])));

source Arduino reference - PROGMEM


analog read only once a time I was working on a school project in where i need to analog read form A0 and test if my value is bigger than some boundary (500 for example) to return 0 or 1
well with a simple code in an infinity loop
this will keep returning 0000000 and 1111111 for infinity
but need 1 only once when my analog value passes from 900 to 300 for example and I dont need once when It stays at 300.
and the same problem for 0 : I need 0 only once when it passes from 300 to 900 and not 0 from staying at 900
thanks for help in advance

Store the current read value AND the previous value and check if a border has been crossed.

E.g.

if Previous value < 500 AND current value >= 500
   Going from 0 to 1 -> return/send 1
else if Previous value >= 500 AND current value < 500
   Going from 1 to 0 -> return/send 0

However, to make it more complicated, you might have debouncing effects, e.g. what if the value moves for some time around 500 to go to 200... It will still result in possibly many 0 and 1 boundary changes.

You can fix this easily by using two different value: by checking going lower < 490 and going higher > 510 (or any other appropriate value. Or use a debounce mechanism where it should be below or above the 500 value for a minimum (but short) amount of time.


Audio Frequency White Noise generation using Arduino Mini Pro For DIY, how to program Arduino Mini Pro to act as an Audio Frequency White Noise generator?

Presumably,

a) using one Digital Output pin

b) feed to a simple passive RC low pass filter to reduce out of band signal

c) feed to a simple class-D IC chip audio amplifier and speaker

d) since it is DIY and noise, lo-fi (not hi-fi) is good enough.

Specific questions,

a) How to program?

b) Wonder if it is better to use to chip act a Pulse Width Modulated 'digital to analogue converter'?

c) How to calculate value for RC filter (assume amplifier has high input impedance)?

Many years ago, I have programmed a hardware sound generator chip as part of a game machine. It has two registers for amplitude and 'frequency' control (band of 'white' noise). It worked very well. I once looked at the output using oscilloscope and it was square wave. I believe that it works, basically, using the above principles. Since I do not have the chip now, I cannot verify it. Now, I would like to duplicate its function using Arduino in software.

I don't know that you need all that - just an Arduino and a piezo speaker and a pot if you want to play with the volume.
void generateNoise() {
    unsigned long int newr;
    unsigned char lobit;
    unsigned char b31, b29, b25, b24;
    b31 = (reg & (1L << 31)) >> 31;
    b29 = (reg & (1L << 29)) >> 29;
    b25 = (reg & (1L << 25)) >> 25;
    b24 = (reg & (1L << 24)) >> 24;
    lobit = b31 ^ b29 ^ b25 ^ b24;
    newr = (reg << 1) | lobit;
    reg = newr;
    digitalWrite (speakerPin, reg & 1);
    delayMicroseconds (50);  // Changing this value changes the frequency.
}


avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00 So I try to compile and upload a simple code such as the Basic Blink.
I have not connected it to pin 0 or pin 1.

There is an LED with the "L" label on the card that works. So I guess not the chip is damaged?

I have selected the correct model which is Arduino Uno / Genuino. I've checked the drivers several times now, even reinstalled Arduino Software twice and tried on 2 different computers.

5V works with ground, I can get the LED to light up. But I cannot compile / upload code.

Error MSG: avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
(this message repeats 10 times with attempts)

I read something about bootloader, but I have no idea how to do this / what it is. I do not have the right components for bootloading I guess.

Also the COM is correct. I've tried using all the listed COMs without any result. Is this a hardware issue? Is my chip grilled or something?

You should re-burn the bootloader. If you have another uno, you can burn bootloader here


Arduino due - Getting 0xFF (garbage) from serial I am developing application with serial communication with arduino due.

Like this:

while(1)
{
  if(Serial2.available() > 0){
  byte l_byData = Serial2.read ();
  Serial.println(l_byData,HEX);
  }
}

But I am getting "0xFF" from serial very frequently.

I am using Arduino 1.6.6 IDE.

Can anyone help on this?

Check baud rate, voltage levels. Better check your signals with a oscilloscope or at least check it with a serial dongle like this https://www.sparkfun.com/products/11814


How to multitask with interrupts on Arduino? I am trying to build a cashless RFID based water dispensing unit. I am using Arduino mega 2560, PN532, relay, flow sensor. Here is the flow of the program in I2C mode; I have two functions, one to scan the card and the other for the flow sensor. As soon as the RFID card is placed on the NFC module, data stored in the card (i.e, date of expiry and balance amount) is obtained and is checked for validity. If the card is valid, then the relay is turned on. A flow sensor measures the quantity of water dispensed. As soon as the limit of 1000 ml is reached, the relay is turned off. The whole process happens serially, when the card scanning is complete, it waits for the entire 1000 ml of water to be dispensed. What I want to achieve is after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin. If the first relay is busy, second relay has to be assigned to it. Can I achieve this using Arduino Mega? How do I manipulate the atmega to perform all these tasks at once?

There is no real multitask on Arduinos. The Arduino can only do one thing at a time.

But, you can do things sequentially, one after another, so fast, that a human will think, that it happens simultaneously. This involves a non-blocking coding style, which needs no interrupts

Every delay in your code (at least the long onces) need to be removed. if you want to do timed things, you should use the coding principle from the BlinkWithoutDelay example, that comes with the Arduino IDE.
Also no function should wait for something to happen. Think of a function, that waits for a command from the serial interface. Blocking code would wait indefinitely, until a command was received, preventing any other code from execute. Instead the function could exit fast, when there is currently no command to process, leaving time for the other code to execute.

The whole principle relies on the loop() function executing very fast, so that your code can still be reactive. This works for most of the situations. Only sometimes you need to react that fast, that you need interrupts. Your usecase doesn't seem to belong to the interrupt needed faction.


How to read analog pins from a second Arduino I've run out of analog pins on Arduino Uno and don't have time to order new parts. I've heard you can connect two Arduinos and I have access to another UNO. If I did that, could I read the analog pins of the second Uno on the first one?

I'm planning to control 7 servos with separate potentiometers.

Yes that is possible, you can even use as many Arduino's as you want and send the information to one 'master' Arduino to process the data.

What you need is a way to communicate between them. Depending on distance, speed and reliability, you can chose for Serial, I2C, SPI or more 'exotic' solutions like CAN(bus), RS485 or even wireless methods (with nRF modules).

Some have a simple protocol, for others you might have to make it yourself.

Also think of the processing, you want to do the processing on the main device, or to process as much as possible on the 'slave' Arduinos and send it to the main device.

(Btw, I talk about Master/Slaves), these are not official terms, but meant as example. For example, with CAN, you can send message from any Arduino to any other. With Serial, you can send from 1 Arduino to 1 other.

If you have 2 Arduino's, probably Serial is the easiest.


Is my Arduino UNO fried? The title sums it all up. While testing  the new proximity detector I bought off of Amazon, a spark flew from some random area and my Arduino's On LED went off while its Loop LED stayed in a dim state. I am here to ask you guys if this basically counts my Arduino as fried and that I need a new one, or if I should wait and see if it works again, being that I wrote this 5 minutes after the thing happened.

Thanks in advance,

afroraydude

It's hard to tell without further testing. Do the following:

Remove the Uno from the faulty circuit, making sure you remove all the wiring from the Arduino board.
Plug the Uno into the USB port. Does the ON LED light up? Does the built-in LED on D13 blink three times? (this should happen if you had the optiboot bootloader)
Remove the USB cable and plug the Uno to a 9V source through the barrel power connector. Do the same test above.
Can you upload the Blink sketch? If you can, does it make D13 LED blink once a second?

Report your findings by updating your question.


How many total digital pin outs does the Arduino Yun have I have read the details on the products page for Arduino Yun but I have also read, on a Arduino forum, that there are only 18 digital pins because of Tx, and Rx. Is this true? I am not worried about the PWM, or analog capabilities of the pins, just purely digital.

According to the official specification, it has 20 digital IO pins which can be used with digitalRead() and digitalWrite() etc.. As is typical on Arduino boards though, pins 0 and 1 also act as serial Rx and Tx (respectively).

You can program it to use them for either purpose.

The information you read might be referring to problems with uploading though. If you have something physically connected to pin 0 and/or 1, then you may have to disconnect it while you do an upload, otherwise it can interfere with the communication between your computer and the microcontroller.

If you're doing a lot of tinkering, then sometimes it's simply easier to avoid using pins 0 and 1 altogether, meaning you'd only have 18 IO pins left.


Sending string over serial to nodejs app. Why does it get chunked? I'm sending a string from my sketch over Serial port as follows:

Serial.println(F("Found ILI9341 LCD driver"));

On the other side, I have a nodejs app using the serialport npm module, with something like this:

var SerialPort = require('serialport')
var serialPort = new SerialPort('/dev/ttyACM1', {
  baudrate: 9600
})

// it opens the connection and register an event 'data'
serialPort.on('open', function () {
  console.log('Communication is on!')
})

// when your app receives data, this event is fired
// so you can capture the data and do what you need
serialPort.on('data', function (data) {
  console.log('data received: ' + data)
})

Communication works, but on nodejs side I get the output chunked, as if it had line breaks, like this:

Communication is on!
data received: Pa
data received: int!
data received:

data received: Fou
data received: nd I
data received: LI93
data received: 41 L
data received: CD d
data received: rive
data received: r

Why does this happen?

It seems I needed to add a parser to SerialPort nodejs module, in order to specify how the input should be treated.

I changed my code to this:

var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline

var serialPort = new SerialPort('/dev/ttyACM0', {
  baudrate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
  console.log('data received: ' + data)
})

serialPort.on('open', function () {
  console.log('Communication is on!')
})

Basically, I'm specifying a Readline parser, which matches with the Serial.println function calls on my arduino sketch. Now the console output works as expected:

Communication is on!
data received: Found ILI9341 LCD driver


MEGA I2C and interrupts on 0,1 Looking at the pinout for the Arduino MEGA:

I see that Pins 20 and 21 can be both SDA and SCL or Interrupts 0 and 1.

If I'm using an Adafruit I2C 16x2 RGB LCD Shield connected to the SDA and SCL pins by the USB Jack, is there anything I can do in my code to still use INT0 and INT1 off Pins 20 and 21 for a different purpose?

No, there is nothing you can do.

Both the SCL pins and both the SDA pins are physically connected together by copper tracks. They are in effect the same pin. If you use I2C you can't use INT0 or INT1. You have INT2 and INT3 though (pins 18 and 19), as well as Pin Change Interrupts on a large number of other pins.


POWER_MODE_IDLE wake on any input change? I want to be able to put an Arduino to "sleep" but I want it to immediately resume if any panel tactile buttons are pressed.

The purpose is to try to minimize any digital noise in an nearby high gain analog circuit.

My guess at this point is that I want to put the Arduino into POWER_MODE_IDLE but it is less clear to me the best way to wake up.

How can I instantly wake up from POWER_MODE_ILDE if any input changes? I don't want to have to hold down a button or even use a specific input. Is there a "catch-all" interrupt that will react immedately to a change on any or on a large set of inputs?

As I mention on my page about interrupts you can use pin-change interrupts on the Atmega328P to wake from the deepest sleep mode (SLEEP_MODE_PWR_DOWN).

Example code:

#include <avr/sleep.h>

const byte LEDLOOP = 8;
const byte LEDWAKE = 9;

ISR (PCINT1_vect)
 {
 // handle pin change interrupt for A0 to A5 here

 // toggle LED
 digitalWrite (LEDWAKE, !digitalRead (LEDWAKE));
 }  // end of PCINT1_vect

void setup ()
  {
  pinMode (LEDWAKE, OUTPUT);
  pinMode (LEDLOOP, OUTPUT);
  digitalWrite (A0, HIGH);  // enable pull-up

  // pin change interrupt
  PCMSK1 |= bit (PCINT8);  // want pin A0
  PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE1);   // enable pin change interrupts for A0 to A5

  }  // end of setup

void loop ()
{

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_mode ();

  // flash to indicate we got out of sleep
  digitalWrite (LEDLOOP, HIGH);
  delay (100);
  digitalWrite (LEDLOOP, LOW);
  delay (100);

  } // end of loop

This has the advantage of consuming very little power while asleep, and also waking on any pin (of an Atmega328P).

Running on 5V at 25°C you should only consume around 150 nA of current while asleep (on a "bare bones" board without USB chip, voltage regulator or power LEDs).

Other sleep modes may use more power but wake more quickly.


AC Motor speed control using SSR? I want to control speed of an AC Motor using phase cutting..
Well, I already have zero cross detector and SSR but don't know how to program Arduino to phase cutting using SSR..
And to connect the motor to SSR, do I need some protective circuit or not? Thanks!

First of all no protective circuit is needed in order to connect an arduino with an SSR. SSR input is isolated from the load.
Now answering your question you better go with an inverter, forget the SSR, and let arduino control the inverter. Using DOs from an arduino you can command the inverter to start/stop the motor or change the motor direction. Using an AO e.g provided by a DAC like MCP4921 you can control the motor RPM, too. There are a lot of inverters available for different loads and also different controls (Manual, Digital/Analog, Serial)


Convert Hex to Decimal from signed 2's complement I am reading data from a meter over dlms protocol and I am getting hex values from there. I want to convert that hex string to signed decimal value. For example - ff9d denotes a value of -99 [reference].
My hex to decimal code is:
unsigned int hexToDec(String hexString)
{
  unsigned int decValue = 0;
  int nextInt;

  for (int i = 0; i < hexString.length(); i++)
  {
    nextInt = int(hexString.charAt(i));
    if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
    if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
    if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
    nextInt = constrain(nextInt, 0, 15);
    decValue = (decValue * 16) + nextInt;
  }
  return decValue;
}

Can anyone please help me how to do it in Arduino IDE?

For example – ff9d denotes a value of -99

The function you wrote returns an unsigned integer which, being
unsigned, cannot be negative. The simple fix is to declare it as
int hexToDec(String hexString)

That should be enough to get it working as expected. Note that the local
variable decValue still has to be unsigned, otherwise you would get a
signed overflow, which is undefined behavoir (i.e. “forbidden”) in
C++. Returning an unsigned number from a function that is supposed to
return a signed number is perfectly fine: you get an implicit conversion
which is guaranteed to do the right thing.
Now, if I may provide some more feedback about this function:

Use, if you can, plain C strings (char *) instead of String
objects, as the latter are not very friendly to your Arduino's memory.
Use fixed-length integers (uint16_t if your protocol dictates 16-bit
integers) instead of the generic int, otherwise your code will fail
if you move to a 32-bit platform, such as an ARM-powered Arduino.
Use character literals ('0' instead of 48) instead of hard-coding
ASCII code points, as that makes the code more readable.
Use a simple subtraction (nextInt - '0') instead of the quite
expensive map() function.

Here is my take at it. Note that it has a “classic C” accent you do not
need to replicate. You may prefer using indices to crawl the string.
int16_t hex2int(const char *hex)
{
    uint16_t value;  // unsigned to avoid signed overflow
    for (value = 0; *hex; hex++) {
        value <<= 4;
        if (*hex >= '0' && *hex <= '9')
            value |= *hex - '0';
        else if (*hex >= 'A' && *hex <= 'F')
            value |= *hex - 'A' + 10;
        else if (*hex >= 'a' && *hex <= 'f')
            value |= *hex - 'a' + 10;
        else
            break;  // stop at first non-hex digit
    }
    return value;
}

Example usage:
Serial.println(hex2int("ff9d"));  // prints "-99"

Edit: As revealed by the comments, the whole question is an XY
problem. You are asking help about your misguided solution rather
than your actual problem. The data you have is not hex: it's binary.
You have a 16-bit signed integer stored in a byte array, most
significant byte first. You figured out you can convert that to an
integer by converting it first to a string representation as
hexadecimal, then converting that representation back to a binary
number. Of course you can do that, but it's an overly complicated and
expensive way of doing something trivial.
The canonical way to recover an integer from a byte array is by
assembling the bytes together using bitwise logic and bit shifts. In
this case:
int16_t reactive_power = (uint16_t) data[dataSize - 5] << 8
                       | data[dataSize - 4];


how to do Arduino to esp8266 communication I am trying to do Arduino to ESP8266 communication, but I am not able to send data to esp8266. However I can receive data from esp8266.

Here if my Arduino code:

#include <SoftwareSerial.h>
SoftwareSerial ESPserial(0, 1); // RX | TX

void setup()
{
  Serial.begin(115200);     // communication with the host computer
  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Enter 1 to turn led high & 2 to turn led low.");
}
// the loop function runs over and over again forever
void loop() {
  // listen for communication from the ESP8266 and then write it to the serial monitor
  if ( ESPserial.available() )   {
    Serial.write( ESPserial.read() );
  }

  // listen for user input and send it to the ESP8266
  if ( Serial.available() )       {
    ESPserial.write( Serial.read() );
  }

}

Here is esp8266 code:

void setup()
{
  Serial.begin(9600);     // communication with the host computer
  // Start the software serial for communication with the ESP8266
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  Serial.println("ESP -- Hello");
  delay(1000);
  // listen for user input and send it to the ESP8266
  if ( Serial.available() )  {

    int ledState = Serial.parseInt();
    if (ledState == 1) {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      Serial.println("ESP Led On\n");
    }
    if (ledState == 2) {
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      Serial.println("ESP Led Off\n");
    }
  }
}

Once I upload both sketches, then I can see it terminal " ESP -- Hello " keep printing comming from esp8266 but when I enter 1 or 2, its not sent to esp8266 due to which I never see "ESP led on/off" messages , so correct me guys what mistake I am making.

using SoftSerial on the hardware serial isn't working on Arduino properly as sometime data receive and sometime not with garbage added so Using digital pins  other  2, & 3  other than hardware serial resolved the issue.


Wifi networking with ESP8266 (NODEMCU version) I am doing some experiments with nodemcu 12 (which has built in esp8266). There most of the tutorials I found by internet describe how to connect to home wifi connection using it.

But when I power on nodemcu, I can see wifi network called "ESPXXX" in my laptop's wifi connection list.

So is there a way to directly connect to the wifi nw of esp8266 by my laptop or via another esp8266 (so I don't have to switch on my home wifi router)?

If it is possible, is there is way to change ssid of esp8266's wifi connection and add password (again this is not about connecting to home wifi and this is about the wifi connection on esp8266 it self)?
So we can make one esp8266 as a wifi host and connect other esp8266s as slave to it.

I am using arduino IDE to upload program into esp8266 and not Lua.

Thanks.

Here you are the working code allowing you to choose SSID, password, network name and IP address of your ESP8266 acting as an access point. In addition, you can specify wifi channel to avoid interference with other devices. A password must be at least 8 characters long or it wouldn't work.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

IPAddress ip(192,168,1,81);         // choose IP address
IPAddress subnet(255,255,255,0);

ESP8266WebServer server(80);

void handleRoot() {
  String page = "<!DOCTYPE html>\n";

  page += "\n\n
Some heading

Generated by ESP8266\n\n";
  server.send(200, "text/html", page);
}

// what to do when accessed through http://ip_address/something_undefined
void handleNotFound(){
  String message = "File not found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void){
  Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
  WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

  IPAddress myIP = WiFi.softAPIP();
  Serial.println();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

  // what to do when accessed through http://ip_address/test
  server.on("/test", [](){
    server.send(200, "text/plain", "This is another page");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started...");
}

void loop(void){
  server.handleClient();
}

You can write something like:

server.on("/open_door", [](){
        // the code to switch on the relay to open the door
        // ... <-- put here the code
        server.send(200, "text/html", "Door: opened");
});

so you can open the door with http://ip_address/open_door.

You can try http://ip_address/something_undefined?a=24&b=25 to get an idea how to process the parameters.


Getting the average of sound in last minute I am reading sound input every 60 seconds and I would like to calculate the average of sound during that period using non-blocking code; what should I do to change the way that I calculate it in separated function as I need to do something else with other sensors.

int calculateSoundValue(){
    int average = analogRead(0);
    // loop to calculate the average simple formula sum div nbr of calculated times
    return average;
}

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

}
void loop() {
  // I donùt wanna calculate the average inside a loop but instead inside a function
  int value = calculateSoundValue();
  Serial.println(value);

  delay(600);
}

UPDATE

Is this what you mean ?

unsigned long previousMillis = 0;
const long interval = 6000;
int totalSamples = 0;
int count = 0

    int calculateSoundValue(){
        int sound = analogRead(0);
        totalSamples+= sound;
        count += 1;
        return totalSamples/count;
    }

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {

  unsigned long currentMillis = millis();
int totalSamples = 0;
int count = 0
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

  }
      int value = calculateSoundValue();
      Serial.println(value);
}

I assume what you actually want is to measure sound intensity. This is
significantly more involved than just averaging the samples you read. I
have written a few weeks ago a program that does exactly that: it
measures the sound intensity and sends those measurements through the
serial port. It is a pretty short program (43 lines of code) you may be
able to adapt to your needs, so I am now sharing it as a GitHub gist:
sound-meter.ino.

In order for this not to be a link-only answer, I'll try to explain the
program's inner working, and go through the theory of measuring sound
intensity on an Arduino. But first let me put here a disclaimer: a
“real” sound level meter should have a frequency response that complies
with some standards, and it should be calibrated to absolute levels.
This program only provides uncalibrated readings with whatever frequency
response its analog hardware has.

Signal conditioning

Four measuring sound on an Arduino, you obviously need a microphone,
but you also need some kind of interface circuit between the microphone
and the Arduino. The purpose of the interface is to “condition the
signal”, i.e. to make sure the Arduino gets a voltage in the proper
range for it's analog-to-digital converter (ADC). It's typically an
op-amp based circuit that provides some amplification and also adds a DC
bias to avoid clipping the negative side of each oscillation. Ideally,
the DC bias should be around Vcc/2, i.e. 2.5 V on an Arduino Uno.

See this SparkFun microphone
breakout for an example on how
such a circuit may be built (click on “Schematic”).

ADC sampling

Once you have a properly conditioned analog signal, you have to sample
it fast enough to catch all its spectral content. The Nyquist–Shannon
sampling
theorem
tells us the sampling rate should be at least twice the highest
frequency in the signal. For audio signals, sampling rates of the order
of 8 kS/s (kilosamples per second) are typical of low quality,
telephone-like applications, whereas high quality audio would run at
44.1 to 48 kS/s.

The ADC of the Arduino Uno, in its default configuration, takes
104 µs to convert one sample. If you just call analogRead() in a
tight loop, this gives a sampling rate of about 9.6 kS/s, which is
fine for this kind of application, unless we have to measure noise above
4.8 kHz. The problem with this approach is that analogRead() is a
blocking function. Calling it in a tight loop means the program will
spend most of its time just waiting for the ADC. If you do anything else
in the loop, not only will the sampling rate be lowered, it will also
become unsteady, which is generally not desirable.

In order to avoid blocking the CPU, we have to forgo analogRead(), and
instead get our hands dirty with low-level configuration of the ADC. The
ADC of the Arduino Uno offers a so-called “free running mode”, which is
well suited for this kind of application. In this mode, the ADC starts a
new conversion as soon as the previous one is done, ensuring a very
consistent sampling rate of 9.6 kS/s. It can also trigger an
interrupt after each conversion, in order for the interrupt service
routine to retrieve and process the sample. See the datasheet of the
ATmega328P
for details on configuring the ADC.

Removal of the DC bias

Once we have the digitized samples, the first thing to do is to remove
the DC bias that was added by the interface circuit. If the bias is
stable and known (maybe determined by experiment), this only involves
subtracting a constant. If it is not known, it can be estimated by
running the samples through a digital low-pass filter with a cutoff
frequency below the range of interest. Subtracting the output of a
low-pass filter is essentially building a high-pass filter. As an
alternative, a numerical derivative (difference between consecutive
samples) can be used as a crude high-pass filter. This, however, will
bias the sensitivity of the detection towards the high end of the
spectrum. Depending on the noise you want to detect, and on the
background noise, this could be acceptable for your application.

In the program I am sharing, I assume the DC bias is known: it's the
dc_offset constant at the beginning of the program.

Instantaneous intensity

With the DC bias removed, the signal we have is a digital image of the
sound picked by the microphone. It could be tempting to just average it
as is. This, however, would just give zero, as the positive fluctuations
of the signal would cancel the negative ones.

The are several options to solve this problem. We could do a peak
detection instead of an average, or we could take the absolute value
before averaging. The most popular option is probably to compute the
squares of the samples. Since the square of a real number is always
positive, this avoids the averaging-out problem. But the square has also
a deeper physical meaning: it is proportional to the sound
intensity, i.e. the
energy carried by the sound wave.

Low-pass filter

The intensity computed above is a very fast varying quantity. If the
signal is a simple tone of constant frequency and volume, the
instantaneous intensity fluctuates between zero and some maximum at
twice the tone frequency. In order to recover the “constant volume”
property of the sound, we need to perform some sort of averaging or, in
other words, we need a low-pass filter.

There are many ways to implement a digital low-pass filter. The most
intuitive may be to group the samples into batches, and then compute the
average of each batch. However, this is neither the best nor the most
efficient to implement. When I need a quick and simple low pass filter,
I generally use an exponential moving
average.
This is the discrete-time equivalent of an analog RC filter, and it can
be implemented very efficiently by remembering the previous output and
updating it as

output += input - output / N;

where, for efficiency reasons, N should be a power of two. The filter's
time constant is N/fs, where fs is the sampling
frequency. In the program I use N = 256, which makes the
division virtually free. This gives a time constant of 26.6 ms. You
can tune the time constant to your needs simply by changing N, but make
sure it is still a power of two.

Decimation

If you only want to trigger an event when the sound intensity exceeds a
defined level, you may not need this. But if you have other processing
to do with those measurements, it is probably not useful to process more
than one intensity reading per time constant of the previous filter.
That's why the program has a decimation step. This is simply the ISR
periodically signaling the main program that an intensity reading is
available. Notice that, since the sample count is an 8-bit variable, it
automatically counts modulo 256. If you want to increase the decimation
factor, you should make sample_count wider and mask out the bits you
do not need.


Arduino GSM module + SMS string sending garbage value I want to check the water level and have an SMS sent via a GSM module. Reed switches are connected to four Arduino analog inputs.

I am unable to add a string and tank level (TKLVL) in program.
The program is sending some garbage value via SMS. But TKLVL variable prints the right value.

What is wrong with my code?

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(10, 11);
    String textMessage;
    #define LED1 2
    #define IRLED 3
    //#define rf433DATA 4
    //D4 IS CONNECTED TO RF433MHZ RECEIVER CHANGE ACC TO LIBRARY
    #define PIRpower 5
    int receiver = 6;
    #define VALVE1 7
    #define GSMRESET 8
    #define pumpONdetect 9
    #define VALVE2 12
    //#define TANK_SENSPOWER 13 //
    #define TANK_SENS4 A0  //full tank wigh buzzer
    #define TANK_SENS3 A1
    #define TANK_SENS2 A2
    #define TANK_SENS1 A3  //low tank
    int TKLVL= 0;
    int LEVEL;

    void setup()
    { pinMode(LED1, OUTPUT);
      pinMode(IRLED, OUTPUT);
      pinMode(PIRpower, OUTPUT);
      //CHECK RECEIVER PIN
      pinMode(GSMRESET, OUTPUT);
      pinMode(VALVE2, OUTPUT);
      // pinMode(TANK_SENSPOWER, OUTPUT); //DRIVE THIS PIN LOW TO ON TANK POWER(PNP TRANSISTOR)
      pinMode(TANK_SENS4, INPUT); //FULL TANK WITH BEEP BUZZER
      pinMode(TANK_SENS3, INPUT);
      pinMode(TANK_SENS2, INPUT);
      pinMode(TANK_SENS1, INPUT); //LOW TANK WATER
      // digitalWrite(TANK_SENSPOWER, HIGH); //turns OFF tanksenspower OFFvia PNP transistor..
      Serial.begin(9600);
      SIM900.begin(9600);
      Serial.print("SIM900 ready...");
      SIM900.println("AT+CMGD=1,4\r");
      delay(1000);
      // AT command to set SIM900 to SMS mode
      SIM900.println("AT+CMGF=1\r");
      delay(400);
      // Set module to send SMS data to serial out upon receipt
      SIM900.println("AT+CNMI=2,2,0,0,0\r");
      delay(400);
      digitalWrite(VALVE1, LOW);

    }

    void loop()
    {
      if (SIM900.available() > 0) {
        textMessage = SIM900.readString();
        Serial.print(textMessage);
        delay(10);
      }
      if (textMessage.indexOf("Von") >= 0)
      {
        G_valve1On();
        Serial.println("on loop");
        textMessage = "";
      }
      if (textMessage.indexOf("Voff") >= 0)
      {
        G_valve1Off();
        Serial.println("off loop");
        textMessage = "";
      }

      if (textMessage.indexOf("Tanklvl") >= 0)
      {
        Tanklvl_calc();
         Serial.print("TKLVL is=");
         Serial.println(TKLVL);
        //  TKLVL=LEVEL;
        // Serial.print("level is=");
        //Serial.println(LEVEL);
        String msg ="TANK IS " + TKLVL;
        Serial.println(msg);
        sendSMS(msg);
        textMessage = "";
      }

    }
    //SEND SMS function
    void sendSMS(String lvlmsg)
    {
      SIM900.print("AT+CMGF=1\r");
      delay(1000);
      SIM900.println("AT+CMGS=\"+9182375*****\"\r");
      delay(100);
      SIM900.println(lvlmsg);
      delay(100);
      SIM900.println((char)26);
      delay(1000);
      SIM900.println();
      delay(5000);
    }

    void G_valve1On()
    {
      digitalWrite(VALVE1, HIGH);
      Serial.println("...turning valve1 on...");
    }
    void G_valve1Off()
    {
      digitalWrite(VALVE1, LOW);
      Serial.println("...turningvalve1 off...");
    }

    int Tanklvl_calc()
    {
      if (digitalRead(TANK_SENS4) == HIGH)
      {
        TKLVL = 100;
        Serial.println("TANK LEVEL 100%");
      }
      else if (digitalRead(TANK_SENS3) == HIGH)
      {
        TKLVL = 75;
        Serial.println("TANL LEVEL 75%");
      }
      else if (digitalRead(TANK_SENS2) == HIGH)
      {
        TKLVL = 50;
        Serial.println("TANK LEVEL 50%");
      }
      else if (digitalRead(TANK_SENS1) == HIGH)
      {
        TKLVL = 25;
        Serial.println("TANK LEVEL 25%");
      }
      else
      {
        TKLVL = 0;
        Serial.println("TANK LEVEL IS LESS THAN 25%");
      }
      return(TKLVL);
    }

Using Strings in a microcontroller is a no-no.
First, try to send a test SMS, to see if everything works OK on SIM800-Arduino etc.

If you receive it correctly, then try to play with char arrays.
First, declare a char array big enough for your data to fit in. Let's use a demo array, but keep in mind that it's your responsibility to keep things tidy.

byte sizeOfBuffer = 10;
char smsString[sizeOfBuffer] = {'\0'};

What we did is create an smsString array of 10 bytes, 9 bytes for data and 1 byte for our special end of sting character. Since we don't want Arduino to handle things with Strings, we have to tell our microcontroller where does that String end. That's what '\0' does.

Then, modify the send function to accept that data type.

//SEND SMS function with char array
void send_SMS_charArray(char *lvlmsg, byte sizeOfsms)
{
  SIM900.print("AT+CMGF=1\r");
  delay(1000);
  SIM900.println("AT+CMGS=\"+918237504767\"\r");
  delay(100);
  for (byte i=0; i<sizeof(sizeOfsms); i++){
    SIM900.print(lvlmsg[i]);
  }
  Serial.println();
  delay(100);
  SIM900.println((char)26);
  delay(1000);
  SIM900.println();
  delay(5000);
}

Finally, to call the new function you would do something like

sprintf_P(smsString, PSTR("TANK IS: %i"), TKLVL);
send_SMS_charArray(smsString, sizeOfBuffer);

Notice sprintf_P when using static messages such as "TANK IS". It will save your life in a few months.


What is the size of the buffer in serial communication with arduino uno? as it is in the question, i need to know what is the size of the biggest string that i can send using the serial port to the arduino.
Thank you

That would be 64 bytes, providing the buffer is fully empty. See https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h#L42-L43


Can we use yx5300 to play audio from a file in Arduino? I want to play a file that I have in my USB device through a yx5300 mp3 module.

I have a file in my USB device at path Music/hello.mp3. I want to play this file using the yx5300 module or some other module, if available.

I have already read this file using a shield. I want to pass the data to the yx5300.

No. That chip can only play files on an SD card that is directly attached to it.


Problems with serial communication from Arduino to ESP8266 I've been trying to get an Arduino and ESP8266 to communicate with each other over serial. The ESP8266 uses the Serial class for communications, while the Arduino uses SoftwareSerial.

The problem is that when I try to send data from the Arduino to the ESP8266,  only the first character of the string sent gets received by the ESP8266. For example, if I send a string "leather", the ESP8266 only receives an 'l'. Both devices are operating at 38400 baud, although I have tried 9600 baud with similar results (apparently SoftwareSerial is more reliable at lower baud rates).

Here is the relevant code that's running on both devices:

Arduino code:

#include <stdlib.h>
#include <SoftwareSerial.h>

#define COMMAND_TILT                'c'
#define SOFTWARE_SERIAL_BAUD_RATE   38400
#define ESP_RX                      8
#define ESP_TX                      9

SoftwareSerial esp(ESP_RX, ESP_TX);

void setup()
{
    ...
    esp.begin(SOFTWARE_SERIAL_BAUD_RATE);
    ...
}

void loop()
{
   if (esp.available() > 0) {
        String data;
        while (esp.available() > 0) {
            data += (char) esp.read();
        }

        char command = data.charAt(0);
        data.remove(0, 1);
        int value = data.toInt();
        char buf[STR_BUF_LEN];

        switch (command) {
             case COMMAND_TILT:
                 ...
                 sprintf(buf, "%c%d", COMMAND_TILT, value);
                 esp.write(buf);
                 break;
             ...
        }
    }

    delay(100);
}

...

ESP8266 code:

#define SERIAL_BAUD_RATE 38400

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

void loop()
{
    ...

    if (Serial.available() > 0) {
        String data;
        while (Serial.available() > 0) {
            data += (char) Serial.read();
        }

        char command = data.charAt(0);
        data.remove(0, 1);

        // problem: now, data.c_str() is blank when it should contain an integer in string format

        ...

        delay(100);
    }
}

...

If it helps to know, I'm running an MQTT client on the ESP8266 and controlling some steppers and relays on the Arduino.

The cause of the issue was that the ESP was reading chars too quickly, meaning that it would give up before the next char could be sent from the Arduino. To fix the issue I simply added a 10 ms delay between each Serial.read() call on the ESP.


'Non-Deterministic' memory usage on Arduino I had a problem with a memory leak in my sketch and cornered it with MemoryFree.h. This works great and I was able to fix my leak.

My sketch is not really static, but My var sizes are. I observed, that the free memory on the arduino reaches a different values and stays there.

For Example

Run 1: 1655 Bytes Free
Run 2: 1659 Bytes Free
Run 3: 1654 Bytes Free

For every run, I get a different, but over a short time, fixed memory usage. Is this normal?

P.S: The serial input to the script just repeats forever with the exact same data.

You haven't posted any code, so any answer is guesswork. However ... if your code makes decisions based on external events (eg. readings from sensors) then it may allocate memory differently, and in a different order, each time.

Sometimes memory allocation leaves gaps (known as "heap fragmentation"). Small differences in your results probably show slightly different sized gaps, due to the allocation order.


Trying to print "occur = 1" in an if statement but it wont work Cant seem to get this code to work with my arduino, and yes its all hooked up properally, even used leds to show that the button is being pressed, what am i doing wrong or dont know?

const int digitalInPin3 = 8;     //switch
int Occur = 0;
int Switch = 0;

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

void loop() {
int Switch = digitalRead(digitalInPin3);

if (Switch == 1){
  int Occur = 1;
}

else {
 int occur = 2;
}

   Serial.print("\t Switch =");
   Serial.print(Switch);
   Serial.print("\t occur =");
   Serial.println(Occur);

  delay(1);
}

Remove the int from inside the if and else statement. The code would always show 0 because access of occur, which is assigned value 1 or 2 is limited to the if..else statement. So the global occur remains 0 always.

So change it to:

if (Switch == 1){
 Occur = 1;
}
else {
 Occur = 2;
}

This will work.


SAM3X8E (Arduino Due) Pin IO registers How do the IO registers of Arduino Due work?
On Arduino Uno just set DDRx, then PINx to read, PORTx to write, I'd like to do the same thing with an Arduino Due, but it has many more registers, such as PIO_OWER, PIO_OSER, PIO_CODR, PIO_SODR, etc. I find no correspondence between Arduino Uno and Arduino Due registers.

There are also some useful functions such as pio_clear, pio_set, pio_get, and others, all explained here:

http://asf.atmel.com/docs/3.19.0/sam3x/html/group__sam__drivers__pio__group.html

Now, I think I've understood what the three mentioned functions do, but not others, for example:

pio_configure (Pio *p_pio, const pio_type_t ul_type, const uint32_t ul_mask, const uint32_t ul_attribute)

I can't figure out what ul_attribute and ul_type are.

If you have a read of section 31 of the Datasheet, available from here, things may come a little clearer for you.

Here's a summary of what I know:

PIO stands for Parallel Input/Output and offers the functionality to read and write multiple register ports at a time.  Where the datasheet mentions a register, for example PIO_OWER, the Arduino library has macros for accessing them in this format REG_PIO?_OWER where ? is either A, B, C or D for the different ports available.

I tend to still use the slow Arduino pinMode() function to set input/output on the pins as it makes the code more readable than the acronym based registers calls such as REG_PIOC_OWER = 0xdeadbeef, but then use the direct registers to set the pins for performance/synchronisation.  As yet, I haven't done anything with input, so my examples are all output based.

For basic usage, you would use REG_PIO?_SODR to set output lines high and REG_PIO?_CODR to set them low.  For example REG_PIOC_SODR = 0x00000002 would set bit 1 (numbered from zero) on PORTC (this is Due digital pin 33) high. All other pins on PORTC remain unchanged.  REG_POIC_CODR = 0x00000002 would set bit 1 on PORTC low.  Again all other pins would be unchanged.

As this is still not optimal, or synchronised if you are working with parallel data, there is a register that allows you to write all 32 bits of a port with a single call.  These are the REG_PIO?_ODSR, so REG_PIOC_ODSR = 0x00000002 would now set bit 1 on PORTC high and all other bits on PORTC would be set low instantly in a single CPU instruction.

Because it is unlikely that you would ever be in a situation where you need to set all 32 bits of a port at the same time, you would need to store the current value of the pins, perform an AND operation to mask out the ones you want to alter, perform an OR operation to set the ones you want set high then perform your write and again, and this is not optimal.  To overcome this, the CPU itself will perform the masking for you.  There is a register called OWSR (output write status register) that will mask out any bits that you write to ODSRs that don't match bits set in the OWSR.

So, now if we call REG_PIOC_OWER = 0x00000002 (this sets bit 1 of the OWSR high) and REG_PIOC_OWDR = 0xfffffffd (this clears all bits except bit 1 of the OWSR) and then call REG_PIOC_ODSR = 0x00000002 again, this time it would only change bit 1 of PORTC and all other bits remain unchanged.  Pay attention to the fact that OWER enables any bits that are set to 1 in the value you write and that OWDR disables any bits that are set to 1 in the value you write.  Even though I understood this when I read it, I still managed to make a code mistake when writing my first test code thinking that OWDR disabled bits that weren't set to 1 in the value I wrote.

I hope this has at least given you a bit of a start in understanding the PIO of the Due CPU.  Have a read and a play and if you have any further questions, I'll try to answer them.

Edit:
One more thing...

How do you know which bits of the PORTs correspond to which digital lines of the Due?  Check this out: Due Pinout


UNO SPI slave read from UNO SPI Master beginTransaction For a project I am trying to understand SPI.

The final project I will use this in, is for reading the SPI from a car radio.

That Radio writes to address 0x80 of a DDRAM LCD display. MY intent is to read for a write to this address and if the bits are correct replace waht is being written.

IE Radio says write the letter E to 0x80, using a mega2560 read this and then interject a different letter then write to the radio screen. So the radio is a master with the Mega and LCD as daisy chained slaves.

I'm using the base code from for writing to the screen. This was written to fully replac ethe radio so i'm trying to mimic the radio using an UNO as Master and the screen using a Uno as a slave.

I've got the demo working from circuits4you.com

I'm trying to modify it to use the same STI settings as seen in the base radio replacement code i'll be modifying for my final project. I know this code writes correctly to the screen. The problem is that the code uses SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3)); as its designed to replace the radio functions.

I'm trying to get that line to work on the 2 UNO's im bench testing with so I can make the mega a slave in the final project.

SPI MASTER Code

void setup (void) {
   Serial.begin(9600); //set baud rate to 115200 for usart
   digitalWrite(SS, HIGH); // disable Slave Select
   SPI.begin ();

}

void loop (void) {
    SPI.beginTransaction(SPISettings(9600, MSBFIRST, SPI_MODE3));

   char c;
   digitalWrite(SS, LOW); // enable Slave Select
   // send test string
   for (const char * p = "Hello, world!\r" ; c = *p; p++)
   {
      SPI.transfer (c);
      Serial.println(c);
   }
   digitalWrite(SS, HIGH); // disable Slave Select
   delay(2000);
   SPI.endTransaction();
}

The problem seems to arise from the SPI.attachInterrupt() not being compatible with the SPI.beginTransaction is this correct and is there a way around it?

SPI SLAVE Code

include <SPI.h>
char buff [50];
volatile byte indx;
volatile boolean process;

void setup (void) {
   Serial.begin (9600);
   pinMode(MISO, OUTPUT); // have to send on master in so it set as output
   SPCR |= _BV(SPE); // turn on SPI in slave mode
   indx = 0; // buffer empty
   process = false;
   SPI.attachInterrupt(); // turn on interrupt

}

ISR (SPI_STC_vect) // SPI interrupt routine
{
   byte c = SPDR; // read byte from SPI Data Register
   if (indx < sizeof buff) {
      buff [indx++] = c; // save data in the next index in the array buff
      if (c == '\r') //check for the end of the word
      process = true;
   }
}

void loop (void) {

   if (process) {
      process = false; //reset the process
      Serial.println (buff); //print the array on serial monitor
      indx= 0; //reset button to zero
   }

}

Okay so I have got this working now. It seems that it was the Slave not understanding the data mode. I found the SPI.setDataMode() it is listed as Do not use in the reference guide on Arduino.com but its worked spot on for me.


Serial data is not sent on interrupt I have a short program which should receive data, use this data to turn on/off an LED, and send data when a button is pressed. It is deployed on a Digispark board. The button is connected to INT0 port (PB2). The interrupt works, but data is not send. Receiving data works fine.

What am I missing here?

#include <SoftSerial.h>

#define RxD 1
#define TxD 0
#define out 3
#define btn 2
#define testled 4

SoftSerial blueToothSerial(RxD, TxD); //RX, TX
volatile int buttonState = 0;

void setup() {
  pinMode(out, OUTPUT);
  pinMode(btn, INPUT);
  pinMode(testled, OUTPUT);
  setupBlueToothConnection();
  digitalWrite(out, HIGH);
  digitalWrite(testled, HIGH);
  attachInterrupt(0, intrpt, CHANGE);
}

void loop() {
  char newVal;
  if(blueToothSerial.available()){
    newVal = blueToothSerial.read();
    if (newVal == '1') {
      digitalWrite(out, HIGH);
    } else {
      digitalWrite(out, LOW);
    }
  }
}

void intrpt() {
  buttonState = digitalRead(btn);
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(testled, HIGH);
  } else {
    // turn LED off:
    digitalWrite(testled, LOW);
    blueToothSerial.println("0");
  }
}

void setupBlueToothConnection() {
  blueToothSerial.begin(9600);
  blueToothSerial.print("\r\n+STWMOD=0\r\n");
  blueToothSerial.print("\r\n+STNA=HC-05\r\n");
  blueToothSerial.print("\r\n+STOAUT=1\r\n");
  blueToothSerial.print("\r\n+STAUTO=0\r\n");
  delay(2000);
  blueToothSerial.print("bluetooth connected!\n");
  delay(2000);
  blueToothSerial.flush();
}

EDIT

Serial data is sent fine. The above code works. On Windows I can see the data are coming, but not on OS X.

If you are handling interrupts then you need to keep the code as quick and simple as possible.  I suspect that in this case calling blueToothSerial.println is what's causing the problem. It may well be calling an operation that an ISR can't call and so it fails and your code doesn't write the data you expect it to.

All I ever do in ISRs is set flags and then get the 'normal' code to handle changes to the flags. Personally I wouldn't do the digitalWrites within the ISR. Have two volatile variables, one for the pin state and one when sending a message is required and handle those in your loop().


Variables not saving I'm trying to write web server code. However, I am having trouble with part of it.

Currently, to get it to save a bool variable I have it use a pin, as when I ran the code without it, after the page refreshes it resets the variable to its original value.

How do I get it to save the variable in this code without it using the pin?

digitalWrite (equalPin, server.arg("equal").toInt());
char equalText[80];
if(equalState) {
  strcpy(equalText, "priority is equal. Deactivate");
  equalState = false;
} else {
  strcpy(equalText, "priority is not equal. Activate");
  equalState = true;
}
equalState = digitalRead(equalPin);

I also have several over copies of this for different pages but if I change 1 of them they all change and reset after 10 seconds.

The code follows the example on this site.

same code snippet without using pin

char equalText[80];

if (equalState){
  strcpy(equalText, "priority is equal. Deactivate");
  equalState = false;
}
else {
  strcpy(equalText, "priority is not equal. Activate");
  equalState = true;
}
equalState = server.arg("equal").toInt();

but it does not make much sense to set the value if you already switched the state based on it's previous value


Advanced I/O shifting bits I wanted to tinker around more with the 8-bit shift register (74HC595) so I tried to make a simple LED display and after reading about some shift commands I got lost and didn't understand much...

Let's start simple...

from what I read -- you can send out Binary data 1s and 0s --- does the shift regsiter read it as on and off? the shift register I'm using which is probably the same thing with others but it has 8 pins that can be used as output --- how does it output the data? --- does it output (example) 10100110 which shifts to the right as if 00000000 -> 10000000 -> 11000000 -> 01100000 -> 00110000 -> 10011000 -> 0100110 -> 10100110 through the pins one by one? like pin 1 would get 0 first then 0 will move to pin 2 and pin 1 will get a 1? (still using 10100110 by example above ^ )

Also what would the code look like? how does shiftOut() and shiftIn() work exactly? does all of this have something to do with pulseIn()? what do the bitwise operators like >> and << or ~ to name a few exactly do?

let's say I made 8 leds hooked up to one of each output pin of the shift-register --- how do I give data to the register? what commands should I use to give data? --- from what I understood I can output 01011011 right? if so, how does the shift-register output it? and if (Assumingly) it does output it like on and off would it eventually turn out as if LED1 = OFF LED2 = ON LED3 = OFF LED4 = ON LED5 = ON LED6 = OFF LED7 = ON LED8 = ON as if I entered in 01011011?

tl;dr

how do 8-bit shift registers work and how do you make codes work with them xP

For the 74HC595 in combination with the Arduino, the best way to check is to use the default example by Arduino:

ShiftOut

With the ShiftOut you can shift the bits into the IC which will make the correct LEDs light up (or not).

Probably you can lit up a LED when passing a HIGH, but you will know very easily by trying the example and check some values/for loops to make them dynamically lighting.

Probably after playing with the example, it will give you much more insight than describing the details here.

Update:

Try first with 00000000 and 11111111 and 8 leds, so you know if 0 will be OFF and 1 will be ON.
Than try with eg 10101010 and 8 leds ... than you know if the first or the last will be on or off.
pulseIn is unrelated
The operators >> and << are so called bit shift operators. Like 1 << 3 gives 8, the binary value 0000001 is shifted 3 bits left resulting in 00001000 which has value 8.
~ is the not operator -> which reverses bits.
The shiftOut function can be used to send data to the 74HC595N.
And to be honest, how does it work ... does it really matter for now? First see what the result is, how to use it. Later you can get into details. Start simple first.


Which motor (type) to use for an arduino controlled magnetic stirrer? I am in the process of building my own sous vide machine and like to replace the pump typically found in most commercial machines with a magnetic stirrer unit. I figured the easiest way would be to use a motor to spin a permanent magnet (instead of creating a strong rotating magnetic field electrically). I first started experimenting with some 12V DC fans leftover from an old computer. By either lowering the input voltage or via PWM I was able to obtain appropriate rotational speed (don't ask me about exact speeds, I guess around 300rpm or so). With the project maturing I am not sure which motor (type and/or exact model) to use. I hoped some of you might point me in the right direction for the type of motor or even better, could suggest a specific model. I considered stepper motors or continuous  servo motors. My criteria for the motor are:

easy to control rotational speed between 0 and around 500 or so rpm (for ramp up and variation of speed to increase turbulent flow)
ability to rotate both clockwise and counter clockwise
enough torque at all speeds to spin a disk with magnets attached (weight and inertia probably negligible, the to be used alnico magnets create a field strong enough to lift 0,4kg each)
small axial dimensions
reasonably priced and long lasting
quiet

The following picture shows a commercial magnetic stirrer found in your average laboratory. The blurry white object in the glass beaker is the the so called stir bar or "fish", a PTFE coated permanent magnet. It spins due to the rotating magnetic field created by the actual device underneath the beaker.

I'd personally recommend a continuous rotation servo or a brushed DC motor. Personally, for this kind of load, I think it would be easier and cheaper to go with the brushed DC motor. You have to remember a continuous rotation servo is a DC motor with some circuitry so you can send pulses to it to control the speed (although it's not directly proportional to the signal you send).

A servo is the only other option besides a brushless motor; both require a little more circuitry than the brushed motor/continuous servo. The additionally cost more. This blog post covers the differences between brushed and brushless motors.

For driving a continuous, you hook it up to power [depends on your servo voltage], ground, and another Arduino pin and use the servo library to send a signal as a degree (90 = no speed, 180 = full speed forward, 0 = full speed backward).

A brushed you would need a h-bridge that allows you to either send voltage, send no voltage, or send reverse voltage (for backward). This chip (~$5) does that for two motors and allows PWM for different speeds. It also includes a brake function, although that doesn't seem necessary for you. It can handle up to a "2.4 A continuous (4 A peak)." I talk about this in this answer of mine.

Quick note, if you want to control the exact RPM of the device and not just manually adjust it to a good rate, you'll need some sort of a rotary encoder or similar. A reed switch (sends current depending on magnetic fields) would work perfectly for this purpose, just mount it below the magnets and figure out the degrees rotated by the motor for each "pulse."


QuadCopter PID using MPU6050 I am using Arduino Uno, with PID library and Jeff Rowberg library for MPU6050 i.e I2Cdev.h, MPU6050_6Axis_MotionApps20.h.

There is one PID for each axis i.e Pitch and Roll, I am getting output that wobbles and is unstable. I don't know whether my code is wrong or something else.

Errors which I feel are:

I am using Esc.write(), I know Microseconds should be used but it feels very light, even it doesn't wobble.
Kalman Filter not used, but I am getting the pitch, roll, yaw.
PID library (By Brett Beauregard) not suitable for Quadcopter.
else if (mpuIntStatus & 0x02) // wait for correc available data length, should be a VERY short wait
         while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
This statement in loop making loop slow, it's written in its comment and maybe it making pid compute upset

Please look at code.

#ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        yaw = ypr[0] * 180/M_PI;
        pitch = ypr[1] * 180/M_PI;
        roll = ypr[2] * 180/M_PI;

        Input = pitch;
        RInput = roll;
        myPID.SetTunings(Kp,Ki,Kd);
        myPIDR.SetTunings(RKp,RKi,RKd);

        //Sample Time is 10 for both PID.

             myPID.Compute();
              myPIDR.Compute();

        if(armed == 1) {
          int m1 = throttle.toInt() + Output;
          int m2 = throttle.toInt() + ROutput;
          int m3 = throttle.toInt() - Output;
          int m4 = throttle.toInt() - ROutput;

 int angle1 = map(m1, 0, 100, 0, 180);
 ESC1.write(angle1); //FRONT PITCH+
 int angle2 = map(m2, 0, 100, 0, 180);
 ESC2.write(angle2); //LEFT ROLL+
 int angle3 = map(m3, 0, 100, 0, 180);
 ESC3.write(angle3); //BACK PITCH-
 int angle4 = map(m4, 0, 100, 0, 180);
 ESC4.write(angle4); //RIGHT ROLL-
        }
    #endif

Kp = 0.25, Ki = 0.04, Kd = 0.05 |
RKp = 0.25, RKi = 0.04, RKd = 0.05

From testing: if I shake my Quadcopter fast by hand it behaves like PID is activated and works as wanted, but suddenly after a couple of seconds again feel loose, may be PID compute become upset

Quadcopters usually use 2-PID loops per axis, a rate loop and an angle loop.

Your quadcopter needs to be very aggressive about its rate of rotation but relatively relaxed about how quickly it returns its angle to the center so it doesn't overshoot. With a single PID it will either be too slow to correct or overshoot and oscillate with no "usable" range of tunings in-between, because in order for its outputs to be strong enough to control the quad it will necessarily be too aggressive to smoothly align with the center position. There is a lot of math that explains why this cannot be achieved with a single loop more rigorously if you care to look into it.

So try setting it up with a PitchAngle PID whose output is the setpoint of a PitchRate PID loop whose output goes to the motors, and similarly with the Roll.

That is only one possible problem though, there is a huge number of things that could be wrong. Are your pitch and roll measurements angles to the horizon or euler angles? how fast is your loop running? Are oscillations induced by the motors causing your accelerometer reading/attitude filter combo to be unusable? Are the PID parameters correct? Is the accelerometer's bias calibrated? Is the gyro drift calibrated? Are all you ESC's calibrated the same way?


How do I feed NRF24L01 from Arduino Pro Mini? I wanted to control speed of my four coreless DC motors using Arduino Nano. Then I realised my 3.7V 380mAh 25C and 720mAh (110mAh on picture is just to hold my battery's place) 25C LiPo batteries won't meet the voltage requirement of a Nano. Then I came up with the idea of using Pro Mini instead of Nano; however I couldn't find a 3.3V pin on Pro Mini to feed NRF24. On Nano, I was using a 3.3V pin and 10uF capacitors between Vin and Gnd legs of NRF24.

So my question is: can I feed NRF24 directly from Vcc pin? Or as an alternative what would happen if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via another TIP122 transistor?

Note: I am using 4 of TIP122 transistors whose gate legs are connected to Pro Mini's 5, 6, 9 and 10 pwm pins (I forgot to add base-resistors). Do you also think it is a reliable way of controlling the motors' speed?

can I feed NRF24 directly from Vcc pin?

NO: the pro mini is either 5V or not strong enough to power the RF24.
EDIT: the 3V3 pro mini "could" power the RF24 via VCC, if you use the cap and if it's not the PA&LNA model (or in full power mode). Best practise is to use an external regulator.

  if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via
  another TIP122 transistor?

NO: lipos are 4.2V when fully charged, and they can be used until 3V (I mean 3V sag voltage, when the load is powered, not when disconnected): External 3V3 regulators is the way to go.

  Do you also think it is a reliable way of controlling the motors'
  speed?

These are PWM output, so yes, why not? Also, add flyback/freewheeling diodes (and -maybe- 100nF polyester caps should help) between the motors terminals.


Can a MEMS accelerometer sensor be used as a shock sensor? I am trying to make an IOT project- SMART DOOR where I have used a serve motor and NodeMcu and for adding further functionality I have been thinking of adding a theft detection feature where whenever a large force is applied on the lock an alarm starts beeping and for that I don't have a shock sensor but I do have MEMS accelerometer sensor(MPU6050 Accelerometer and Gyroscope).
So can I use it to add this functionality?
If yes, can I get a little guide on what configuration and sensitivity I should use?

THANK YOU!

Sure you can. A "shock" is merely a large amount of acceleration over a short period of time.

You would probably want to set the MPU6050 to its least sensitive setting (±16g), and you might even be able to make use of the "tap" function whereby the MPU6050 itself looks for a sudden short sharp shock to trigger an interrupt (though that may be a little too sensitive for your needs, I don't know).


Multiple 7 segment displays blinking i just set up 2 displays ( 3 digit 7 segments ), and the displays seems to be blinkin ( i know they are suppose to blink but so fast that the human eye cannot detect it ).

I'm using the SevSeg Library and this is how my code looks:

void setup() {

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

   byte digitPins2[] = {14, 15, 16};
   byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};
   sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);

}

void loop() {

  while(true){
     sevseg1.setNumber(number,0);
     sevseg2.setNumber(number,1);
     sevseg1.refreshDisplay();
     sevseg2.refreshDisplay();
  }
}

I need to add 2 more 3 digits 7 segment displays so i was wondering what is it that is causing the blinking.

Im using Arduino Mega.

First of all, you have a while(true) in your loop, that makes no sense. The loop already loops for ever.

You are also changing the number every time the loop() is run, making it flicker. If you follow the Arduino library example, you can see they only use setNumber every so often and use refreshDisplay every time the code runs through the loop().

Also, you didn't setBrightness, which shouldn't be a problem since the library probably sets a default value, but I'd advise on including it in your code to eliminate unforeseen problems.

Try this code and let me know if it works:

#include "SevSeg.h"

SevSeg sevseg1; //Instantiate a seven segment controller object
SevSeg sevseg2;

void setup() {
  byte numDigits = 4;
  byte digitPins1[] = {2, 3, 4, 5};
  byte segmentPins1[] = {6, 7, 8, 9, 10, 11, 12, 13};
  byte digitPins2[] = {14, 15, 16};
  byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};

  sevseg1.begin(COMMON_ANODE, numDigits, digitPins1, segmentPins1);
  sevseg1.setBrightness(90);

  sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);
  sevseg2.setBrightness(90);
}

void loop() {
  static unsigned long timer = millis();
  static int deciSeconds = 0;

  if (millis() >= timer) {
    deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond
    timer += 100;
    if (deciSeconds == 10000) { // Reset to 0 after counting for 1000 seconds.
      deciSeconds=0;
    }
    sevseg1.setNumber(deciSeconds, 1);
    sevseg2.setNumber(deciSeconds, 1);
  }

  sevseg1.refreshDisplay(); // Must run repeatedly
  sevseg2.refreshDisplay(); // Must run repeatedly
}


How do you change the state of an image on a TFT display when the associated pin changes state? I just recently resolved my problem on getting images to load on to my TFT display via the SD card. Thanks to UTFT_SdRaw!!! it's by far the easiest to use. For a novice like me, its been a real feat. Now translating the code, I am trying to turn on and off the image when the pin state changes:

Example:
When pin A2 on my MEGA goes high (+5vdc) I want my SD to spool up and load an image so here is my code snipit:

****myFiles.load(20, 55, 130, 130, "Power Medium.raw");****

So now when the pin state changes back to low (0vdc), how do I remove the image without clearing the entire screen? The image seems to stay frozen instead of disappearing when the pin voltage falls away.

Any ideas? I am stumped. Thanks in advance for any comments and suggestions that may help me over the hump.

It's quite silmple: just draw a box over the image the same colour as the background.

Either that or draw a different image over the top of the existing image.


How to change wifi credentials of multiple ESP8266 together I need to change WiFi credentials of multiple ESP8266 in one go, without needing to change passwords for each of them individually. I know there is a WiFiManager library, which makes your ESP8266 access point when not connected to any network, but that will require me configure each of them individually.

How can I save the fatigue of changing their wifi credentials individually? All of them needs to connect to the same network, whose password is recently changed.

you can reconfigure your router, or whatever network mode you are using, with auto-login to the MAC addresses of your ESPs.
And then if you provide the MACs of the corresponding ESPs, and change your WiFi credentials, then you don't need to configure the ESPs individually. It will auto-connect itself.


Error code 10 for arduino device driver How can I fix error code 10 while installing the device driver for Arduino in Windows 8.1?
The LED on the board is blinking after connecting it to the laptop, so I don't think so that the board is damaged. What is the cause of this issue?

First of all, test if you even need a new driver. On Windows, the Arduino drivers for my Uno and my Mega were installed automatically by Windows. I'd advise to restart your computer, using the actual restart button, not manually shutting off and turning on... this is very important with Windows 8.1 and its Hybrid Boot default!!! A normal reboot doesn't fully reload all of the drivers. Next, open the Arduino IDE, and then see if you can successfully upload the "blink" example sketch.

If that doesn't work, let's try something else.

First of all, open up Device Manager and find your device:

It should be under the Ports (COM & LPT) section. After that, right click and click on Properties.

Then, let's go to the Driver tab and click on Update Driver. Then, click on Search Online Automatically for this Driver.

First, try seeing if an automatic update finds any drivers capable. If not, I've found previously that there's sometimes a Reinstall or Fix button somewhere if the driver isn't working correctly.

In addition, you can also update it manually using Device Manager. Instead of clicking on Search Online Automatically for this Driver, click Browse My Computer Manually. For me, there was a Mega driver under the Let me pick from a list of compatible device drivers on my computer and there was a Mega driver for me (although I don't know if that's because I have it installed already).

You can also use that same menu to point it to the location of the installation of the Arduino IDE and it will search for any compatible drivers.

Rolling back the driver is another option if the Arduino IDE tried to install a faulty driver that somehow got corrupt over a working driver installed by the computer.

The last thing I would suggest trying as a last resort is using the Uninstall Driver button and then trying to reinstall the driver manually. I've never done this with an Arduino board, although there have been some times with other drivers that this has helped to remove the faulty driver.

If none of this works, it may be a faulty board.


LED matrix appears dead I recently purchased a 1.2 8x8 yellow matrix from Adafruit, along with a HT16K33 backpack for it. I joined the matrix and the backpack, connected everything to the arduino, followed the instructions on the site and got it to work. During animation certain rows would not light up and upon later examination I realized that I had to solder up the pins to the backpack because some pins would not completely make contact with the backpack. After soldering the matrix to the backpack, I fired up arduino and uploaded the matrix8x8 sketch that comes with the library to test the matrix and nothing happens.

I don't have a multimeter yet, but tried to check whether electricity is reaching the backpack which turns out to be true. (used a led and connected it to both + and -, and data and clock pins on the backpack.) in both cases the led lights up.

How can I check the health of the backpack and/or matrix?

I hate to say it, but a multimeter would really come in handy for you.  Harbor Freight has some for under $10.

That said, without knowing anything specific about what you are using, you could try using the same LED you used to test power and put it in parallel with one of the LEDs on the matrix.  I'm guessing you don't have power at the LEDs though because it seems unlikely that all the LEDs would fail.  Check your solder work and make sure you have not shorted anything.  Also, you could have overheated a component when soldering causing it to fail.  Good luck.


Mouser/DigiKey part number for female "stacking" headers? Adafruit has this wonderful product: http://www.adafruit.com/products/85

What are these actually called? I've looked all over the place in Mouser and DigiKey and can't find them (now, granted, it's impossible to find anything in DigiKey since they discontinued their printed catalog, but I'm digressing...)

They are great for putting other things that are on breakout boards on a tightly-packed breadboard and still be able to attach probes.

Also, sometimes, the board you are trying to attach is this:

As you can see, there is a dip switch blocking the 8-pin header. This is fine for its final resting place (on a board with a socket), but putting it on a breadboard is a bit of a pain. I have quite a few of those, so even though the aforementioned adafruit part is pretty cheap and I could get a bunch, I'd rather know what the real part is called so I can get the sizes I need.

PS: In case you are wondering, and you like old-style nixie tubes, that's http://www.tayloredge.com/storefront/SmartNixie/DataSheets/Datasheet_SmartNixie.pdf.)

They're actually called "Wire-Wrap Headers" and they pre-date the Arduino probably by at least 50 years or so.

They used to be used to create circuits between chips and components by wrapping wire around the pins and routing it to other connectors:

They have since been adopted as stackable headers on boards like the Arduino shields.

Being such old technology not many people make them any more, though thanks to their popularity on things like the Arduino they are starting to appear more and more from normal electronics supply companies.


Attach Interrupt problem I'm just learning how to use the Arduino Uno and I'm trying to control the speed of an AC fan. I made a sketch of this project on proteus but the triac seems not to be responding. I guess there's a problem with the attachInterrupt part of the code. Here's the code:

#define triacPulse 5
#define interruptPin 2

//button event
#define button1 6

void setup() {
  // put your setup code here, to run once:
  pinMode(button1, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(button1==HIGH){
    attachInterrupt(0, triacControl, FALLING);
  }
}

void triacControl()
{
  delay(5);   //delay for 5 milliseconds
  digitalWrite(triacPulse, HIGH);
  delay(5);

  digitalWrite(triacPulse, LOW);
}

Thanks for the answer in advance

First of all your if statement will always be false. You ask if 6 equals 1 (from arduino.h).
It schould be digitalRead(button1) == HIGH. Also it looks like your button should start an impulse of 5ms. Am I right?
In this case you will attach the Interrupt to the Button. Also don't put delays in the Interrupt function. Another thing, that isn't important in small Projects only for you, is to increase the readability by typing "define constants" uppercase, so you know where to find them and that they aren't changeable variables (For this reason HIGH, LOW, INPUT, RISING, ... are all uppercase).

All in all the code should be look like this:

#define BUTTON1PIN          6
#define TRIACPIN            5
#define TRIACPULSE          5                       // [ms]

bool doPulse = false;
long triacStartTime = 0;

void setup(){
  pinMode(BUTTON1PIN, INPUT);
  pinMode(TRIACPIN, OUTPUT);
  attachInterrupt(BUTTON1PIN, pulseISR, RISING);    // attach a Interrupt once!
                                                    // pulseISR is called everytime the button is pressed
                                                    // ISR: Interrupt service Routine (only for Readability)
}

void loop(){
  if(doPulse){
    digitalWrite(TRIACPIN, HIGH);
    triacStartTime = millis();
    doPulse = false;
  }
  if(millis() > triacStartTime + TRIACPULSE){        // Shut down after 5 ms
    digitalWrite(TRIACPIN, LOW);
  }
}

void pulseISR(){
  doPulse = true;                                    // NO delays in ISR! And as short as possible
}


File include error while using Arduino Nano I am using the code below to interface the Arduino nano and android cell phone to enable serial communication through the USB port. I downloaded the filter library from GitHub https://github.com/JonHub/Filters

I am getting an error saying thet the library is not found.
I would really appreciate some suggestions on this.

Here is my code:

 //This code is for arduino communicating to android phone through USb serial port.
 //For arduino nano

 #include <Filters.h>   //implements digital filters which mimic the analog filter, keep track of variable statistics in realtime

char data_read; //character datatype takes up to 1 byte of memory
unsigned int analog_out;
unsigned long time;
float filterFrequency = 10.0;
FilterOnePole lowpassFilter( LOWPASS, filterFrequency );//implements digital RC type filter; both highpass and lowpass

 void setup()
 {
  Serial.begin(115200); //open the serial port and set the baud rate for communication
  // create a one pole (RC) lowpass filter

 }
 void loop()
 {
 }

 void serialEvent() { //Used when data is unavailable yet
 if (Serial.available()) //checks the number of bytes available for reading from the serial port
 {
data_read = Serial.read();

if (data_read == '0') {
  Serial.print("#");

  //Serial.print("10100");
  analog_out = lowpassFilter.input( analogRead(0) );
  Serial.print(analog_out + 10000);

  Serial.print(":");

  //Serial.print("20200");
  analog_out = lowpassFilter.input( analogRead(1) );
  Serial.print(analog_out + 20000);

  Serial.print(":");

  //Serial.print("30300");
  analog_out = lowpassFilter.input( analogRead(2) );
  Serial.print(analog_out + 30000);

  Serial.print("p");
}
/*if(data_read == '0' || data_read == '1' || data_read == '2' || data_read == '3' || data_read == '4' || data_read == '5'){
  analog_out = lowpassFilter.input( analogRead( data_read-48 ) );
  Serial.print((analog_out)+(data_read-48)*10000);
  Serial.print(":");
  }else if(data_read =='p'){
  Serial.print("p");
  }*/
   }
 }

Here is my error message:

  Arduino: 1.8.5 (Windows 10), Board: "Arduino Nano, ATmega328P"

  C:\Users\daphn\Documents\Arduino\Analog_Serial_out\Analog_Serial_out.ino:4:129: fatal error: Filters.h: No such file or directory

  #include <Filters.h>   //implements digital filters which mimic the analog filter, keep track of variable statistics in realtime

                                                                                ^

  compilation terminated.

  exit status 1
  Error compiling for board Arduino Nano.

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

You have to put the folder with the library files in the folder libraries under your sketchbook folder. Then the IDE should be able to find them.

I think there is also a possibility to save them in the same folder as your .ino file, but it I don't know how exactly you have to do this.


I need to generate a programmable pulse inside an ISR I have an application that requires that I generate an output pulse whose width is calculated in the main loop. The pulse has to be triggered by an interrupt and I understand that "delay" won't work inside the ISR. I can't use a polling technique because of the requirement to use serial writes in the main loop.

Any ideas or suggestions will be most appreciated.
Thx

you can use delayMicroseconds() inside the ISR if you really need to. It is not usually the best practice to delay inside an ISR, and there may be a cleaner way to accomplish what you need but without some background of what the signal is and what its used for this is your best bet.


Can I use a camera sensor from a not functioning smartphone in Arduino or Raspberry pi? I want to use the OmniVision_OV16860 camera sensor from a not functioning Moto G4 plus phone to capture pictures using Arduino or Raspberry Pi.

Is it possible to do that? If yes, explain the whole process.

Is it possible to ... use the OmniVision_OV16860 camera sensor (on an)
  Arduino?

It is doubtful as bare image sensors usually require specialized software drivers to be of any use. Also, a common Arduino does not have the power to do image processing.  Only the few Arduino's built with unusually powerful processors could handle image processing.  But, at this level, expect little support as most do not do image processing on the Arduino platform.


A good water flow meter to monitor home usage with Arduino I'm searching for a good water flow meter to add to my home controller project with Arduino. I have been searching in several pages and I only found some devices that work for low flow.  I need to control the water usage in my home and I thought to add a flow meter at the point where the water enters my home, and view the data with Arduino.

Do you have experience with any flow meter with good quality?

I've used an arduino with an irrigation flow meter.

I think I'm getting accurate results, but I haven't checked against a bill. It can handle high flow, and the sensors will attach to any size pvc line. The sensor are a bit expensive, however. $150 for the sensor and $35 for the T junction that it plugs into.

However, as you are living in an apartment, you'll probably need a non-invasive sensor. Perhaps an acoustic one.


System Is not Functioning Error. Windows XP, Arduino Uno R3, C# Listen SerialPort Can anyone help me with this issue.

We created an arduino project. We listen microswitch.
If switch click, Arduino send basic serial data.
And C# application read serial port.

This solution is working but after more times (3Hours, 5Hours,..) system stoped.
Error message is "a device attached to the system is not functioning"
Solution: Usb remove and retry plug system is going to running.

We are try putty.exe maybe problem C# project but don't working.

If microswitch click don't flash "TX" or "RX" led.

const int button = 3;

uint64_t bounceTime = 50;
uint64_t holdTime = 250;
uint64_t doubleTime = 500;

uint64_t lastReading = LOW;
uint64_t hold = 0;
uint64_t single = 0;

uint64_t onTime = 0;
uint64_t lastSwitchTime = 0;

void setup() {
 pinMode(button, INPUT_PULLUP);
 Serial.begin(9600);
}

void loop() {

 int reading = digitalRead(button);

 if (reading == HIGH && lastReading == LOW) {
   onTime = millis();
 }

 if (reading == HIGH && lastReading == HIGH) {
   if ((millis() - onTime) > holdTime) {
     hold = 1;
   }
 }

 if (reading == LOW && lastReading == HIGH) {
   if (((millis() - onTime) > bounceTime) && hold != 1) {
     onRelease();
   }
   if (hold == 1) {
      delay(5000);
      reading = digitalRead(button);
      if(reading==LOW){
              Serial.println("B");
      }
     hold = 0;
   }
 }
 lastReading = reading;

 if (single == 1 && (millis() - lastSwitchTime) > doubleTime) {
   single = 0;
 }

}

void onRelease() {
 if ((millis() - lastSwitchTime) >= doubleTime) {
   single = 1;
   lastSwitchTime = millis();
   return;
 }

 if ((millis() - lastSwitchTime) < doubleTime) {
   single = 0;
   lastSwitchTime = millis();
 }

}

I assume that by "USB" you mean "USB-to-serial adaptor".

Try running the same code without any serial communications, just have an LED do the equivalent of printing, and power it from a good power supply. If it runs for more than five hours, the problem is with the USB adaptor and/or your PC (Windows XP? Really?), and hence not relevant to this forum.

If the code crashes, then maybe you have a marginal board, or there is some other environmental factor that's giving you trouble. The code looks OK on first glance.