How to connect an Arduino and a WAMP server's MySQL database?

As gre_gor pointed out, it looks like your connecting to the wrong ip.

Change:

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

To:

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


An I2C bus can be connected to many slaves at the same time, since in the I2C protocol every slave has an address.

But, as Majenko wrote in the comments, the library for the PS2 controller doesn't use I2C. The communication with the controller is bit banged, meaning that every part of the communication is done by software. This can be done with every digital pin on the Arduino. In your setup you have to usw the function ps2x.config_gamepad().  In it's parameters you can set the pins that the library will use.


Connect my Arduinos to central server, despite different IP adresses

Your problem is two-fold, and neither are easy for an Arduino to overcome.

First you have the problem that the router's internet-facing IP address is (unless you have a special arrangement with your ISP) liable to change at any time. You need to keep your sever up to date at all times with what that IP address is, and the only real way of doing that is for the router, or something behind the router, to connect with your server so it can update its IP address.

Secondly you have the port forwarding. The router has to know where to forward the port to. That means that either the IP address of the Arduino has to be static, or the Arduino has to somehow tell the router to do the port forwarding.  The simplest method is just to allocate a static IP address as you have done. The alternative is to use UPnP to instruct the router "I need you to forward this port through to me" - assuming the router understands UPnP. The hardest part of that though is getting the Arduino to speak UPnP. I am not aware of any UPnP libraries for the Arduino.

So keep the static IP address for the Arduino, it is simplest. One thing to note with manually allocating an IP address though is that it is vitally important you allocate it outside the IP address range of the DHCP server. Otherwise it is possible that the DHCP server could then allocate the IP address to someone else, and you'd then get a conflict. Most routers allow you to choose the range of IP addresses so you may want to go in and check that the DHCP server isn't able to clobber the IP address you have chosen.

To help solve the first problem some routers provide a "DDNS" (Dynamic DNS) facility, whereby they will periodically connect to a DDNS service to update a DNS record with the public IP address of the router. Not all provide it and those that do usually only provide access to a couple of DDNS services, so check your router to see if it does support it and if there is a suitable one for your needs there. If there is you can configure that and then, instead of connecting to the IP address of your router for issuing commands you instead connect to the DDNS domain name allocated to your router.

However, there is one much simpler option that solves all the problems in one go: reverse the communications.

Instead of the server connecting to the router to forward the port through to the Arduino to issue a command, it is far simpler (though I will admit not as responsive) for the Arduino, from whatever IP address it happens to be on, to just connect to the server itself and ask it for any pending commands.

If you have the ability to run your own software on the server you could even create your own small TCP server which the Arduino connects permanently to. The server can then send commands down that TCP connection just as if you were working with an Arduino directly connected by serial.

In both those situations it doesn't matter what IP address your router is on. You don't need to do any port forwarding. The Arduino can be on any IP address on your network.

And further more you have more security - no one could connect to your Arduino through the internet and cause havoc.


Can I switch from Arduino IDE to Atmel studio or Visual Micro but still use Arduino library?

At the end of the day, an Arduino library and the Arduino core are just files full of code.

There is nothing to stop you creating a project in Atmel studio (or wherever) and importing all those files into your project.

You will need all the core files (hardware/arduino/core/arduino/*) plus all the files for the libraries you want to use.


Correct solution for "multiple definition of" compile error

You have an old copy of the sha256 files lingering in the build folder. These will have been output at some point in the past and never been cleaned up since they have been deleted from the IDE.

It is probably a bug in the IDE that doesn't remove the old files.

Restarting the IDE will cure the problem and allow you to compile.


A class within a class - via an Initialiser Lists: NOT able to update a variable

Even without the real code, I think the problem is with the function First::Second().

You need to understand what happens in C++ when values are passed as parameters.  The are passed by value by default, this means a COPY of the value is passed into the function, you can modify the parameter all you like but when you return those changes are lost.

There are two exceptions to this, the first is pointers.  When you pass in a pointer you can modify what is pointed to but you still can't modify the pointer, because that is a copy.  If you want to modify the pointer then you need a pointer to a pointer int** ptr_to_ptr.

The other exception is a reference.  In this case the function can modify the parent function's variable.  This is more efficient in terms of memory.

So you have:

int AddOne(int value) {++value; return value};   // 5 == AddOne(5);
int AddOne (int value) {return value+1};         // 6 == AddOne(5); - doesn't modify the parameter.
int AddOne(int* pValue) {(*value)+1; return *value;}//6 == AddOne(5); - Pointer
int AddOne(int& value){++value; return value;}   // 6 == AddOne(5); - Referance
int AddOne(const int& value){++value; return value;} // Compiler error, modifying const value.

So why it is First::Second() causing the problem?  Well the same rules apply to return values as to parameters and you are returning a copy of the value widget so you then modify that copy and then dispose of it.  So this is what you need to fix the problem.

Second& First::getSecond()
{
    return widget;
}

EDIT : Its not clear in the preceding text but you don't need getSecond() to return a reference if you are not altering the value of widget so getDouble() will return the expected value because it is working form a copy of the original and not storing any changes.  However update() will not work as expected because the result of getSecond() goes out of scope (gets disposed of) once the call is complete.  The changes its made are not save to the original because it is working on a copy.


how do you capture the top value in a fallen edge in analogs data (flex sensor)

I suggest you consider as “top value of the falling edge” the maximum of
the values you have read during a specified time window before the edge
is detected. This means you have to compute the maximum at the time you
detect the edge. If you instead continuously compute a running maximum,
then you are going to get a global maximum. Amended source:

bool loaded = false;
int threshold = 760;
int index = 0 ;
const int values_size = 4;  // this controls the time window
int values[values_size];

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

void loop() {
  int data = analogRead(A0);

  if (loaded) {
    // Store the reading.
    values[index] = data;
    index = (index + 1) % values_size;

    // Detect falling edge.
    if (data < threshold) {
      loaded = false;

      // Find the max.
      int _max = 0;
      for (int i = 0; i < values_size; i++) {
        if (values[i] > _max) _max = values[i];
        values[i] = 0;  // clear, for next time
      }

      // Report it.
      Serial.flush();
      Serial.print('a');
      Serial.print(',');
      Serial.print(_max);
      Serial.println();
      delay(300);
    }
  }

  // Detect rising edge.
  else if (!loaded && data > threshold) {
    loaded = true;
  }
  delay(20);
}

Notice the line values[i] = 0;. It is intended to avoid the reading of
one falling edge being seen on the next one.


Arduino Serial Monitor works but not on PySerial and PuTTY

I wrote a python application which communicated with an arduino and for some reason I had to insert a delay after opening the serial for it to work correctly, if I didn't the first data I sent would always get dropped. Perhaps that's what's occuring here? Setting the attributes of the serial connection like that is probably slower than doing it in initialisation.

For myself I found that a delay of 3 seconds was what I needed for it to work 100% correctly on all computers (on some a second was enough). You only had to wait after opening it once open it worked fine.

To do a delay import the time module and use the sleep function which takes an argument of seconds.

import time

time.sleep(3)

Also worth noting depending on your application it's worth setting a timeout value for the serial that's appropriate or just keeping it open with the timeout paramter.

 ser = serial.Serial(com, 115200, timeout=0)

If you do this make sure to close it when you finished with it though (I personally used a try finally block which makes sure its always closed).

try:
  ser = serial.Serial(com, 115200, timeout=0)
  #go nuts with whatever communicating your doing
finally:
  ser.close()

I'm afraid I can't really tell you what caused the issue though. I also realise that this question is quite old so I hope my answer is still helpful, if not to you then to someone else who stumbles across it. To note for future the people on the official Arduino forum may be of more help for arduino related questions in general.


Arduino Due: Interrupt-based ADC hangs processing

In your interrupt handler, ADC_Handler(), you set sample_buffer_full when the buffer is full.  I don't see anywhere in the code where  sample_buffer_full ever gets reset (cleared) once it's been set.

While sample_buffer_full is set, it disables the body of the interrupt handler – ie, the handler's structure is

if (!sample_buffer_full) { ...body of handler... }

– and in particular, prevents adc_get_latest_value(ADC); from occurring.  The source code of adc_get_latest_value(); is like

uint32_t adc_get_latest_value(const Adc *p_adc) {
  return p_adc->ADC_LCDR;
}

which accesses the ADC data register.  According to section 43.6.4 Conversion Results on page 1322 of the data sheet, Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf,

  The channel EOC bit in the Status Register (ADC_SR) is set and the DRDY is set. In the case of a connected PDC channel, DRDY rising triggers a data transfer request. In any case, either EOC and DRDY can trigger an
  interrupt.

  Reading one of the ADC_CDR registers clears the corresponding EOC bit. Reading ADC_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.

It appears to me that your code enables interrupts, fills a buffer, sets sample_buffer_full, then spins in ADC_Handler().  That is, repeatedly executes ADC_Handler() without clearing the EOC bit.

Note, for  oscilloscope applications with a Due, I suggest using DMA buffers instead of one interrupt per conversion.  See thread #137635, speed of analogRead, in forum.arduino.cc for DMA code to read one or two analog channels on a Due at one sample per microsecond.  Also see edaboard.com/thread283843 and forum.arduino.cc #186169

Edit note: Although sample_buffer_full does get reset, that reset happens after a time-consuming for-loop.  Whether it takes some hundreds of microseconds or a few milliseconds, the for-loop is enough of a delay that at least one more conversion and interrupt will occur before sample_buffer_full gets cleared.  One unhandled conversion is enough to lock up the interrupt handler.  Here are some alternative approaches to consider:

• Use a circular buffer, and never stop filling it.  This is ok if you are only interested in the most recent data, rather than a complete waveform record.

• Set or reset sample_buffer_full as now; and remove the initial if test from the handler.  Instead, put an if before sample_buffer_idx++;, to not increment if the buffer is full.

• Turn off ADC's freerun mode.  This is a reasonable thing to do when not taking data.

• Turn off ADC's interrupt when not taking data.  Also reasonable.

• Use multiple buffers.  Reasonable, but by itself doesn't avoid the problem.

• Read the latest value every time the handler executes [for example, say int datum = adc_get_latest_value(ADC); as the first statement in the handler] and then only store that value in certain cases.  An easy and effective way to avoid problem.


Is the strange problem I'm having to do with comparing floats?

You already know, from previous answers, why the comparison doesn't give
you the result you expect: you assumed that any multiple of 0.1 is also
a multiple of 0.001, which is true for real numbers but nor for floats.

To fix the issue, it has been suggested to you to allow for some
fussiness in the comparison. I would suggest a different approach: keep
your comparisons as they are, and instead change the way the speed is
updated in the ISR:

if (motorSpeed < targetSpeed) {
    motorSpeed = min(motorSpeed + speedIncrement, targetSpeed);
}
else if (motorSpeed > targetSpeed) {
    motorSpeed = max(motorSpeed - speedIncrement, targetSpeed);
}

With this logic, motorSpeed will always end up being exactly equal
to targetSpeed, irrespective of whether the speed change is a multiple
of the increment or not.

A common misconception about floating point numbers has it that they are
not exact. Truth is, most floating point calculations involve rounding
errors, but the floating point numbers themselves are exact numbers,
if not the numbers you expect¹. Then, when you do the assignment

motorSpeed = targetSpeed;

which the code above ends up doing at some point, you can test

if (motorSpeed == targetSpeed) ...

and it will be true.

¹ When you write “0.1” in the source code, you get the float which is
closest to 0.1, which happens to be 0.100000001490116119384765625
exactly.


I²C between 2 Arduinos sends additional receive event

Your code has several issues:

For the master:

Your I2C transactions should be quick and not delayed with Serial.print()s like in getFromState()
You requested 2 bytes from the slave but you are reading only one from the buffer. Wire.flush() flushes the outgoing buffer, not the receive buffer. Use while (Wire.read() != -1); instead.
Its also advised that you use Wire.available() to iterate through the receive buffer when read()ing; its how you check if anything was received at all and how many bytes were received.
After using requestFrom(), you shouldn't call endTransmission(). Its self-contained.

For the slave:

You should never call Serial.print() or delay() in requestEvent() or receiveEvent(); both functions are called from within ISRs and ISRs are meant to execute quickly and return.
You are requesting 2 bytes from the slave in your master code, whereas your slave's requestEvent() writes only one byte.
In receiveEvent(), again its best to use either Wire.available() to iterate through the RX buffer or you use the variable amount. This way, you read everything in the buffer; you can also flush the RX buffer like I showed you before.

Finally those delays are rather long; 10ms would do, if they are even needed at all.


How do I detect the Computer's operating system?

If you can't get the OS from the USB port, why not use the existing keys/inputs to set the mode on startup? That is, if you tell the user to press different combinations of 2 buttons on startup, you have 4 (2 bits => 4 values) different paths on startup:

00 => Normal startup, don't change mode
01 => OS 1
10 => OS 2
11 => OS 3


It is not clear, what the code actually should do (what behaviour you are trying to achieve), so I will only look into the obvious programming problems.

The following declarations at the global scope seem to be pin numbers:

int x = 45;
int y = 47;
int z = 41;
int w = 43;

int WaterIn =  40;
int WaterOut = 42;

int Pump1 = 25;
int Pump2 = 24;
int Pump3 = 27;

But in the Valves() function yout treat them as they were representing the value of that pins. That is not the case. If you want to read the state of a pin, you cannot do

if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))

You are just comparing the pin number with HIGH, which is defined as 1. That cannot work. You have to actually read the pin using it's pin number, which looks like this:

if( digitalRead(x) == HIGH && digitalRead(y) == HIGH && digitalRead(z) == HIGH && digitalRead(w) == HIGH)

And that can be shortened to:

if( digitalRead(x) && digitalRead(y) && digitalRead(z) && digitalRead(w) )

Inside of the mentioned if statements you set a variable multiple times without doing anything with it. Any consecutive write to this variable will overwrite the previous value. After the code block

pinToTurnHigh = WaterIn;
pinToTurnHigh = Pump1;
pinToTurnHigh = Pump2;
pinToTurnHigh = Pump3;

The variable pinToTurnHigh is 27 (Pump3). The values, that you assigned right before that line, are lost. You actually have to do something with the variable, or the first 3 lines of that block makes no sense.
In most cases it is not a good idea, to use variables with changing values to handle pin numbers, since that will make the code difficult to understand. The circuitry is mostly hardwired, it will not change. So there is no need to assign pin numbers to a changing variable. Instead you can directly do, what you need to do with a constant pin number. (Actually the code optimizer, that comes with the compiler, can optimize the not-changing pin-number variables out, so that you wrote them in your code, but the actually code might not have them.) Here it seems, that you want to write a HIGH value to all the mentioned pins. You can do that directly:

digitalWrite(WaterIn, HIGH);
digitalWrite(Pump1, HIGH);
digitalWrite(Pump2, HIGH);
digitalWrite(Pump3, HIGH);

Here it is important to understand, that digitalWrite() is only working on 1 single pin at a time. If you want to set multiple pins with it, you have to call it multiple times with the according pin numbers.
Now the timing of your code: The Calendar() function will block the rest of the code for about 4s, because you used that much of delay(). During that time the Arduino cannot react to anything. The switches will not do anything either (since the Arduino is busy waiting in the delay() instead of checking the switches). The code, that is called after the Calendar() function, contains no delay()s, so it will run very fast. In the Valves() function you first reset all the pumps and valves to LOW. Then you write HIGH to one pin (as mentioned above I assume, that you wanted to write them all on condition). After that the program will go back to the loop() function and execute the resetAllPumpValve() function again, which will set all the outputs to LOW.

All in all that means, that the Arduino is fiddling thumbs inside the Calendar() function, without doing anything else. Then he will reset, set and reset the pins again. Since there is not timing code in there, this will happen very fast. So the pins have to be LOW most of the time and being turned on about every 4s for a tiny amount of time (a low number of milliseconds, since that is about the time to execute digitalWrite() or it's siblings). The motors or values will hardly have time to move with that.

For solving this you might want to look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It shows a non-blocking coding style, that will only do something, if it is the time to do it. Much like when you bake a pizza. You will not sit in front of the oven and wait patiently, until the pizza is fully baked. You will put it into the oven and regularly (maybe every 5 min) look, if the pizza is ready to eat. In the meantime you would do other things. Thats what is done there by using the millis() function, that will return the number of milliseconds passed since the programs startup. You can look into the example and google about it to learn more. It has been covered numerous times throughout the internet.

That's it for now. To really help you with the logic of the program, you will first have to get these parts right.

Have fun while learning :-)


Upload Code on Arduino Mega using FTDI Cable

FTDI cables usually have RTS which is used to bring Reset low. If you only have four pins, press the Reset button on the board the moment you start the upload.


Can I do parallel processing in Arduino?

You do not need parallel processing or finite-state machines for that:

// Vector with digital pin numbers for LEDs (with resistor to ground)
const int LED_MAX = 5;
const int LED[LED_MAX] = { 2, 3, 4, 5, 6 };

// Vector with analog pin numbers for LDR (with pullup resistor)
const int LDR_MAX = 5;
const int LDR[LDR_MAX] = { A0, A1, A2, A3, A4 };

// Analog value or lower when to light the LED
const int THRESHOLD = 200;

void setup()
{
   // All LED pins should be digital output pins
   for (int i = 0; i < LED_MAX; i++)
     pinMode(LED[i], OUTPUT);
}

void loop()
{
   // Read all LDRs and set LED pins according to threshold
   for (int i = 0; i < LDR_MAX; i++)
     digitalWrite(LED[i], analogRead(LDR[i]) < THRESHOLD);
}

But if you really want to describe this as multiple tasks you could use the Simple Scheduler library:

#include <Scheduler.h>

const int THRESHOLD = 200;

template<int LED> void setup()
{
   pinMode(LED, OUTPUT);
}

template<int LED, int LDR> void loop()
{
   digitalWrite(LED, analogRead(LDR) < THRESHOLD);
   yield();
}

void setup()
{
   Scheduler.start(setup<2>, loop<2, A0>);
   Scheduler.start(setup<3>, loop<3, A1>);
   Scheduler.start(setup<4>, loop<4, A2>);
   Scheduler.start(setup<5>, loop<5, A3>);
   Scheduler.start(setup<6>, loop<6, A4>);
}

void loop()
{
   yield();
}


How to connect arduino with local network

To connect to a network you need a network interface.  This could be an Ethernet interface, a Wifi interface or something that supports TCP/IP.  The easiest way of doing this is with ether an Ethernet 'shield' of a WIFI 'shield'.

In either case there are a range of options, from full shields to smaller boards that connect via jumper wires.  One important consideration is the longer the wires the more chance for signal degradation and loss of comms.  So direct plug in boards are probably better.

Probably the easiest way to do it is to use a ESP8266-??, but using an ESP as a network interface is like only using your PC for email.  The ESP is faster and has more memory than the Arduino, so it would be better to program that as the web-server and get the Arduino to feed it the data.

You could use Bluetooth, radio, etc, but that's just making life hard for yourself.

You could also look at the Arduinos that have networking built in.


How to find out the maximum used stack space?

Knowing the stack size is pretty easy: the stack pointer is initially
set to RAMEND and goes down as the stack grows. Thus:

static inline size_t stack_size()
{
    return RAMEND - SP;
}

  should I add this in 'strategic' locations [...]

Obviously, the result will depend on where this is evaluated. Ideally
you should test this in the deepest parts of your call chain, as this is
where the stack will be at its maximum size. Note that ISRs stack on top
of all your regular code.

Edit: There is no easy way to know the maximum stack size. You
could get an approximation by sampling the stack at regular intervals,
e.g.:

#include <util/atomic.h>

volatile size_t min_sp = RAMEND;

ISR(TIMER0_COMPA_vect)
{
    if (SP < min_sp)
        min_sp = SP;
}

static inline size_t max_stack_size()
{
    size_t min_sp_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        min_sp_copy = min_sp;
    }
    return RAMEND - min_sp_copy;
}

If you enable TIMER0_COMPA interrupt in setup():

TIMSK0 |= _BV(OCIE0A);

then the stack size will be sampled every 1.024 ms. Note, however,
that this ISR is itself using some stack space for its own purposes
(9 bytes in my experiment), and that this is not sampling other
ISRs or critical sections.


Change the baud rate to 57600, it specifies at:
    Serial.begin(57600);


Controlling a servo motor with two arduinos?

You can't just connect random pins together like that. Connecting two output pins together is a recipe for disaster. Best case scenario: nothing works. Worst case scenario: you break one or both Arduinos.

Only one Arduino can control a servo. If you want a second Arduino to make something happen to the servo you have to make it tell the Arduino that is controlling the servo that something should happen.

That could be a simple output of the second Arduino connected to an input of the first Arduino, in which case it kind of acts like a button. Or you could create some kind of communication channel between them - maybe using a Serial connection, or a Wire (I2C) connection. There's many ways, and which is best depends on how much control one Arduino needs to exert over the other.


I suppose that digital output power from yun is insufficient to drive all four readers - so, you need to add some digital buffers to MOSI, SCK, and RST lines.

74LS07 digital buffer:


Control speed of a dc motor with a 9v battery

You have 3 problems here:

Driver circuit the motor: Since you only want to control the motors speed (not changing it's direction, where you would need a H-bridge like the L298N), a very simply driver circuit is sufficient. It can consist of a bipolar transistor or a MOSFET. The Arduino's digital output pin would set the transistor/MOSFET to conductive or non-conductive, which turns the motor on or off. The motor is connected (through the transistor/MOSFET) with the full supply voltage. For the needed circuit, you can google terms like "transistor as switch" or "MOSFET as switch". That should give you plenty of tutorials.
Controlling the motor speed: Normally the speed of a motor is not controlled through the voltage, since the speed behaves not linear with the voltage. Instead we use PWM (Pulse Width Modulation), where a squarewave voltage with a constant frequency is outputted at the Arduino's pin. To change the motor speed, you change the ratio between ON and OFF time of the pin (called "duty cycle"). So the motor basically get's turned on and off very fast. Since the motor is to slow, to follow the fast change, we are basically giving it small pushes very fast. If you only push half of the time (duty cycle 50%), the motor will run with about half the speed. In Arduino code you use analogWrite(pin_number, x) with x between 0 and 255 to output a PWM wave at the specified pin. Refer to the Arduino documentation for details.
Powering the whole device: First: A 9V block battery is actually like the worst choice for most cases (especially for devices with motors). It has a big series resistance, what means, that it cannot provide much current without dropping the voltage radically. They are meant for low-current devices. Better use multiple AA/AAA batteries in series.

You didn't state, what Arduino you actually use, but from the description, it has to be one of the 3.3V boards, like the Arduino Pro Mini 3.3V version. Most Arduino boards also have a small voltage regulator on them. The input for it is mostly marked with Vin. Please refer to the documentation of your Arduino board, to check, which voltages are suitable for that voltage regulator. If you don't have a voltage regulator on your Arduino or your battery voltage doesn't fit, you have to provide the power through your own external voltage regulator. You should use a switching regulator (far more efficient, than linear regulators), which can provide the needed power (depending on the Arduino and the bluetooth device maybe between 50mA and 300mA, difficult to say generally) plus a bit overhead.

You should then provide the motor with the full battery voltage, especially not through the Arduino's voltage regulator. Motors can draw quite much current. If you draw more current through a regulator, than possible, it will overheat, emergency shutdown or even burn out. If the battery voltage is not suitable, you should use a voltage regulator, that can safely provide the needed current.

Note: Depending on the size of the motor and it's load, you might want to add a flyback diode, that would safely let inductive reverse currents flow to ground, so that the inductive voltage is not piling up in the transistor/MOSFET.


You can set the verbosity level in the Arduino IDE:

File menu
Preferences
Settings tab
"Show verbose output during" => check "upload"
Click OK

Upload again, and note the additional output telling you what is wrong.

It should also point you to this URL, which points out the most occurring issues.

The issue I have most, is that I forget to switch between Micro and Uno board (as I deploy my sketch on both boards).


What is recommended color recognition sensor RGB for different cases?

You have a conceptual error. You don't need n wires to transmite n bits of information. If you use a serial protocol, one wire or two is enough to transmit information of any size: you just send one bit after another.

Just think: you are downloading sketchs in your Arduino thru a cable with only 4 wires ...

Most sensors (and modules) for Arduino use I2C or SPI to transmit commands/information in digital format. You can learn a lot in this tutorial that covers I2C, SPI and USB.

A quick search on Aliexpress show me this APDS-9960 sensor

The sensor provide ambient light and color measurement, proximity detection and non-contact gesture detection. The APDS-9960 has built in UV and IR blocking filters, four separate diodes sensitive to different directions, and an I2C compatible interface.

Pins: VL (optional power to IR LED), GND (Ground), VCC (power to APDS-9960 sensor), SDA (I2C data), SCL (I2C clock), and INT (interrupt). Each APDS-9960 also has a detection range of 4 to 8 inches (10 to 20 cm).

It works with 3.3V.


Uploading a sketch causing an error message in Arduino Uno

On the "Tools" menu choose "Programmer:" and specify AVRISP mkII; be sure that you've also chosen the appropriate "Board:" entry for the Uno.


The word "clone" immediately rings alarm bells.

Firstly, for a "normal" Arduino (like an Uno, etc) the sketch cannot influence whether Windows detects the board or not.  All that is handled by a completely separate chip.

A lot of the cheap clones these days are coming out of China with a really really cheap USB serial adapter chip.  These barely work at the best of times.  Looking at the pictures I have found of your clone (the manufacturer's site is considerably lacking in any information whatsoever) it doesn't look like it's one of those chips, but one never can tell.

If they have followed the reference designs for the Arduino then it will be an Atmel ATMega32U4 (IIRC) chip that deals with the interface to the computer.  That has firmware of its own on it, and if that has become corrupted (very unlikely) or damaged (possible) then it could cause it to not be recognised.  If that is the case the in the former instance (corrupted) you will need to replace the firmware on it. For that you will need either a hardware ICSP programmer or another Arduino.  In the latter instance you're stuffed, since you would need to replace the chip.

As I say that is unlikely.

Instead your problem is most likely actually with either Windows or the USB cable.  You may need to remove and reinstall the Arduino drivers, or try a difference USB cable.  Also try your "Arduino" on another computer.


Next time, select your code and press ctrl-K... Also align your code (indent it well).

However, you don't need help actually as you have plenty of memory left. As as written:

You only use 12% of program storage space. This might seem a lot having such a small sketch, but most of it is because of library usage/framework (such as the digitalWrite call(s).
210 bytes of dynamic memory is also not something to worry. Btw, this is unrelated to the sketch size, but to your use of (global and other) variables.

So unless you know beforehand your sketch will be much bigger, don't change it because of that reason (too less space).

However, there is another reason, to shorten the sketch, and that is because of duplicated code. As you can see, there is in the entire sketch a lot of repetition (or almost repetition), as in:

if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
{
  digitalWrite(7,HIGH); //Enciende la luz stop
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
}

What you can do to improve it is:

Either use a switch statement instead of the if/else statements
Or create a function that incorporates this condition, together with the following item. This solution is in your case the most clear.

What you do is creating a new function:

void setPins(bool condition, int pin7, int pin11, int pin12, int pin10, int pin9)
{
  if (condition)
  {
    digitalWrite(7, pin7);
    digitalWrite(11, pin11);
    digitalWrite(12, pin12);
    digitalWrite(10, pin10);
    digitalWrite(9, pin9);
  }
}

And you call your function with:

setPins(texto == "5", HIGH, LOW, LOW, LOW, LOW);

And the same for all other conditions. I only used 5 as example.


what is the difference between providing 7 volts or 12 volts to arduino uno?

The amount of heat dissipated by the voltage regulator.  The higher the voltage you supply the hotter the regulator will get.


How to send data from firebase php to arduino?

add global variable String data; and in loop()

data = "trash=";
data += Trash;
data += "&distance=";
data += distance;
data += "&temp_f=";
data += temp_f;
data += "&humidity=";
data += humidity;

// build HTTP request
getStr = "POST /upload.php HTTP/1.1\r\n";
getStr += "Content-type: application/x-www-form-urlencoded\r\n";
getStr += "Content-length: ";
getStr += data.length();
getStr += "\r\nHost: gg.com\r\n\r\n";
getStr += data;


LED strips with WS2811 and 12V are the ones with one driver and 3 RGB LEDs on it. These are interconnected so you just can't control less than whole group of three.

If you need individual control, you have to get 5V variant with WS2812.


RFID/NFC (13.56 MHz), is it possible to send raw bytes and receive response?

RFID protocols require either passive or active tags.  Depending on which you use, either the tag or reader regularly transmits pulses.  Check www.rfidreader.com for more info.  https://www.rfidjournal.com provides valuable resources as well.

Many companies invest heavily in developing RFID technology.  You would be well advised not to reinvent wheels without reeeeally deeeeeep pockets.


That depends very much on how delay() was written (and how it will be written in the future!). There are "sleep modes", which will reduce the power consumption of the arduino - these are one of the best way to reduce power consumption. Delay() may or may not activate these. If not, there could be a replacement Delay() function that could do this.

If you want to reduce power, check out http://www.gammon.com.au/power - this is an excellent step-by-step tutorial on how to reduce power consumption from 50mA down to 288 µA


Powering two L298N motor boards with external supply

If your second schematic correctly represents your actual wiring, the problem is that you are connecting the arduino 5V pin (instead of the GND pin) to the L298 GND.

I assume you have also connected the control pins of the motor controllers to Arduino pins?


From Arduino IDE 1.6.10 onward the Arduino IDE compiles all source files in the src subfolder of the sketch and recursively through all folders under the src folder.

Support for compilation of sketch subfolders was added one or two IDE versions before 1.6.10 and was originally not limited to the src folder but a lot of problems were reported by people who had stored separate programs in subfolders of their sketch that caused compilation errors so this feature was restricted to the src subfolder only.

So if you structure a sketch like this:

foo
|_foo.ino
|_src
   |_bar.cpp
   |_bar.h

And use this #include directive in your sketch:

#include "src/bar.h"

it will work fine.

  Almost as if the IDE is completely ignoring the C source files.

Arduino sketches are converted to C++ before being compiled. They are not C. If you want to use C in C++ code you need to wrap it in extern "C" {}

extern "C" {
#include "src/sub1/gadget1.h"
}

  what is the correct/current way of organizing the above project

project
|_project.ino
|_types.h
|_src
   |_sub1
   |  |_gadget1.c
   |  |_gadget1.h
   |  |_gadget2.c
   |  |_gadget2.h
   |_blarg
      |_foobar.c
      |_foobar.h


What is the execution context of the function registered via the Wire.onReceive() method?

Looking at twi.c in the Arduino libraries, it seems the callback function is called from within the I2C interrupt service routine (ISR). Any code in the call back will lengthen the ISR so it will have to be short. I don't think Serial.write will be too much of a problem; the TX interrupt will be delayed to the end of the I2C ISR which finishes straight after the callback and the Serial.write function is fairly short.

If you need to have a longer function run, you could instead have the callback store bytes in a ring buffer, then check for any available bytes in the main loop().. but this is what the Wire class helps with already.


How I can send data information without work WiFi to LCD?

Blynk.connected() returns true when hardware is connected to Blynk Server, so you can guard Blynk code with
if( Blynk.connected() ){
  // do Blynk things here
}

// Update the LCD anywhere outside of the above "if" statement.


lcd.clear doesn't work with Serial.begin(9600) on Arduino Mega 2560

Pins 0 and 1 are the hardware serial pins on the Mega.  If you're going to use Serial, then you can't connect your LCD to those pins or it won't work.  Even if you are only connected to Serial through the USB, pins 0 and 1 are still acting as Tx and Rx.


Encoder coupled with motor shaft.Encoder is giving larger redings than expected

I guess this is a kind of debouncing problem, caused by noise on the interrupt pin. The behaviour might also get worsened by the disalignment you mentioned. You could verify this by manually rotating the shaft, even though you "get the blinks" I doubt they are accurate in count.

If that is the case there are two things you could do:

add a capacity or a RC filter to the interrupt pin to smoothen out voltage peaks if there are some. This will decrease the chance that the interrupt gets triggered accidentially (and will not solve the problem), but as a low pass it also limits the maximum count rate you are able to detect.
implement debouncing in software. This is usually done by ignoring the input signal for a specific amount of time ("deadtime") after an interrupt has occured. As you are expecting a periodic signal and debouncing behaviour might be different at different speed it could be a good idea to capture the time span between two "blinks" and make the deadtime dependend on this calculated speed.

Something else: the way you check for the timestamp is little incorrect. You should instead do something like this:

void setup() {
  unsigned long starttime=millis();
}

void loop() {
  if (millis()-starttime > 5000) {
    starttime=millis();
    // put code here to run every 5000 ms
  }
}


How do I correctly choose components for my current project?

According to this datasheet the 595 can drive up to 6 mA per output pin with a maximum of 20 mA for the input to the chip (so, 2.5 mA if you are driving all outputs).

Since your LEDs are quoting a forward current of 25 mA it seems that you will fall somewhat short of providing the 25 mA per LED.

There are higher power shift registers, eg. the TPIC6B595.

You might want to consider a multiplexing LED driver such as the MAX7219. I have a post about using that chip.

Your LEDs sound similar to the things that the MAX7219 is designed to drive. It also has inbuilt current-limiting with the current selected by a single resistor.

It isn't clear from your question whether you have the common anode or common cathode device, but you need a common cathode for the MAX7219.

The MAX7219 is not that expensive if you buy it from eBay. For example search for "MAX7219 kit". I found hits for 4 x MAX7219 for $US 9.75 including boards, capacitors and LEDs. Just discard the LEDs (8 x 8 dot matrix) and run the wires to your bargraph.

  As they are designed to run 7 segment displays how would I connect it to transfer from my current 16 bit binary shift setup ...

They can run in a couple of modes (see the Decode Mode register) and one is to send arbitrary bits. Since you can program in any combination of bits (in my link above there is an array which does a CP437 font) you can therefore make up any combination of bars on and off. I would get one as an experiment (buy one of those kits from eBay) and try the idea out. It will be a lot less mucking around than 595 chips, transistors, current-limiting resistors, and so on.

There are various kits around, some are pre-soldered (which you won't want), some come with SMD chips and some with through-hole chips. Choose SMD or through-hole depending on your confidence with soldering SMD parts.

  I know on my shift registers pins 1-8 go to the LED anodes and Pins 9-11 go to transistors that run the cathodes. Can you help me understand the pin connections to get the MAX to run this?

Looking at your bar graph specs:

You have 3 rather than 8 cathodes (pins 14, 9 and 8 are duplicates of 1, 6 and 7). So, you would run the cathode wiring (1, 6, 7) to the first 3 "digit" pins (2, 11 and 6) on the MAX7219. The other 8 wires (marked anodes) would go to the 8 anodes (2, 3, 4, 5, 10, 11, 12, 13).

As you have only used 3 cathode pins you could wire up a second bargraph using another 3 cathode pins (and run the anodes in parallel). That way a single MAX7219 can drive two bargraphs, giving you a total of 24 bars, each of which can show red, green, or yellow at one time.

Example wiring and code

I ordered a couple of the LED modules and worked out a schematic for them:

One MAX7219 can drive two of the modules.

Example of wiring:

Example code:

#include <SPI.h>

 // define max7219 registers
const byte MAX7219_REG_NOOP        = 0x0;
const byte MAX7219_REG_DIGIT0      = 0x1;
const byte MAX7219_REG_DIGIT1      = 0x2;
const byte MAX7219_REG_DIGIT2      = 0x3;
const byte MAX7219_REG_DIGIT3      = 0x4;
const byte MAX7219_REG_DIGIT4      = 0x5;
const byte MAX7219_REG_DIGIT5      = 0x6;
const byte MAX7219_REG_DIGIT6      = 0x7;
const byte MAX7219_REG_DIGIT7      = 0x8;
const byte MAX7219_REG_DECODEMODE  = 0x9;
const byte MAX7219_REG_INTENSITY   = 0xA;
const byte MAX7219_REG_SCANLIMIT   = 0xB;
const byte MAX7219_REG_SHUTDOWN    = 0xC;
const byte MAX7219_REG_DISPLAYTEST = 0xF;

// which groups of bars we are addressing
const byte BARS_1_4   = MAX7219_REG_DIGIT0;
const byte BARS_5_8   = MAX7219_REG_DIGIT1;
const byte BARS_9_12  = MAX7219_REG_DIGIT2;
const byte BARS_13_16 = MAX7219_REG_DIGIT3;
const byte BARS_17_20 = MAX7219_REG_DIGIT4;
const byte BARS_21_24 = MAX7219_REG_DIGIT5;

// within a group, which one (from the left)
const byte BAR1_RED = 0x80;
const byte BAR2_RED = 0x20;
const byte BAR3_RED = 0x08;
const byte BAR4_RED = 0x02;

const byte BAR1_GREEN = 0x40;
const byte BAR2_GREEN = 0x10;
const byte BAR3_GREEN = 0x04;
const byte BAR4_GREEN = 0x01;

// yellow is done by adding red and green
const byte BAR1_YELLOW = BAR1_RED + BAR1_GREEN;
const byte BAR2_YELLOW = BAR2_RED + BAR2_GREEN;
const byte BAR3_YELLOW = BAR3_RED + BAR3_GREEN;
const byte BAR4_YELLOW = BAR4_RED + BAR4_GREEN;

void sendByte (const byte reg, const byte data)
  {
  digitalWrite (SS, LOW);
  SPI.transfer (reg);
  SPI.transfer (data);
  digitalWrite (SS, HIGH);
  }  // end of sendByte

void setup () {

  SPI.begin ();

  sendByte (MAX7219_REG_SCANLIMIT, 5);   // show 6 digits
  sendByte (MAX7219_REG_DECODEMODE, 0);  // using an led matrix (not digits)
  sendByte (MAX7219_REG_DISPLAYTEST, 0); // no display test

  // clear display
  for (byte col = 0; col < 8; col++)
    sendByte (col + 1, 0);

  sendByte (MAX7219_REG_INTENSITY, 7);  // character intensity: range: 0 to 15
  sendByte (MAX7219_REG_SHUTDOWN, 1);   // not in shutdown mode (ie. start it up)
}   // end of setup

void loop ()
 {
  // send various test combinations
  sendByte(BARS_1_4, BAR1_RED | BAR2_GREEN | BAR3_RED | BAR4_GREEN);
  sendByte(BARS_5_8, BAR2_RED);
  sendByte(BARS_9_12, BAR2_YELLOW);
  sendByte(BARS_13_16, BAR1_RED | BAR2_GREEN | BAR3_RED | BAR4_GREEN);
  sendByte(BARS_17_20, BAR2_YELLOW);
  sendByte(BARS_21_24, BAR1_RED | BAR2_RED);
 }  // end of loop

This is documented in my page about the MAX7219.


DS18B20 - Thermometer and Sensor discrepancy (varying)

Can you buy a few more from other (more reliable) sellers ? Perhaps it is damaged. Did you accidently connect it wrong and it got very hot ?

There has been counterfeit DS18B20 sensors, but they were transistors that were re-labeled as DS18B20. Those didn't work at all.

You have not convinced me that you are only measuring the air temperature. Maybe there is still something nearby that causes it to get warmer. The 3 degrees difference is a lot. There must be a good reason for that, or else the DS18B20 is broken. How accurate is that mercury thermometer ?

I wrote before: "To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water)". That is what I did, out of curiosity. It turned out to be accurate.


Waking Arduino from sleep by holding button for more than 3 seconds

You won't manage it without external circuitry.

The problem is the Arduino has to be awake to know you held the button for 3 seconds. You can only wake immediately you press the button. However you could then sleep again if the button is released within 3 seconds.

For external circuitry, you would need to arrange to charge (or discharge) a capacitor slowly through the button so that it reaches a threshold after 3 seconds and that threshold triggers the input to the Arduino. A HIGH input on the Arduino is 0.6×Vcc, so 3.3V for a 5V Arduino. If you arrange it that the capacitor reaches 3.3V after being charged for 3 seconds the input will see it at the right time.

simulate this circuit – Schematic created using CircuitLab

In this circuit, R1 and C1 form an RC network that charges the capacitor through the switch. C1 and R1+R2 form an RC network that discharges the capacitor all the time, so it is discharged when you release the button.

Discharge time will be slightly longer than charge time owing to the addition of R1 + R2.

To calculate the charge time, you can use T=RC which is how long (in seconds) it takes to charge the capacitor up to 63.2% of the supply voltage. That's fractionally over the 60% that the HIGH threshold is, so that's fine.

If you want T=RC to equal 3 seconds, you can rearrange the formula to suit your components. For instance if you have a 1000µF capacitor available you can rearrange to R=3/0.001 = 3kΩ. So a common 3.3kΩ resistor and 1000µF capacitor would give you (3300 × 0.001) 3.3 seconds.

R2 wants to be small enough that it doesn't slow down discharge too much, yet high enough that it doesn't draw too much current. Using about 10% of R1 is reasonable (330Ω), so with a 3.3 second charge time that resistor would increase the discharge time by 0.33 seconds.

This method is basically a very extreme form of debouncing.


You can do it as long as the current isn't excessive. I don't think there are any specs available, but the connector and the width / thickness of the copper tracks on the PCB will be the limiting factor.


Yes and no.

Yes you can make Arduinos communicate with each other and send messages to each other.

Can you use that to make a game?  Possibly.

Is it worth the effort?  No.

It would be a huge amount of work and be overly complex when you could just use a bigger Arduino, like a Mega2560 or a Due.


I thin the following is happening:

The MCP transmits 1 measurement per SPI transaction, which consists of activating chip select, reading data and deactivating chip select. To distinguish between different transactions, the time between deactivation and reactivation of chip select need to have a bit delay between them. Currently your code runs really fast, a few microseconds between the transactions at max.

This may also be connected to the MCP needing time to measure the analog signal.

I think there is some kind of race condition, so that the MCP does not have a new value to transmit, either because the MCP hasn't finished measurement yet, or because the delay between the transactions were just a bit too short, maybe a combination of both.

When the MCP is once in this situation, it will only send zeros at that point  (read chapter 5.1 in the datasheet. Last sentence in the left column).

You need to give the MCP more time between the transactions. I suggest using a small delay at the end of the loop() function. You can experiment with the actual value, I would guess, that you can go down to the microseconds range.


That's a very poor datasheet. I think it's using equals signs where it means less-or-equal, so:

  High level: 2.3V = Vin = Vss

Intends to say that Vin between 2.3 and Vss will be considered high, and

  Low:-0.3V = Vin = 1.5V

Intends to say that Vin between -0.3 and 1.5V will be considered low.

"Vss" in the high level definition is confusing, because in the rest of the datasheet, "VD" is used for the logic voltage and "VS" is used for the motor; you'd expect the upper limit to be the logic voltage.

The diagram at the end of the datasheet shows how it can be used with an Arduino. A 7.5V source is going into the Vin pin (instead of the barrel jack, which is unusual). There's a protection diode on the power input which incurs a ~1V voltage drop, so the Arduino Vin pin should be outputting 6.5V, which drives the board. The digital outs from the Arduino, when driven high, are at 5V, well above the 2.3V threshold given on the datasheet.

I'd recommend powering the Arduino through the barrel jack with a 7.5V or 9V supply to drive the logic side of the board. (Powering through the USB port will put 5V or less on the Vin pin.)

You'll want a more robust supply for the motor side, because the Arduino can't deliver very much current.


Check your port to which your arduino is connected. The port name can be checked from Arduino IDE. Click Tools -> Port -> There you can find the port name.
Open Terminal and type the following command.

sudo chmod 777 /dev/port_name

After this try to Recompile/Upload the code again.


Did I fry my DUE by powering it from a external source and USB at the same time? If so, why?

If it was the same sketch involved in the destruction of both it may be a good idea to check to make sure the sketch that is involved as well to make sure there are no logical shorts to ground or other pins. Rugged-Circuits has a list of some common ways the Arduino can get shorted. It is showing the Uno but I am sure all similar rules apply with the exception of total power requirements and other differences between the boards.


Your outputAllBut function is wrong. It turns all but the specified output high, but it doesn't turn the specified output low. As a result, after calling it multiple times, you end up with all of the outputs high forever (since you don't have code anywhere else that would turn them off), so it's just a question of timing which one it considered "on" any time you press a button.

Side note: toggling the outputs between low and high to do the matrix read is dangerous, as pressing multiple buttons at a time can cause a short circuit that way. You should instead always keep all of them low, and control which one is active by setting it to output mode and the rest to input mode.


Found the problem, cant use PIN 2 as RX.

  Note: Not all pins on the Mega and Mega 2560 support change
  interrupts, so only the following can be used for RX: 10, 11, 12, 13,
  50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69


How can I set a calculated value when my sketch is uploaded?

The C compilers provide two macros that resolve to string literals:  __DATE__ gives the time the file was compiled, and __TIME__ gives the current time of day. They output e.g. "May 31 2017" and "21:19:49"

You'd have to parse these string to get the time and do the calculations to get the remaining time.


Using multiple laptop battery packs to power everything

I'd be cautious about hooking them in parallel. According to ADAfruit power leakage between batteries is a problem.

  [multipack parallel] ... batteries are assembled by a company that is experienced and certified to test and assemble battery packs. The individual batteries are tested and sorted by machine so that each pack has matching batteries with the same capacity and internal resistance. Individuals do not have this equipment, which is why you should not try to make your own packs.

Are you certain all your batteries are the same age and have the same usage history? A brand-spanking new one will try to charge an old worn battery to its own fresh voltage.


Sublime Text 2 with stino, compilation gives "filename ... is incorrect" Arduino IDE 1.7.8

Sorry but this is too big for a comment.

Firstly please can you check the obvious, in Windows Explorer paste the path C:\Users\lov\AppData\Local\Temp\Stino_build\t5 into the address bar and does the directory exist. (I have fallen for that so many times)

Secondly do you have permission to create a file there?

Have you updated the IDE? Does blink compile?

Have you tried running the IDE as admin?

Hopefully one of those will fix it.


SOLVED: Strange phenomenon with avrdude: stk500v2_ReceiveMessage(): timeout only with ATmega250 on windows 7x64

I found the problem coming from a mismatch of the port speed setting and the baudrate in the avrdude command.
It seems that the ATmega is very sensitive to timing issues.
After I did set everything to 115200 it works on my w7 box like on the notebook.


After some digging around in the core, it seems like Arduino updates millis() with a 8 bit timer: it uses overflow with a prescaler value of 64. In simpler terms, it has it set up so a certain piece of code (the ISR) is run approximately once per millisecond on a 16MHz system (and proportionately less frequently on slower clocked systems).

When that ISR is ran, it increments a variable that is used by the millis() function.

So, even if some non-interruptable code is being ran for a fraction of a millisecond, it won't matter since the bit for that interrupt vector will still remain set.

However, there is a problem when the ISR is ran less often than it should be triggered. This may be a result of using noInterrupts() for an extended period of time or when too many other interrupts are being ran and there is not enough CPU for all of the tasks. If a lot of the other ISRs have a higher interrupt priorities, it is possible that the code for the millis() may never be ran. In this case, you would have more serious issues than this, but it is something to keep in mind when you're writing code.

The general rule of thumb of ISRs still apply: keep it short!!!

Note: if you require extreme accuracy, the built in function isn't the best choice. A RTC is a good idea for long term time keeping.


How do I resolve "avrdude: stk500_recv(): programmer is not responding"?

After trying numerous suggestions, 2 different boards, 3 different cables on a WinXP and a Win7 machine, I finally got things working by going to "Tools -> Processors -> ATmega 328P Old Bootloader"


invalid conversion from 'uint16_t* error when creating an array of uint16_t items

You have two options.

You can make an array of arrays like this:

const uint16_t sources[3][RAW_DATA_LEN] = {
    { 8546, 4310, 558, ... }, // CD
    { 8550, 4310, 526, ... }, // AUX
    { 8550, 4306, 530, ... }  // CDR
};

But then you don't have the sourceCD, etc. variables any more. If you
want, you could #define aliases for them like this:

#define sourceCD  (sources[0])
#define sourceAUX (sources[1])
#define sourceCDR (sources[2])

You can make an array of pointers, as suggested in the comments:

const uint16_t sourceCD[RAW_DATA_LEN]  = { 8546, 4310, 558, ... };
const uint16_t sourceAUX[RAW_DATA_LEN] = { 8550, 4310, 526, ... };
const uint16_t sourceCDR[RAW_DATA_LEN] = { 8550, 4306, 530, ... };
const uint16_t *sources[3] = { sourceCD, sourceAUX,  sourceCDR };

This works because, in the last line, the array identifiers such as
sourceCD implicitly “decay” to pointers to their first elements. Note
the const keyword in the last line, needed for consistency with the
types of the arrays declared above.


And the Arduino team finally figured it out:

http://blog.arduino.cc/2014/05/06/time-to-expand-your-yun-disk-space-and-install-node-js/


Arduino based SPI programming of LT1257 not working

I read the LT1257 data-sheet more carefully. There is a pull down nmos at the output of the DAC. So when uninitialized, the output of LT1257 should be ~0V. So the output I was measuring (~1.02V) is spurious. I suspect I damaged the IC. I tried the same code on a different LT1257 and it worked. I can confirm now that this code is working.


Problem sending data from arduino with ESP8266 to a local mysql database

The HOST should not have a newline after it, so you should have

client.print("HOST: ");
client.println(server);

In addition your PHP looks dodgy to me.  I'm not very familiar with PHP at all, but I think the &amp;s here are left over from something you have removed, and causing syntax errors - just remove them

if (!empty($n) &amp;&amp;)

I believe your n parameter is going to be in _GET (not _REQUEST).  Also, you should check whether it's there, not just assume it is, so:

if isset ( $_GET["n"] )
{
    $n = $_GET["n"];
    // Do your database stuff here
}

(You should find the PHP log (where depends on what OS your server is running on) and I think it would point you straight to this problem.  No point trying to debug it blind.)


Can I set an Arduino pin as input and output?

No there is no function that lets you set all the pins to either input or output at the same time, but it wouldn't take much to write one.

No, you can't set an Arduino's pin as bidirectional.  If you are running out of pins look at IO expanders or multiple Arduinos.

Hope that helps, if not please feel free to clarify what it is you would like to know and we'll try and help.


You're calling delay() in the onWsEvent() callback. The ESPAsyncWebServer documentation specifically says not to do that in the 'Important things to remember' section:

You can not use yield or delay or any function that uses them inside the callbacks

When you call delay() or loop inside an async web server callback, you block its event task from doing any other processing. This can interfere with a variety of housekeeping functions that HTTP, TCP and the Arduino Core need to perform. In general you should do as little as possible during a callback and return as quickly as possible.
The correct way to structure this code is to set a flag in the callback and inspection the flag and do the work in loop().
For instance,
AsyncWebServer server(80);
AsyncWebSocket ws("/test");

boolean flag_move_stepper = false;

void setup(){

and
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){
    flag_move_stepper = true;

    // you'll need to rewrite this code to share variables with `loop()` and do the work there

and
void loop(){
  if(flag_move_stepper) {
    flag_move_stepper = false;

    // do the work formerly in onWsEvent() here
  }

}

You'll need to make the variables you stored data in in the event handler available to loop() and move the stepper code there for this to work.


Yes, in theory you can always miss events if you use a polling approach like that. Whether or not that's a problem depends on how accurate/frequent your data collection needs to be.

You can often mitigate the issue to an acceptable level if you are able to poll fast enough. That's determined largely by what else your main loop is doing. The more work it has to do elsewhere, the longer it will take between calls to analogRead() (and the more likely it is to miss something). Optimising your code can help.

You may also find that you can compensate sufficiently by interpolating between samples. Linear interpolation is very easy, although more complex options may also be possible, especially if you're processing the data offline afterwards.

If polling isn't working for you, then interrupts are the obvious alternative. Since you're reading an analog signal, you'd probably need some external circuitry which does a voltage comparison. You can get dedicated comparator IC's from all sorts of vendors, or use an op-amp circuit if you prefer.

If the signal goes over a pre-determined threshold, the comparator would have to pulse or assert a digital line. That could trigger an external interrupt pin on your microcontroller, which will execute custom handler code. See attachInterrupt() for more information.


This is not a direct answer to your question, as I have no such answer,
and I believe the answer you are seeking would be of no use to you.

The problem with your question is that your method of testing memory
usage is heavily flawed. By removing the switch statement, you most
likely have allowed the linker to remove lots of methods referenced by
it, leading to huge memory savings. Those savings do not mean the
culprit is the switch statement itself.

The correct way to test static memory usage is to use either
avr-objdump or avr-nm. You have to find where the IDE puts the
compiled elf file, then you can issue the command:

avr-nm --size-sort -Crtd my_program.elf

This will give you a list of all symbols in your program sorted by size.
Symbols of type 't', 'w' and 'd' (upper or lower case) eat flash.
Symbols of type 'd', 'b' and 'v' eat RAM.


It seems you have the module connected to the Nano pins 0 and 1, and are also trying to communicate with the PC via the Serial object and serial monitor?

There is a USB/serial converter chip on the Nano that is likely conflicting with your module. You can try SoftwareSerial to get a bit-banged serial port for communicating with the module on some other pins.


Does an I²C IO Expander needs additional resistors for outputs?

Yes, according to the datasheet (which should always be your first port of call for any chip) the outputs are Open Drain. That means you require a pullup resistor, exactly as if the outputs were simple buttons.


Sending and receiving different types of data via I2C in Arduino

I2C is truly a powerful option of Arduino, for too many reasons; yet the amount of tutorials available are not that many and unfortunately are too complicated for the average person.

After working on this for 2 days, I think I have a way to transfer pretty much anything between master and slaves and viceversa. Note that I2C does not transfer floats or even integers larger than 255, there are several ways to go about this and here is a good tutorial
http://www.gammon.com.au/i2c
and even a library: http://forum.arduino.cc/index.php?topic=171682.0

The solution I found was simpler. Basically we convert any value, string, number, text, float, you name it, and turn into a variable char, which can be transferred via I2C. Once transferred, you can convert back to a number although in my case below, I just wanted to display the data from the slave.

Here is the code. I provide comments on different parts for clarity. I hope this helps. it worked for me.

//master
#include <Wire.h>

char t[10]={};//empty array where to put the numbers comming from the slave
volatile int Val; // varaible used by the master to sent data to the slave

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(8, 3);    // request 3 bytes from slave device #8

//gathers data comming from slave
int i=0; //counter for each bite as it arrives
  while (Wire.available()) {
    t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
    i=i+1;
  }

Serial.println(t);   //shows the data in the array t
delay(500); //give some time to relax

// send data to slave. here I am just sending the number 2
  Val=2;
  Wire.beginTransmission (8);
  Wire.write (Val);
  Wire.endTransmission ();
}

here the other part
    //slave

#include <Wire.h>

char t[10]; //empty array where to put the numbers going to the master
volatile int Val; // variable used by the master to sent data to the slave

void setup() {
  Wire.begin(8);                // Slave id #8
  Wire.onRequest(requestEvent); // fucntion to run when asking for data
  Wire.onReceive(receiveEvent); // what to do when receiving data
  Serial.begin(9600);  // serial for displaying data on your screen
}

void loop() {
  int aRead = analogRead(A0); //plug a potentiometer or a resistor to pin A0, so you can see data being transfer
  float x = aRead/1024.0*5.0; //generate a float number, with this method you can use any time of data pretty much

  dtostrf(x, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  Serial.println(Val);         // print the character
 delay(500);
}

// function: what to do when asked for data
void requestEvent() {
Wire.write(t);
}

// what to do when receiving data from master
void receiveEvent(int howMany)
{Val = Wire.read();}


Have you searched for other libraries or example code for this particular sensor?

I found this NewPing library that claims to have been developed to fix poor performance of such modules due to poor timing methods.


Pin change interrupt does not work properly to wake up arduino from sleep mode

Start by checking your calculation of time limits. I see you are mixing signed and unsigned arithmetics - not a very good idea. Check the blink-without-delay example for how to do that.

The declaration of timer_start_time should be paid special attention.

Good luck with your project!


Currently your code is not working, because Arduino is fast enough to check the closed switch state many times before it opens again, so before calculating a new speed value, you need to see LOW on the input.

Still, there are at least 2 better ways to do what you want.

pulseIn() - a function intended just for what you are trying to do: measuring lenght of a pulses. If your switch is active HIGH, you need to measure length of a LOW pulse:

unsigned long duration;
duration = pulseIn(reed, LOW);
// calculate speed basing on duration (in microseconds)

Keep in mind, that pulseIn() is a blocking function, so no code will be executed, until it receives the pulse. You can counter it bu specifying a timeout, after which, the program will continue.

External interrupts are an another approach. Interrupt handling routines are executed when a specified event occurs, no matter if the microcontroller is busy doing something else or not. They would guarantee, that you will not miss any pulse even if they would have frequency in order of kHz.

volatile unsigned long lastTime = 0;

void setup() {
    attachInterrupt(0, readTime, RISING);
}

void readTime() {
    unsigned long t = millis();
    // calculate speed basing on t - lastTime
    lastTime = t;
}

Interrupt handling routine should be as short as possible. Avoid using delays in it, doing Serial.print and other communications. Also, millis() and micros() will not increment during execution of interrupt handler.

Debouncing - even with above two methods, things may still not work properly. The most probable cause would be switch "bouncing". You can counter it by

software debouncing  - delaying after pulseIn() or ignoring interrupts for some period of time after first interrupt is detected
adding a small (10-100nF) capacitor at the input, that will act as a low-pass filter, cutting out short pulses
using not a reed switch, but a hall sensor with hysteresis


JSN-SR04T-2.0 with NodeMCU not starts after reset or reconnect usb power

To enable ESP8266 firmware flashing GPIO0 pin must be pulled low
  before the device is reset. Conversely, for a normal boot, GPIO0 must
  be pulled high or floating.

The D3 pin is equivalent  GPIO0. For a normal boot, GPIO0 must be pulled high or floating while powering up or resetting the module. After that (normal boot), you can use the output for other purposes.

You can use a different output or try to use a pull-up resistor for the D3.


Photoresistor is not working, is there something wrong in the code?

The code looks OK. It looks like it's your circuit which is the problem.

The main role of a photoresistor is to restrict the amount of current flowing through it when the light level is reduced. It won't directly affect voltage the way you're expecting (the analog pins respond to voltage).

However, it's pretty easy to make it affect voltage with a slightly different circuit. Try creating a voltage divider circuit, such that the supply voltage (5V) goes through the photoresistor, then through another resistor, and then to ground. The Arduino's analog pin should be connected between the photoresistor and resistor. (See the image below, although the resistor on the output probably isn't necessary in this case.)

This should cause the voltage on the analog pin to decrease when the light level decreases. You may need to experiment a little to find a suitable resistor value on the ground connection, although 2K Ohms is probably a good starting point. It basically affects the sensitivity of the circuit.

Image credit: Morteza Lahijanian (source)


Is there a microcontroller that can output hdmi?

It depends on what you are looking for. There are lots o chips made to control and process hdmi frames. However, as Jot said, the arduino is not suitable for this. The arduino can output basic VGA, but it does not have enough "horsepower" to play with HDMI. The best and cheapest solution is to use a Raspberry Pi.


Trying to understand bitbanging, shiftIn(), reading EEPROM

OK I know this is a little late, but for other readers having the same problem, here's a sketch I wrote to read a 93c46 when I had to dump the EEPROM from a car radio. I've deliberately not included the EWEN instruction anywhere as the last thing I wanted to do was accidentally write to the EEPROM.

The key is the modified shiftOut routine which adds a parameter specifying how many bits you want to shift out.

To adapt sketch for other 93c packages, change the number of 16bit words at start of loop{} and number of address bits in 2nd call to myshiftOut.

If your package has an ORG pin, tie it to Vcc.

Hope this helps someone...

/*
Arduino Uno sketch to dump a 93c46 EEPROM in 16 bit mode.  Metalbanana 12/9/16, with thanks to raint.
Easily modified for other 93c series parts. Note many 93c46 from autos are 'rotated' pinout,
i.e. those with a T following part no. e.g. 'TEM8':

1=NC    8=ORG
2=Vcc   7=GND
3=CS    6=DO
4=SK    5=DI

so check pcb for Vcc and GND locations with a meter first! An Arduino ProtoShield is ideal to mount IC
as it has a SOIC pad (Note: you can't use the mini breadboard at same time as it covers one set of headers).
Standard shiftOut is not suitable as it sends 8 bits, our addresses are 6 bits,
instructions are 3 bits so sketch uses a modified shiftOut called myshiftOut.
*/

// define pins for eeprom
const int CHIP_SEL = 8;  // to CS
const int CLOCK = 9;     // to SK
const int DATA_IN = 10;  // to DO
const int DATA_OUT = 11; // to DI

const byte READ  = B110;                //read instruction

bool debug = 0;

void myshiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, byte val, uint8_t bits)
{
  for (int i = 0; i < bits; i++)  {
    if (bitOrder == LSBFIRST) {
      digitalWrite(dataPin, !!(val & (1 << i)));
      if (debug)Serial.print(!!(val & (1 << i)));
    }
    else
    {
      digitalWrite(dataPin, !!(val & (1 << (bits - 1 - i))));
      if (debug)Serial.print(!!(val & (1 << (bits - 1 - i))));
    }
    digitalWrite(clockPin, HIGH);
    digitalWrite(clockPin, LOW);
  }
}

void setup() {
  pinMode(CHIP_SEL, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(DATA_OUT, OUTPUT);
  pinMode(DATA_IN, INPUT_PULLUP);

  Serial.begin(9600);
  Serial.println("\n\n");
}

void loop()
{
  for (int addr = 0; addr < 64; addr++) // 64 words for 93c46
  {
    // print address at start of each line
    if (addr % 8 == 0) {
      Serial.println();
      if (addr < 8) Serial.print("0");
      Serial.print(addr * 2, HEX);
      Serial.print(": ");
    }

    digitalWrite(CHIP_SEL, HIGH);
    myshiftOut(DATA_OUT, CLOCK, MSBFIRST, READ, 3); //send READ instruction
    myshiftOut(DATA_OUT, CLOCK, MSBFIRST, addr, 6); //send address, 6 bits for 93c46

    digitalWrite(CLOCK, LOW); // recommended in language reference
    byte incomingH = shiftIn(DATA_IN, CLOCK, MSBFIRST); //receive high byte
    byte incomingL = shiftIn(DATA_IN, CLOCK, MSBFIRST); //receive low byte

    // reverse byte order & print
    if (incomingL < 16) Serial.print("0");
    Serial.print(incomingL, HEX);
    Serial.print(" ");
    if (incomingH < 16) Serial.print("0");
    Serial.print(incomingH, HEX);
    Serial.print(" ");

    digitalWrite(CHIP_SEL, LOW);
  }

  while (1);
}


I back up Michel Keijzers' suggestion to use a plain array, especially
given the tiny amount of RAM in your MCU (only 256 bytes).

Concerning the removal of items from the list, and given that your list
will be 16 bytes at most, you don't need to get fancy: just move back
the items that are past the one you removed. It will not take long.

Here is a barebones implementation of a list that can hold at most
16 bytes and supports removal:

class List {
public:
    byte length;
    byte data[16];
    void append(byte item) {
        if (length < 16) data[length++] = item;
    }
    void remove(byte index) {
        if (index >= length) return;
        memmove(&data[index], &data[index+1], length - index - 1);
        length--;
    }
};

Note that this only takes 17 bytes of RAM (16 items max plus a
length count). There is not vtable, as it has no virtual methods. You
can get fancier if you want, make this a template parametrized by the
data type and the maximum length, add accessors and such... but if you
are just writing a simple sketch (as opposed to a general purpose
library), I would recommend keeping it as simple as possible.

Example usage, based on your pseudo-code:

List l { .length = 3, .data = { 12, 82, 29 } };
l.remove(1);

This will indeed result in the list [12, 29].


If button is pressed: Motor A and B move for 1 second at slow speed == > Motor A keep moving but at fast speed and motor B stop. else: Motor A and B both stop.

I would do a quick state machine:

  STATE / button released: do nothing;
      STATE / button pressed: run motors a+b;
      STATE / run motor a+b: run motor a+b; if 1 second has passed, advance to just run motor a;
      STATE / run motor a: run motor a at fast speed and stop motor b.

fairly easy to code as well.


You can use photo any transmissive or reflective photo interrupter (wire or TH) ideally with integrated Schmitt trigger and connect to IRQ driven AVR input to have quick trigger reaction. For production is cheaper photo interrupter with external Schmitt but for prototyping it does not matter.
Don't forget serial resistor to limit current.

Search e.g. "photo interrupter Schmitt" at Farnell.


433Mhz receiver only get values of 0, 1, 2

Those cheap 433 MHz RF modules require a (good) library to work. The VirtualWire/RadioHead library is the best.

The VirtualWire library it outdated, but still used.

The RadioHead library has a few bugs fixed, but uses more memory.
Use it in RH_ASK mode, see the included 'ask' examples.

[Update: better quality]
Most cheap 433 MHz ASK transmitters work with 3.5 to 12V. They have the longest range at 12V. About 20 meters is no problem with 5V, but if longer range is needed then transmitters that are only made for 5V are better.
The cheap 433 MHz receivers use a coil to tune the frequency. They are very sensitive and they do work well. However, when such a module is placed near metal or close to the Arduino, the frequency might change. Modules that use a crystal for the frequency are better. Sometimes a sensitivity is mentioned (for example -112dBm) but I don't know how reliable that is. When an antenna of 16 cm does not work well, try an antenna of more than a meter.

The transceivers are better for wireless data transfer, but that depends on the use.
Sparkfun has Wireless Buying Guide.
RadioHead has a list of supported transceivers.

The nRF24L01+ are very cheap. I read that every one of them on Ebay or Aliexpress is counterfeit, but the counterfeit chips do work. They work at 3.3V, and are 5V tolerant.

The CC1101, CC2500 and so on are good, but not often used with an Arduino. The same for Si4432, Si4436 and so on. If you know a good library, they are very good transceiver chips.

Adafruit is using the RFM69 a lot. For example the Feather Packet Radio board.

Last but not least: don't forget Wifi and Bluetooth.


As Majenko pointed out, the wires are not connected to the piezo.  By moving the piezo to the correct rails on the other side of the board, the circuit would be completed and the piezo should work.

Edit:
Building on Nick Gammon's comment, the rows of each side of a breadboard are not connected (to allow DIP packages).


I have just tested vbextreme/Scheduler and Arduino-Scheduler using the following code:
#include <Scheduler.h>

void setup() {
  pinMode(3, OUTPUT);
  Scheduler.startLoop(loop2);
}

void loop() {
  digitalWrite(3, LOW);
  yield();
  digitalWrite(3, HIGH);
  yield();
}

void loop2() {
  yield();
}

Without any Scheduler lines, the code occupies 734 bytes of ROM, 9 bytes of RAM, and the pin toggles with a period of 8.5 us (117 kHz). The numbers below represent the additional ROM/RAM/execution time:

vbextreme/Scheduler occupies additional 1676 bytes of ROM, 70 bytes of RAM, and the context switch takes 15.5 us (toggle frequency 14.18 kHz). It seems to only support AVR/SAMD boards.

vbextreme/Scheduler with CONFIG_AVR_OPTIMIZE_COOPERATIVE set to 1 occupies additional 1568 bytes of ROM, 70 bytes of RAM, and the context switch takes 11 us (toggle frequency 19.07 kHz).

Arduino-Scheduler occupies additional 578 bytes of ROM, 44 bytes of RAM, and the context switch takes 10.6 us (toggle frequency 19.59 kHz). It supports AVR/SAMD and some of the Teensy/STM32 boards. It seems that this scheduler is not compatible with tasks which use malloc().

CopyThreads occupies an additional 2148 bytes of ROM, 41 bytes of RAM, and the context switch takes 54.5 us (toggle frequency 4.417 kHz). This scheduler claims to have the advantage of using a single stack, so as long as tasks do not yield during peak stack usage, each task has essentially the complete stack at its disposal.

I couldn't get the equivalent code for TaskScheduler to run, I'll be grateful if someone posts an answer featuring schedulers I didn't test.


The motor should

  turn when the next average the program measures is 100 or more greater than the previous average it measured

So simply write it:

// Old average is called "average"
// Compute the new average and put it in next_average
if ((next_average - average) >= 100)
{
  // Turn the motor
}
average = next_average;


ESP8266 connecting keypad and lcd display

You can read the keypad using a single analog input (A0 in ESP8266) using this circuit:

When you press a key, some resistors are connected between Vcc and Ground. For each key, the total resistence is different, and the voltage at the input pin is different.

To read the keypad, you read the voltage at the input pin A0. You also have a table that associate the readings with keys. You search in the table for the nearest entry to the value you get. That's your key.

Wire the circuit and make a little sketch to read the values for each key you press. That's how you construct your table.

The value at A0 will be a little different each time you read the pin. That's is normal. Don't expect a exact macht.


Use interrupts with analog pins in arduino or another possible solution?

You are looking for the bad solution for a simple problem. As Ignacio
Vazquez-Abrams puts it, the problem is you using delay(). The simplest
solution is to manage the timings with millis(). See the Blink
Without Delay Arduino
tutorial.


I have taken your code from above and compiled it for a PC in Visual Studio.
When I create an object of type DigitalOutPin and call setPinValue() it calls the function I expect.  So this means either you have managed to find a bug in the gcc compiler, or there is something else in your code that is coming into play.  Can you try writing a VERY simple minimal test program that defines the Pin class and DigitalOutPin class (with just the setPinValue functions that print a string) and the setup and loop functions.  Just to see if you have found a gcc bug.

Even if this fixes the inheritance problem, you have other issues with you code because C++ is weird.  In Channel.h your Pin variables will need to be pointers, this will allow them to call the functions in the derived classes, not the base class functions.

I think you may get a performance improvement by using "const int& foo" for you parameters.  The const means the function can't change it, this allows the compiler to treat it differently and the "&" means use a reference to the variable rather than make a new copy of it.

Functions that don't change member variables within the code should also be declared constant.  "int FooBar(const int& value) const;"  It makes it clearer to the reader and the compiler probably does some funky stuff to improve performance.  (You might want to investigate "inline" if you are writing one line functions.)

Finally I'd recommend using constructors and destructors.  In release builds variables are not assigned a value.  If these variables are class members this means you don't know what they are to start with.  Also derived classes should initialise the base class, so:

// Class constructor for DigitalOutPin
DigitalOutPin::DigitalOutPin(const int& pinNumber)
  : Pin(pinNumber)  // Initialise the base class
  , m_State(false)  // Initialise all the class members (in order declared in .h file)
{
  // Lots of lovely code
}
// Class destructor for DigitalOutPin (Declared as virtual)
DigitalOutPin::~DigitalOutPin()
{}


The error you're reporting is coming from your call to PubNub.publish(). You could have diagnosed the problem by taking outputting and inspecting what you were passing to it.

Your line:

PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");

is not going to work. You're sending the string "String(IMU.getAccelX_mss())" to PubNub rather than the value of IMU.getAccelX_mss() as a String. Take the quotes off it:

PubNonSubClient *pclient = PubNub.publish(pubchannel, String(IMU.getAccelX_mss()));

If for some reason the number has to be returned as a string, the code would look like:

PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"" + String(IMU.getAccelX_mss()) + "\"");


You're getting confused with number bases. A number prefixed with 0x is hexadecimal. That's base 16 - not base 10.
0x125 is actually 293. If you try squeezing 293 into an 8-bit register it will truncate to 37.
Channel 125 is 0x7D in hexadecimal.
I can't recall off hand how big the register is for the channel number, but either 7 or 8 bits would suffice (probably only 7 bits actually used) so the highest channel number you could possibly enter would be 127, which is 0x7F, after which it will start at channel 0 again for 128 or 0x80.


With my post approaching one month without a single reply  :smiley-confuse: !
(for whichever reason) I would like to post for those who may need this library :

https://drive.google.com/file/d/0Bx5wWRfN_z7oMDlZMDhWbXM2VFU/view
The library is based on the original one written by Jason Vreeland [CodeRage]
Released 3/7/2010 under GNU license
and was used (and possibly modified) by "jhottell" on electronhacks.com :
https://electronhacks.com/2014/04/arduino-modbus-plc-rtu/
The major difference is the use of RS485.
I have written code and tested it on an "UNO" which worked perfectly with more
than one ModBus Slave Simulator under windows, including DAQ Factory which
is a professional package used in actual industry.


Generating digital positive (+5 V) and negative (-5 V) signal?

It is not so easy to create a -5v power supply using a capacitor or transistor.

A very easy way is to use an additional Wall wart power supply to create -5 volts (while still using your original +5 volt power supply).

For the additional (new -5 volts power supply), use the two wires (positive and negative to create your -5 volts).   The positive lead goes to your board ground, and the negative lead becomes your -5 volts.

EDIT 1  :   Make certain that the Wall wart that you use is isolated from the mains voltage (line voltage you plug it into).  Most Wall warts are isolated,  but check to be sure.

Then you need level translation, which can be done with an op-amp and a couple of resistors  :

You have not mentioned what frequency (data rate) you need.  This circuit is not fast, so for high frequency or high data rates, the circuit could be improved.


How do I repurpose Arduino's reset button

If you just want the reset button to change the program mode, the
simplest thing would be to let the button reset the Arduino and switch
modes each time your program restarts. Then you do not need to change
the fuses or get a high voltage programmer. The code would look like
this:

void setup()
{
    // At startup, switch to the next mode.
    if (++mode >= NUMBER_OF_MODES) mode = 0;

    // etc...
}

There is just a small issue here: when the program starts, all the
global variables (like mode above) are supposed to be initialized by
the C runtime. This can be avoided by using a non-standard feature of
gcc: if you request the variable to be stored in the special .noinit
section, then it will not be initialized. Here is the program I used to
test this idea:

const unsigned int NUMBER_OF_MODES = 5;

__attribute__((section(".noinit"))) unsigned int mode;

void setup()
{
    // At startup, switch to the next mode.
    if (++mode >= NUMBER_OF_MODES) mode = 0;

    Serial.begin(9600);
    Serial.print("Current mode: ");
    Serial.println(mode);
}

void loop() {}

Now, each time I press the reset button, it goes to the next mode among
(0, 1, 2, 3, 4). The main drawback compared to using a regular input is
the delay added by the bootloader, which is slightly more than one
second.

A word about the cold boot initialization: the RAM is not initialized
by the hardware and contains essentially random bits. This means you
cannot count on mode having initially a valid value. This is why:

I am testing for ++mode >= NUMBER_OF_MODES rather than
++mode == NUMBER_OF_MODES, as the initial mode could be way larger
than NUMBER_OF_MODES
mode is an unsigned integer, otherwise I would need to also test for
it being negative.


What GUI software/platform can I use to control my Arduino MP3 player over the serial port?

When interfacing the Arduino with other software, consider using Jubito.


Arduino GSM Shield NET and STATUS led turn off after a few seconds

SOLUTION:
To solve my GSM shield issue, I connected a 9 V battery to my Arduino as a supply instead of using my Laptop's USB cable (and I also tried a 12 V supply as well). Thankfully, it did work. In the case that that it does not work (after uploading the program), click on the 'restart' button found on the GSM shield. You can find the type of sources that I used to supply my Arduino & GSM shield in the image posted below. IT IS IMPORTANT TO MENTION THAT THE FOLLOWING PROGRAM WAS IMPLEMENTED TO CHECK IF THE GSM SHIELD IS WORKING (I tried the "GSM Networks Scanner" program that I have mentioned in my question initially, but it did not work and it was not necessary anyways. So, I used the 'GSM SMS' code directly and it worked fine)

This is the code that worked out with me:

#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;

// char array of the telephone number to send SMS
// change the number 1-212-555-1212 to a number
// you have access to
char remoteNumber[20]= "Replace this text with a mobile number instead";

// char array of the message
char txtMsg[200]="Hello World";

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

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  sendSMS();
}

void loop()
{
// nothing to see here
}

void sendSMS(){

  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
}


How much current needed to power arduino uno?

The maximum voltage at the Vin pin is 12V, so using your battery is fine!

Considering the current consumption:
The arduino itself will usually source less than 200mA, but your whole setup will probably sink more than that.


How to use a common anode 7-segment, 4-digit display?

Just as a complement to Paul's answer, I wrote a short program to show
how to drive the 7-segment 4-digit display of his figure:

This is actually a common cathode display, so the program assumes that,
as well as the particular wiring of the figure. The interesting part is
the refresh_display() function, which should be called periodically.
The algorithm is as follows:

drive the 7 anodes with the appropriate signals for one of the digits
we want to show
set HIGH the output that controls that digit's cathode through the
NPN transistor
wait for 2.5 ms (for a refresh rate of 100 Hz)
set LOW the cathode-controlling output
move to the next digit.

It should be noted that the waiting is done without blocking the CPU, by
using the technique described in the Blink Without
Delay Arduino
tutorial. Here is the program:

const int NB_DIGITS     = 4;  // 4-digit display
const int FIRST_ANODE   = 2;  // anodes a..g on pins 2..8
const int FIRST_CATHODE = 9;  // cathodes, right to left, on pins 9..12

// Digits to display, from right to left.
uint8_t digits[NB_DIGITS];

// Set all the used pins as outputs.
void init_display()
{
    for (int i = 0; i < 7; i++)
        pinMode(FIRST_ANODE + i, OUTPUT);
    for (int i = 0; i < NB_DIGITS; i++)
        pinMode(FIRST_CATHODE + i, OUTPUT);
}

// This should be called periodically.
void refresh_display()
{
    // Our 7-segment "font".
    static const uint8_t font[10] = {
        //abcdefg
        0b1111110, // 0
        0b0110000, // 1
        0b1101101, // 2
        0b1111001, // 3
        0b0110011, // 4
        0b1011011, // 5
        0b1011111, // 6
        0b1110000, // 7
        0b1111111, // 8
        0b1111011  // 9
    };

    // Wait for 2.5 ms before switching digits.
    static uint32_t last_switch;
    uint32_t now = micros();
    if (now - last_switch < 2500) return;
    last_switch = now;

    // Switch off the current digit.
    static uint8_t pos;
    digitalWrite(FIRST_CATHODE + pos, LOW);

    // Set the anodes for the next digit.
    pos = (pos + 1) % NB_DIGITS;
    uint8_t glyph = font[digits[pos]];
    for (int i = 0; i < 7; i++)
        digitalWrite(FIRST_ANODE + i, glyph & 1 << (6-i));

    // Switch digit on.
    digitalWrite(FIRST_CATHODE + pos, HIGH);
}

/***********************************************************************
 * Example usage.
 */

void setup()
{
    init_display();
}

void loop()
{
    uint32_t now = millis();

    // Change the number displayed every second.
    static uint32_t last_change;
    if (now - last_change >= 1000) {
        digits[3] = digits[2];
        digits[2] = digits[1];
        digits[1] = digits[0];
        digits[0] = (digits[0] + 1) % 10;
        last_change = now;
    }

    refresh_display();
}

Paul provided a link to a tutorial on
Parallax
that suggests using the
Multiplex7Seg
Arduino library. That library is more general than the example code
above, as it does not make assumptions about the pins used. But the big
difference between the library and this code is in the way the timings
are managed:

The library is driven by the Timer 2 overflow interrupt. This should
provide a very steady timing, at the cost of having one timer
dedicated to this job.
The code above relies on the user calling refresh_display() often
enough. It doesn't require dedicated hardware resources, but it
doesn't play well with programs that take too long to loop(): it
won't like you calling delay().


In general it makes little or no difference what the value of resistor you use is.

The only things it can affect are:

The current consumption while a button is pressed - a lower value resistor will cause more current to flow while for the time the button is pressed (it makes no difference at other times).
The LOW voltage (VIL) read at the IO pin if the button has a high resistance (for example if it's on the end of a 500m length of cable).
Noise immunity - a lower value resistor will pull the pin up "harder" making it more difficult for noise induced in a long wire (see the previous point, too) from causing a false button press (although this is less of a concern with modern digital inputs that tend to all have Schmitt triggers).

10k is often chosen not because it's "better" than any other value, but purely because it's more common that many other values, and it's in the right kind of ball-park for most setups.  It's low enough to give good noise immunity while being high enough to not cause undue current flow while the button is pressed. But more importantly, it's a resistor that everyone has in their kit, and is most likely the most common resistor used in a number of other places in the circuit as well. It's a good all-rounder as far as resistors go.

To take a closer look at the current flow aspect - if you are running (as with an ESP8266) at 3.3V and you have a 10k resistor the current flow, when the button is pressed and the resistor connected directly to ground, though the resistor would be (I=V/R) 3.3/10,000 = 330uA. If you used a 4.7k resistor (as you are doing at the moment) the current rises to 3.3/4,700 = 702uA. Yes, that's just over double the current, but twice peantus is still peanuts. So 4.7k, under most general circumstances, is perfectly fine.

However if power consumption is a real concern and you want to keep all consumption to an absolute minimum switching to 100k (as you often see in low-power circuits) would be beneficial, since 3.3/100,000 is 33uA.

If your input is connected to a momentary button which will be pressed for fractions of a second at a time it's not that much of an issue. But if the input is connected to a switch that could be activated for days or weeks at a time it obviously becomes of greater interest.

So in short: when running on batteries higher value pullup resistors are better, but when running off a power supply it really makes no difference.


Two things:

The else will only be subject to the last if being false, the rest of the if statements are completely separate and can affect the else in no way whatsoever.  To chain them you need if (...) { blah blah } else if (...) { blah blah } etc.
You cannot compare characters and strings like that (and in fact they're not even strings, they're lots of characters squeezed into a single character through the use of the wrong kind of quotes).

So basically no, your whole program there is completely wrong and won't do what you think it will and you need to completely re-thing how it works.

Some tips:

Use strcmp() to compare strings.
If reading strings from serial store them in character arrays not a single character.

You might find this useful:

http://hacking.majenko.co.uk/reading-serial-on-the-arduino
http://hacking.majenko.co.uk/the-evils-of-arduino-strings


Will the L9823 work at 3.3v with Wemos boards?

No. The undervoltage puts it in reset at 3.95V per the ST data sheet. It is a  5v only part with a wide tolerance on VCC. It was designed many years ago as an automotive part. It is a very nice part and performs well.


I had the same problem described above.
Error downloading http://downloads.arduino.cc/packages/package_index.json

I solved the problem, just deleting the temporary file: "package_index.json.tmp"


Can you current-limit Arduino 101 GPIO pins?

No. I have never heard of a microcontroller with constant current or current limiting on the GPIO pins.

You may get a drive strength on the pins of an FPGA, but I have never seen such a thing on a microcontroller.

In general, if you have a need to reduce the voltage as the current increases you would just slip a resistor in the circuit. Or for more precise control using the GPIO pin to control a constant current source or constant current sink is the normal way of doing it.

GPIO pins are generally designed for communicating with other logic level devices. They require minimal current. Some microcontrollers provide a higher drive strength to work with larger fanouts (lots of devices connected to one pin, such as in SPI buses), but they are not intended for providing power to a device or giving control over their current.


Can't send serial data throught serial pins but it works with the usb port

I suggest you try to flash the pin 13 LED in your loop().  It seems like the Arduino is not booting correctly on the batteries?

The serial port on the uno is kinda messy, it shouldn't really be shared with the usb port like that.  I prefer the Leonardo for these applications - where the USB serial and serial pins are totally independent.