Arduino WiFi Dongle Connection I want to use a my existing WiFI USB Dongle with Arduino Uno. I know that there is no USB port in Arduino Uno as such so I opened the USB Dongle and Soldered it so that I can plug the wire to Arduino. Below is the picture of Dongle -

Now the problem is, I am not able to find any way to use this with Arduino. I can see there are some standard WiFi modules like WiFi Shield and ESP Module available which are mostly used. But is it necessary to use those modules only ? Can we use this USB module and if yes then how ?

The details information about this WiFI dongle is available at below path -
https://www.amazon.in/gp/product/B0088TKTY2/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

No, you will not be able to use this dongle. This device needs to be plugged into a USB Host device, which an Uno is not capable of doing for several reasons, one of which is that this dongle would require some driver on the host device, and the only drivers made for it are likely made only for Windows/Mac/Linux type operating systems.

Most of the WiFi shields communicate with Arduino over a non-USB protocol like SPI or I2C, while it looks like this dongle is a purpose-built chip that communicates with a host over USB only, not I2C or SPI.

It's likely you can find an ESP8266 device for a lower cost than this dongle would cost, however. The ESP8266 device would communicate with an Arduino via UART (serial port).


How can I filter out noise from ADC lines without delay or signal change? I'm working on a project with a joystick and I'm trying to keep everything a simple and low latency as possible. I am reading the pots with the onboard 10bit ADC on the ATmega 32u4 but may be upgrading to either a 16bit ADC or 24 bit ADC. How can I filter noise out of the signals?

The Atmel ATmega328 datasheet, section 24.6.1, recommends that you drive the analog input pin with an output impedance of 10 KOhm or less. Also, it recommends that you remove high-frequency components with a low-pass filter. (That low-pass is sometimes called an antialiasing filter).

The simplest possible low-pass filter is a resistor and a capacitor.

  +5V                        +5V
   |                          |
(sensor)---resistor---+---(Arduino)
   |                  |          |
   |            capacitor        |
   |                  |          |
  GND----------------GND--------GND

Contrary to popular belief, it is not possible to make an antialiasing filter in software.

For an initial low-resolution prototype, a quick rule of thumb is to pick the RC time constant at least 10 times as long as the time between samples.

So if you are sampling at around 1000 Samples/second (i.e., a sampling interval of 1 millisecond), then 100 Ohms of resistance and (roughly) 100 uF ceramic capacitor may be adequate.
(The RC time constant here is RC == 100 Ohms x 100 uF = 10 milliseconds).

Many joysticks already have a relatively high output impedance; you'll need to use a resistor with that much less resistance to compensate.
(Sometimes you don't need any additional resistance; but you still need that capacitor between the Arduino analog input pin and the Arduino ground pin).
(Many sensors have an output impedance more than 10 KOhm; people who use them are pretty much forced to use an op-amp chip to get clean signals).

Entire books have been written on signal filtering.
In addition, there are many other techniques for getting higher resolution analog signals, higher speed data collection, and trading off between them --
but they are probably overkill for reading the position of a joystick.


Cannot compile F() macro with R"string" I am trying to compile the following code:
logger.log_info(F(R"(some text here that may take
    multiple lines
    and here it is done.)"));

But the compiler exists with the following error:

error: unterminated raw string

I am able to use either R or F, but not both together. How should I be able to use them together?

If you put:
    #define DO_NOTHING(s) (s)

    DO_NOTHING(R"xyz(Hello
    World)xyz")

you can see g++ choke on preprocessing the raw string literal in the macro invocation with the latest esp8266 board package as of writing (version 2.7.4).  This comes with g++ 4.8.2 for xtensa.
    ~/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-4-b40a506/bin/xtensa-lx106-elf-g++ -E  donothing.h

You may need to adjust the command-line for your system.  donothing.h is just the macro and invocation described above.
Result:
# 1 "donothing.h"
# 1 "<command-line>"
# 1 "donothing.h"

donothing.h:3:13: warning: missing terminating " character [enabled by default]
 DO_NOTHING(R"xyz(Hello
             ^
(R"xyz(Hello World)
donothing.h:4:10: warning: missing terminating " character [enabled by default]
 World)xyz")
          ^
      xyz")

This does not happen with g++ 9.3.0 on an amd64 Linux target.
As a workaround you can reconstruct (more or less) what the F() macro does with the following:
    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      static const char pgm_str[] PROGMEM = (R"xyz(Hello
    World)xyz");

      Serial.println(FPSTR(pgm_str));
      delay(4000);
    }


Serial Commmunication between two arduino I want to send the voltage magnitude received on an analog pin of atmega328Pu to another arduino uno using Serial communication pins TX and RX and display the value on the receiver arduino's Serial monitor.

Transmitter Arduino Code:

void setup()
{

  Serial.begin(9600);

  pinMode(A0, INPUT);

}

void loop()

{

  int voltage=analogRead(A0);

  Serial.println(voltage);

}

Receiver Arduino Code:

void setup()

{

  Serial.begin(9600);

}
int incomingByte = 0;

void loop()
{
if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
}

}

Problem: Now the Problem I am facing is that Serial Monitor of Receiver arduino does not shows anything, it remains blank. Please analyse this system help me in finding out the best way to get around this problem?

The problem is that a serial connection usually connects two devices, in your case it's three (sensor arduino, receiving arduino and your pc).

To get around this you have to use an additional software serial on different pins on the receiving arduino (unfortunately the atmega328 has only one hardware serial interface).
As long as you don't have to send anything from pc to the receiving arduino and from the receiving arduino to the sensing one you could try to simply disconnect the wire receiving-TX to sensing-RX and see if it works. In this latter case you could actually get rid of the receiving arduino at all.

Edit: another important point was mentioned in JRobert's answer: grounds of devices communicating with each other must always be connected!


Extract binary numbers from infrared sensor that uses I2C bus I have an infrared sensor(OTI 301) which in order to display the desired temperature I need to apply a formula that depends on 3 binary numbers extracted from the sensor itself. I have tried different approaches but no success yet to extract these binary numbers. Please see link for the data sheet of the sensor where you can see useful information regarding the formula and the binary numbers. https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view also here is the code I have tried in the Arduino IDE. Also, attached picture are the needed commands to extract the data from the second data sheet, https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view.

#include <Wire.h>
byte val[2] = {0x20,0x80};
void setup() {
Wire.begin(0x20);        // join i2c bus (address optional for master)
Serial.begin(9600);  // start serial for output
}

void loop() {

  //master writter
  Wire.beginTransmission(0x20); // transmit to device
  Wire.write(val,2);
  //Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  //master reader
  Wire.requestFrom(0x20, 6);    // request 6 bytes from slave device

  while (Wire.available()) { // slave may send less than requested
  Serial.println("H");
  char c = Wire.read(); // receive a byte as character
}

delay(500);
}

There are likley two problems:

An invalid device address is used. The device address is 0x10 and the Arduino Wire library expects it that way (and not in the shifted version with read/write bit).
Your code uses two separate transactions, however the datasheet specifies a single transaction with a repeated START condition for separating the write and read part.

So an improved version looks like so:

#define DEVICE_ADDRESS 0x10

void loop() {
    Wire.beginTransmission(DEVICE_ADDRESS);
    Wire.write(0x80);  // readout command
    Wire.endTransmission(false); // stop sending without ending transaction (repeated START)
    Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
    uint8_t data[6];
    for (int i = 0; i < 6; i++) {
        data[i] = Wire.read();
    }
}


The Capacitive Sensor library on a D1 Mini I want to set up a hand-made capacitive sensor on a D1 Mini, as in this tutorial, so that I can get specific capacitive readings. But I couldn't get the CapacitiveSensor library to work with the D1 Mini. Just to make sure I wasn't crazy, I fired up an Arduino Nano knockoff, and the library worked just fine.

I found a thread from early 2017 on this topic, which had various suggestions, none of which worked.

Does anyone know either how to make this library work with a D1 Mini, or another efficient way of getting capacitive readings on digital pins on a D1 Mini?

Actually it looks like the answer was in the early 2017 thread all along. I switched to a 400k resistor and it works! (I've only verified this just for pins 5 -> 6, although I'd expect it works for any combination of pins not including D0 / D3 / D4 / D8.)

However, a caveat here -- it doesn't work well. With an Arduino and a ~6m resistor, you can sense a change in capacitance from several inches away, with a nice continuous increase in capacitance as you get closer. At least for me, the 400k resistor had very low operational range, only maybe 1/2 in. or so, and even then the differences were subtle. But increasing to a 600k resistor replicated the initial problem -- I just got the "-2" error message consistently. And going down to a 200k resistor just decreased the range as you'd expect. So there seems to be a very narrow operational range of resistance for the D1 Mini, with less utility than the Arduino.


How the output of a bicycle dynamo can be displayed using Arduino? I am on a project in which I need to make bicycle dynamo frequency meter.
The power generator’s output should vary with the speed of the wheel.

Which parts do I need to make it work?

The project should look like: : http://www.lanzo.se/experiments/dynamo/dynamo.html
                 or http://practicalphysics.org/bicycle-dynamo-and-oscilloscope.html

-->without oscilloscope ( which is replaced with Arduino and panel )

The first thing to look at before you connect the bicycle dynamo to an Arduino is what type of signal / voltage it generates. The link you've provided: http://www.lanzo.se/experiments/dynamo/dynamo.html gives you the answer. It's an AC signal which varies between +4V and -4V (It could be much higher if you spin it faster). On the Atmega328P data sheet under "Absolute Maximum Ratings" it says "Voltage on any Pin except RESET with respect to Ground -0.5V to VCC +0.5V". Obviously, -4V exceeds the -0.5V maximum so don't connect it directly to an Arduino.

The signal from the dynamo to Arduino must be limited to between 0V and 5V (for an Arduino operating at 5V). The answer on how to accomplish this is a general electronics question and should be asked on a different forum e.g. https://electronics.stackexchange.com/questions/132330/8v-ac-signal-into-3-3v-digital-input-pin

The "frequency meter" part of your question is easy to build with an Arduino. You could use an Uno or something smaller like a Pro Mini with a 16 x 2 LCD display and this library: https://github.com/k3ng/k3ng_antenna_tuner/tree/master/libraries/FreqCounter. An I2C backpack for the LCD is only a dollar more and makes the wiring much easier. To use the backpack you'll need this library: https://github.com/marcoschwartz/LiquidCrystal_I2C.


Error building Arduino WiShield Flash example: 'dflash' was not declared in this scope I'm using WiShield library from: https://github.com/jcmuller/WiShield

What is wrong with this library?

The code:

/*
 * Web Server using Flash
 *
 * A simple web server example using the WiShield 2.0
 * that reads the manufacturing ID from the Flash and
 * displays it on a webpage.
 */

#include <WiShield.h>
#include <dataflash.h>

#define WIRELESS_MODE_INFRA    1
#define WIRELESS_MODE_ADHOC    2

#define FLASH_SLAVE_SELECT 7
#define WIFI_SLAVE_SELECT  10

// Wireless configuration parameters ----------------------------------------
unsigned char local_ip[] = {192,168,1,2};   // IP address of WiShield
unsigned char gateway_ip[] = {192,168,1,1}; // router or gateway IP address
unsigned char subnet_mask[] = {255,255,255,0};  // subnet mask for the local network
const prog_char ssid[] PROGMEM = {"ASYNCLABS"}; // max 32 bytes

unsigned char security_type = 0;    // 0 - open; 1 - WEP; 2 - WPA; 3 - WPA2

// WPA/WPA2 passphrase
const prog_char security_passphrase[] PROGMEM = {"12345678"};   // max 64 characters

// WEP 128-bit keys
// sample HEX keys
prog_uchar wep_keys[] PROGMEM = {   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,     0x09, 0x0a, 0x0b, 0x0c, 0x0d,   // Key 0
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 1
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 2
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00    // Key 3
                            };

// setup the wireless mode
// infrastructure - connect to AP
// adhoc - connect to another WiFi device
unsigned char wireless_mode = WIRELESS_MODE_INFRA;

unsigned char ssid_len;
unsigned char security_passphrase_len;
//---------------------------------------------------------------------------

unsigned char mfg_id[4];

void setup()
{
  initShield();
}

// This is the webpage that is served up by the webserver
const prog_char webpage[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type:     text/html\r\n\r\n"
                                ""
                                ""
                                "
Flash Mfg ID: 000 000 000
"
                                "<form method=post action=\"/upload\" enctype=\"multipart/form-data\">"
                                "FS Image Upload"
                                "
"
                                "<input type=file name=i size=40> &nbsp; <input type=submit value=\"Upload\">"
                                "</form>"
                                ""
                                "";

void loop()
{
  dflash.read_id(mfg_id);

  WiFi.run();
}

void initShield()
{
  // there is some contention on the SPI between the flash and wifi chip,
  // so disable both devices at the beginning until they are properly
  // initialized by their respective libraries
  pinMode(FLASH_SLAVE_SELECT, OUTPUT);
  digitalWrite(FLASH_SLAVE_SELECT, HIGH);
  pinMode(WIFI_SLAVE_SELECT, OUTPUT);
  digitalWrite(WIFI_SLAVE_SELECT, HIGH);

  // now init dataflash
  dflash.init(FLASH_SLAVE_SELECT);

  // now init wifi
  WiFi.init();
}

I doubt anything is wrong with the library, but in your initShield and loop methods you refer to a variable called 'dflash' which does not seem to be defined anywhere.


Error:expected declaration before { token. (Havent i already declared it?) I'm getting the error message:

sketch_dec31d.ino: In function 'void setup()':
sketch_dec31d:20: error: expected unqualified-id before '.' token
sketch_dec31d.ino: In function 'void loop()':
sketch_dec31d:29: error: expected primary-expression before '.' token
sketch_dec31d:31: error: expected primary-expression before '.' token
sketch_dec31d:33: error: expected primary-expression before '.' token
sketch_dec31d:43: error: expected primary-expression before '.' token

This is the code:

#include <dht.h>     // what pin we're connected to
#define DHTTYPE DHT11   // DHT 11
#define DHT11_PIN 2

// Initialize DHT sensor for normal 16mhz Arduino

String TextForSms ;
String humidity = " Humidity: %";
String temperature = "   Temperature";
String sign = " *C";

char fromc; // character from computer

void setup() {
  Serial.begin(9600);
 // Serial.println("DHT11 test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  int h = dht.readHumidity();
  // Read temperature as Celsius
  int t = dht.readTemperature();
  // Read temperature as Fahrenheit
  int f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  int hi = dht.computeHeatIndex(f, h);

   TextForSms = TextForSms + t + "," + h + ",";
Serial.println(TextForSms);
     TextForSms = "";
   delay(1000);

}

Probably the error is in line

dht.begin();

You did not declare the variable dht, probably of type DHT11 ? You can find the correct class name in the dht.h header file.

After checking this (random) website compute heat index arduino about DHT11 I see the line:

DHT dht(DHTPIN, DHTTYPE);

Which you also have to add, probably as:

DHT dht(DHT11_PIN, DHTTYPE);


Coin recognition using Coin Accepter in Arduino Uno I'm working on a vending machine project and I'm using CH-926 and an Arduino Uno for that. I've already set the coin accepter for different number of coins and respective output pulses. I'm unable to get the desired output for this. With every coin I insert the output varies even when I put the same coin.

int pulse = 0;

void coin_value() {
  pulse = pulse + 1;
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.println("Ready to be collected");
}

void loop() {
  if (digitalRead(2) == HIGH) {
    attachInterrupt(0, coin_value, FALLING);

    if (pulse == 3) {
      Serial.println("50");
    }
    if (pulse == 2) {
      Serial.println("20");
    }
    if (pulse == 1) {
      Serial.println("10");
    }
  }

  pulse = 0;
}

For each coin there are different specific pulses which helps to recognize the coin.int pulse=0;.

So when I insert coin 1 then the output should be 10, for coin 2 the output should be 20 and for coin 3 the output should be 50.

Your code is faulty in a number of respects.

pulse should be declared volatile, i.e.

volatile int pulse = 0;

That is because it can change in an interrupt service routine.

You should only do attachInterrupt once, in setup.

Your code to display the count will be timing dependent. What if you happen to display the count after one pulse has arrived, but before they all have? Then you set the count back to zero.

Better would be something like this, untested however:

volatile int pulse = 0;

void coin_value() {
  pulse = pulse + 1;
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.println("Ready to be collected");
  attachInterrupt(0, coin_value, FALLING);
}

void loop() {

  if (pulse > 0)
    {
    delay (1000);   // let the other pulses arrive
    if (pulse == 3) {
      Serial.println("50");
    }
    if (pulse == 2) {
      Serial.println("20");
    }
    if (pulse == 1) {
      Serial.println("10");
    }
    pulse = 0;  // clear for next time
  }

}

(Edited to add)

Even then your test for 1/2/3 might fail if the coin acceptor sends the pulses twice. Then you might get 2/4/6 pulses. You probably need to display something if there is another count, eg.

  if (pulse == 3) {
    Serial.println("50");
  }
  else if (pulse == 2) {
    Serial.println("20");
  }
  else if (pulse == 1) {
    Serial.println("10");
  }
  else {
     Serial.print ("Unexpected number of pulses: ");
     Serial.println (pulse);
  }


Can I port a project built on Arduino Uno to a standalone ATmega328 using the exact same code? I'm building an IoT power usage monitor in which the data is logged using a RTC and an SD card module and a web app hosted on an ESP8266 gives access to this data. My question is can I use the exact same code (with libraries like "ESP8266.h") on a standalone ATmega programmed using Arduino as ISP?

Almost all of my projects are roll-your-own-duinos with Atmega 328p chips, with code generated for an "Arduino/Genuino Uno" board. Many of them use an ESP8266-01 board as a WiFi interface. I either run the entire board at 3.3v or use a daughter-board that interfaces the ESP to a 5v environment.

If you're porting code from an actual Arduino Uno, there is nothing to do except to make sure your pinouts are the same between the Arduino and the RYO-duino. Otherwise, make all your pin definitions constants and group them together in such a way (e.g. with #ifdef / #else / #endif) that you can easily enable one or the other group just before you compile.

Update:

  There's a bit more required, for example, the clock rate needs to
  match or the timing will be off ...

I did gloss over the power & clock since the question hadn't asked about departures from the Uno's design. But yes, a RYO will need a compatible power supply and a matching clock rate, to be able to assume an arbitrary sketch could be run on it successfully. To make the RYO look like an UNO, it will need 5v power and a 16 MHz crystal, just as the Uno design provides.

If a RYO is designed be other than like an Uno, considering power source, clock rate, fuse options, DIP instead of an SMT, then there is nothing to support the supposition that a port from an Uno could succeed without modifying the code for those differences.


How can I make push buttons react to being pressed instantly? I am making an Arduino alarm clock. I am checking for the state of a button. If it is clicked, I increment the button counter. If the counter is divisible by 2, it is mode 0, if not, it is mode 1. I have small delays in the code for each mode to help the lcd clear itself. Those delays are preventing the buttons to reacting to my touch, because there is likely a delay during that time.

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=0;
int minutes=0;
const int modePin=6; //button
int prevModeState=0; //prev state of button
unsigned long timer;
int modeState;//current state
int mode=0;//mode of alarm
int buttonCounter=0;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("00:00");
pinMode(modePin, INPUT);
}

void loop() {
modeState=digitalRead(modePin);
if(prevModeState!=modeState){    //this is the part where I check for the state
  if(modeState==HIGH){
    buttonCounter++;
  }
}
prevModeState=modeState;
if(buttonCounter%2==0){
  mode=0;
}
else{
  mode=1;
}

if(mode==0){
  timer=millis();
  if(timer%600==0){
     minutes++;
    if(minutes==60){
        minutes=0;
        hours++;
        }
     if(hours==24){
        hours=0;
     }
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    lcd.setCursor(6, 1);
    writeTime();
    delay(200); //delay
    }
}
else if(mode==1){
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("Set Time:");
  lcd.setCursor(6, 1);
  writeTime();
  delay(500); //delays

}
}

void writeTime(){
if(minutes<10){

      if(hours<10){
        lcd.print(String("0")+hours+":"+"0"+minutes);
      }
      else{
        lcd.print(hours+String(":")+"0"+minutes);
      }
    }
    else{
      if(hours<10){
         lcd.print(String("0")+hours+":"+minutes);
      }
      else{
         lcd.print(hours+String(":")+minutes);//possibly split if problems arise
      }

    }
}

How can I edit my code?

You have a few options, including using interrupts. But I believe the most important thing is: "do not use delay()" and you might not even need to use interrupts...

Have a look on this nice post from Nick Gammon: http://www.gammon.com.au/blink with some tips about non-blocking coding.

Also a very simple "Blink LED" example: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


UART communication, is it possible to use only the TX line? I am trying to connect an ESP-01 with an ArduinoMega through the serial port of both, as they use different voltage levels I would need a voltage divider between the TX pin of the Mega (pin 1) and the pin RX of the ESP-01 (pin 4) , it is not difficult to do, but I just need to "send data" from ESP-01 to Mega, then I have a question and it is as follows:

If I just need to send data from one device to the other, could I just connect the TX pin of the ESP-01 to the RX of the Mega? If I do so, will I receive data in the Mega?

Greetings

Yes.

You can connect only the the line with which the ESP-01 transmits to the Arduino's receiver, and accomplish one-way data transfer.

However, the ESP will have to be willing to transmit without prompting, and you will not be able to use the Arduino to setup or configure it.  Further, you will not be able to use any in-band signalling to ask the ESP to refrain from sending, so you will have to be sure that your Arduino sketch is generally ready to claim any input which may arrive, and that if there are periods when it is not, the behind-the-scenes serial buffer is large enough.

There's also the question if it is safe to connect the ESP transmit pin directly to the Arduino receive.  In the intended direction of operation, it is.  But should you ever load code on the Arduino which uses that pin as a GPIO output, there is some risk of damage to the ESP.  It's up to you to decide if careful usage will be enough to prevent that; if not, you may want to try something like a 1K series resistor and a schottky diode to clamp the line to the ESP's 3.3v supply, in a way that diverts the current from any accidental 5v output around any internal protection diode that may have more limited power handling.


Connection problem with Arduino Mega 2560 and GSM shield ( official M10) As I don't want to stack the shield over the mega 2560 board, I try to connect only the pins that used for GSM communication. Here are my connection:

Pin 3 on Mega <==> Pin GSM Rx on Shield

Pin 10 on Mega <==> Pin GSM Tx on Shield

Pin 4 on Mega <==> Pin 4 on Shield

Pin 5V on Mega <==> Pin Vin on Shield

Pin GRD on Mega <==> Pin GRD on Shield

Code I used is from the Examples library, GsmScanNetworks:

#include <GSM.h>

// PIN Number
#define PINNUMBER "8888"

// initialize the library instance
GSM gsmAccess;     // include a 'true' parameter to enable debugging
GSMScanner scannerNetworks;
GSMModem modemTest;

// Save data variables
String IMEI = "";

// serial monitor result messages
String errortext = "ERROR";

void setup()
{
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("GSM networks scanner");
  scannerNetworks.begin();

  // 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);
    }
  }

  // get modem parameters
  // IMEI, modem unique identifier
  Serial.print("Modem IMEI: ");
  IMEI = modemTest.getIMEI();
  IMEI.replace("\n","");
  if(IMEI != NULL)
    Serial.println(IMEI);
}

void loop()
{
  // scan for existing networks, displays a list of networks
  Serial.println("Scanning available networks. May take some seconds.");
  Serial.println(scannerNetworks.readNetworks());

    // currently connected carrier
  Serial.print("Current carrier: ");
  Serial.println(scannerNetworks.getCurrentCarrier());

  // returns strength and ber
  // signal strength in 0-31 scale. 31 means power > 51dBm
  // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
  Serial.print("Signal Strength: ");
  Serial.print(scannerNetworks.getSignalStrength());
  Serial.println(" [0-31]");

}

Questions:

After opening the serial port, only a line "GSM network scanner" is read. Seems that the program is stuck ongsmAccess.begin(PINNUMBER), how shall I fix that?
Is it a must that I shall supply 5V 2A power to the shield seperately in order for the shield to work? (with connection mentioned above, the ON led light on the shield does turns on with an orange light)
For the PINNUMBER defined in the program, my SIM has default PIN 8888. I checked with a mobile phone that the SIM card does work. But my phone shows that the SIM card is not locked with PIN. So shall I define the PIN as 8888 for ''?

EDIT:

GSM shield link

Note for using GSM shield with Mega

* And yes! The shield did work when stacked! (Orginally I don't want to bend pin 2...but...unnh...stacking and bending out pin 2 did work)

* Tried the examples "GSMScanNetwork" and "SendSMS", works fine. But for "GsmWebServer", an IP address is shown, but when I enter the IP address on my browser, chrome/ie says they cannot find the IP address.....Any clues?

* And does the status LED on the GSM board have anything to do with power? It goes on and off and on and off.....

* For question 1 & 3, PINNUMBER is set to ''. Worked fine.

I have done this, and had (some limited) success.

A couple of your connections are wrong;
Connect both the pin 7s on the shield and MEGA, not the pin 4s. Pin 7 is the reset pin - I think that GSM.begin resets the shield before doing anything. This might help with Q1.

Make sure that you use the regulated 5V output on the MEGA, and not the Vin to power your shield. Vin is whatever voltage is connected to the MEGA power socket, and could damage your shield. I personally have not noticed any difference when powering the MEGA+Shield from USB or external 12V supply.

I had problems with interference when I used wires to connect shield to MEGA. The stacking seems to have reduced this problem, but not eliminated it by any means...

The GSM Web server is unlikely to work except maybe from within your SIM provider's own network. Some of the limitations are mentioned here;
https://www.arduino.cc/en/Tutorial/GSMToolsTestWebServer


Can anyone help me spot where my buffer overflow might be occuring? I'm using dtostrf() to transcribe a float into a string for my touchscreen. I'd leave it as a float, but my screen orientation library function only works with a string.

So I have a char array, then a float value. then dtostrf().

char buffer[6]
float X; //changes each loop with incoming sensor data from pixy camera
float thingposition = X * .0064  //float calculations are performed.

void loop(){
Camera.Get_X();   //retrieves X from the camera. waits until X has been recieved via UART serial
dtostrf(buffer, 5, 2, thingposition) // writes float to string with a controled decimal place and all that - dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf);
Tft.drawString(buffer, 70, 215, 5, WHITE);   //print output to screen
}

Note that this is a simplified version. In my code I also have methods for overwriting my last string value on the LCD when the new one has changed.
I also have several "if" conditionals that control whether I write the buffer value to the screen or instead send an error message. Those things do not seem to be causing me problems though, except to say that my buffer overflows only occur when I cause the sensors to flip the conditionals at just the right interval.

For example, when I place my hand in front of the camera, that triggers the error message. Take my hand away, and then the number "thingposition" is printed to the screen. But if I time my hand just right, the buffer overflows and numbers loop across the screen. Usually this freezes the whole sketch. The best I can figure is that since dtostrf() does not check bounds, and since the calculated float values can be longer than the buffer has room for, that sometimes dtostrf() tries to write too many digits to the buffer. Something timing-related seems to trigger the problem, but what I need is some way to prevent the overflow in the first place.

I've tried rounding "thingposition" to a certain number of sigfigs, but I can't seem to truncate it at the desired decimal point. That shouldn't matter though, since dtostrf has controls for the minimum total length including the decimal point, as well the number of digits after the decimal. I also tried making sure that the last byte in my char array is null by adding this right after dtostrf():

stringval[5] = NULL;   //make sure buffer is null-terminated to prevent buffer overflow

I've tried doubles, different ways of rounding, and anything I could find, but the problem has persisted for several weeks and a few steady days worth of searching for a solution. I'll be glad to provide further information if anyone has any ideas on what to try. Thanks everyone.

The problem with using "simplified code" is that your 'simplification' may not have captured your problem. But I will take your code as given and assume that it's correct (which I'm afraid it isn't).

var
    char buffer[6]  // Won't compile - no semicolon (';')
    float X;        // Uninitialised value - could be 1000000000000
    float thingposition = X * .0064 // No ';', and .0064 of 10000000000 is huge!

void loop(){
    Camera.Get_X(); // Should this be "X = Camera.Get_X();" ?
    dtostrf(buffer, 5, 2, thingposition)  // No ';'. You NEED to recalculate thingposition!

If the above code is a good representation of what you've got, you seem to be assuming that you define the formula once (in the thingposition line), and it automatically applies that formula, like Excel, when you change its input, X. Sorry, programs don't work that way.

Once you calculate thingposition, it becomes independent of where it came from. If you change other variables, thingposition kees its value until you explicitly change it.

How do you fix it? You recalculate thingposition every time:

var
    char buffer[6];      // Hopefully big enough - see below
    float X;             // Used by Camera.Get_X()
    float thingposition;

void loop(){
    X = Camera.Get_X();        // Get X from Camera
    thingposition = X * .0064; // Calculate thingposition
    dtostrf(buffer, 5, 2, thingposition);

Note that dtostrf() will try to obey your size parameters, BUT. If the float is larger than your maximum size, it WILL print out the full number anyway. That is, if thingposition is 1000, it will produce 5 characters all right: "1000.". But if it's 1000000, it will produce "1000000" which is seven characters. You need to ensure that buffer is big enough to handle larger numbers than you expect.

Do the maths. If X is guaranteed to be between 0 and 255, then multiplying it by 0.0064 will result in a maximum value of 1.632, so the above dtostrf() woud produce " 1.63". No problem!


Moving motion sensor? Long story short, I'm trying to build some form of device that you can wear and it will detect when something moves behind you. I wanted to use PIR sensors for the motion detection, but I have no idea if they can detect objects if you're moving. Any ideas?

OP didn't really specify the actual requirements other than detecting movement and wanting to use PIR while in motion.

PIR (Passive Infrared) implies looking for warm bodies.  In general, PIR motion sensors look for the presence of thermal radiation that moves between the individual parts of the sensor.  On TV it is shown that you can fool PIR detectors by carrying a large cold panel between you and the detector. ;-)

They also detect reflected thermal radiation that is moving.   It does not need to be a direct view.  So moving the sensor around outside would pick up a lot of reflected IR sunlight changes.  And certainly incandescent lights would do the same since about 80% of their emitted energy is IR.

The way they are designed, (with lenses like a bee's eye) they are more likely to detect your own arms swinging back as you walk and generate false alarms that way.  So you would need some kind of mounting arrangement that only allowed it to "see" directly behind.  And even then only in a dark room.

PIR sounds like a lot of trouble for an application like this.  (As in, probably not suitable)

Here is a decent instructable that explains how they work:  http://www.instructables.com/id/PIR-Motion-Sensor-Tutorial/

If PIR is not a be-all requirement, here is an alternative to be considered, even though it would require some work to get it right:

Radar

Here is a nice, inexpensive radar unit that will arrive eventually on the slow boat, and the price is right.  It could work well in motion if you program it to detect changes that occur at speeds faster than your own motion.  And you would want to program a pulse gate it so it only senses objects at more than a certain distance behind you.

Anyway, in the spirit of hacking, I offer this idea:

LFS-DC04 2.7GHz Microwave Radar Module DC 5V

http://www.ebay.com/itm/262662221979

It is small enough to wear.  But it is slow, so I wouldn't recommend using it to detect intruders with violent intent.  I believe it would be good mounted on a bicycle-pulled trailer or something like that, to make sure you know if something is coming up on you too fast.

Product Introduction:

1.Model:LFS-DC04
2.Frequency:2.7GHz
3.Size:40*22mm
4.Input Voltage:DC 5V
5.Output Type:level signal output
6.Connection Method:VCC,GND connect with positive negative input, OUT,GND signal connect with output
7.Installation Height:1-3.5m
8.Sensing Ditance:5-8m
9.Delay Time:30s(quick testing mode is 4s)
10.Sensing Angle:360 degree

It is low enough power that it shouldn't fry your kidneys.  Probably very similar to sitting next to a high-power WiFi router all the time, or like having a cellphone in your pocket with WiFi and 4G turned on all the time.


Why can I not use pointers instead of array with PROGMEM? I'm currently changing some libraries to use flash instead of RAM for string storage so that I do not run out of SRAM on a project.

Some strings in the library are declared in this manner:

const char *testStringA = "ABC";

This is different to how I normally see this done:

const char testStringB[] = "DEF";

However, I think that these two are equivalent when declared const and initialised in the declaration. Both work fine in code.

I attempted to move these to flash:

const prog_char *testStringC PROGMEM = "GHI";

I then found that this didn't work. It was producing gobbledegook when printed.

However, following the more usual pattern of:

const prog_char testStringD[] PROGMEM = "JKL";

works fine.

I can see in the disassembly:

00000068 <testStringC>:
  68:   04 01                                               ..

0000006a <_ZL11testStringD>:
  6a:   4a 4b 4c 00                                         JKL.

So it is clear the pointer and PROGMEM results in the string/array not being initialised.

Why is this?

Example code:

#include <avr/pgmspace.h>

const int BUFFER_LEN = 20;

const char *testStringA = "ABC";
const char testStringB[] = "DEF";
const prog_char *testStringC PROGMEM = "GHI";
const prog_char testStringD[] PROGMEM = "JKL";

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

void loop()
{
    char buffer[BUFFER_LEN];

    Serial.println(testStringA);
    Serial.println(testStringB);

    strncpy_P(buffer, testStringC, BUFFER_LEN);
    Serial.println(buffer);

    strncpy_P(buffer, testStringD, BUFFER_LEN);
    Serial.println(buffer);

    delay(1000);

}

Well, this question has been wisely answered in an answer to Stack Overflow question C: differences between char pointer and array.

Basically, what you're declaring as PROGMEM with,

const prog_char testStringD[] PROGMEM = "JKL";

is both the array and the memory it points to, that is, the elements of the array, both in current's scope stack. Whereas with:

const prog_char* testStringC PROGMEM = "GHI";

you declare a PROGMEM pointer to a constant string that may stay elsewhere in memory, but not declared as a PROGMEM string.

Though I did not test that, but you should try to declare:

const prog_char* testStringC PROGMEM = F("GHI");

to actually allocate the pointed string within the PROGMEM space. I guess it should be working, using Arduino's F() macro, which adds a lot of boilerplate code to actually have the same result as the array declaration.

As said in comments, if not in a global context, the PSTR() macro could be used instead of the F() macro.

Simpler is better: use the array declaration, not the pointer one!

Cf that other answer, the __flash qualifier is a third solution ;-)


How do I know if bootloader flash was successful? I just bought a raw Atmega328p microcontroller. I am attempting to flash it with the Arduino bootloader.

The process seemed relatively straightforward as I had just followed the posted tutorial (https://www.arduino.cc/en/Tutorial/ArduinoISP).

Everything seemed to go fine and I even got a message after the second attempt with a message of 'Burning Bootloader Done'. I am targeting the device as if it were an Arduino Pro Mini.

I then moved onto program the chip with an Arduino sketch via the FTDI programmer. However, the sketch upload fails. It says that it is out of sync. I verify that everything is wired up correctly, yet it still fails. I then remove power to the Atmega328p chip (just to see if I get a different error) yet I still get the out of sync error.

This has me questioning whether or not the bootloader was even flashed in the first place. So how do I know if the bootloader actually was successful? A couple things to note:

When I power on the Atmega328p, the PB6 output starts blinking immediately. I would assume that if there were a bootloader, there would be a moment of pause until the regular program starts. Should I expect to see a pause if the bootloader is on the chip?
If the bootloader is on the chip, should I even expect to see the Atemga328ps default heartbeat?
When I flash the chip with the bootloader, it says that it could take up to a minute to finish. However, it only takes 6 seconds until it states 'Bootloader Finished Burning'. This seems like it's happening too fast.

If we determine that the problem is due to something else (i.e. not the bootloader), I will begin a new discussion. However, right now I'm just curious how I know if the bootloader is actually on the device.

See my page about burning bootloaders.
The sketch there has a "verify" option so you can check if the bootloader was burned.
See my post What happens when code is uploaded using the bootloader?.
With Optiboot installed you expect to see three flashes:

As for your other problems, see Have I bricked my Arduino Uno? Problems with uploading to board.
You may well not have set the fuses correctly.


My mega only works on 1.0.1 IDE My mega usb/serial adapter died some time ago, so I bought an external FTDI programer wich I got working on 1.0.1 IDE. I can load any program to the mega, even complex led matrix driver I wrote myself so the ATmega works fine and the external FTDI board does too. Strangely enough I if I want to update the IDE (tried once on 1.0.5 and yesterday downloaded 1.6.5) I get an

 avrdude: stk500v2_getsync(): timeout communicating with programmer

When this problem occurs, I see that the programmer board recieves something (it has Rx and Tx LED's) the Mega resets but never sends any data back, which does happen on 1.0.1 IDE.
This happens on my pc, and on a laptop son no pc related problems.
I'd keep using this version but now I got an OLED display I want to drive (SSD1306 from waveshare) but I can't compile u8glib on 1.0.1 but I can on 1.6.5, however I can't get a simple blink example to upload with this IDE.

I suspect the DTR pin (reset pin) is handled differently and that makes the mega stay resetting until it times out.
What can be the problem here? How can I get more info from the console to solve this?

You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.

The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.


The most practical plug socket I am starting some Arduino's projects with different sizes (very small based on Arduino Nano and bigger using Arduino Mega). These projects will be manipulated by students and they will connect and disconnect many times the wires. I will try to not use breadboard if I can. In order to develop very versatile projects, the idea will be to use very useful plug sockets. Currently I have no idea of which kinds of plug sockets I can use.

Do you have any idea about the existing plug sockets (from 2 to 6/8 wires) and which one it is preferable to use?

Complements:

Some shields and components I already have and want to use have sometimes some plugs sockets (similar to this) but sometimes only some classical pins
I want also to build my own shields by integrating plug sockets to the arduino or to another shield
Some parts will be also composed by small electrical circuit on which I want to integrate plug sockets aswell
I will also use LiPo batteries (for example this one which have a connector I can't buy currently because I don't know the reference)
Communications will be also achieved using SPI and I2C

Ok, so more info from the OP:

non-electrical engineering students needs a prototyping platform
minimize possible damages, support hot plug-and-play
not too expensive

Dedicated connector
I suggest using standard subD9 connectors. Sensors shall have male pins, while the control board female socket (this makes very hard to do accidental short circuits on the control board). We were using these connectors in a daily basis in a lasershow system, and I was very statisfied. Inexpensive, easy to solder, works with a wide range of cables or separate wires.
In many cases, you can integrate the sensor into the housing of the connector. For example, an IR receiver, an accelerometer, etc. fits well.
You can use off-the-shelf serial cable extenders which makes it very versatile.
Since it is a D shaped connector, there is only one possible way to connect a sensor to the mainboard, and we're golden.
Dedicated connector light
NSL25 and NSG25 are my favorites:
http://www.soselectronic.hu/?str=371&artnum=4927&name=nsl-25-2-g
http://www.soselectronic.hu/?str=371&artnum=4934&name=-nsg-25-2
Although these are inexpensive wire to board connectors, it is very hard to misconnect them. Criping is a PITA, but you can purchase pre-crimped connectors with wires such as http://www.soselectronic.hu/?str=371&artnum=6175&name=-p-35003
One 3 wire female connector with wires costs about 50 USD cent.
Note though that in this case, the control board has the male connectors. By accidentally dropping a coin to the connector, or using a screwdriver, it is easy to run into short circuits. This leads us to the next plan...
Any inexpensive connector with proper electric protection
Probably the most inexpensive solution is to use standard headers and pins. Here you may also wish to buy ready made cables, than start crimping yourself:
http://www.soselectronic.hu/?str=371&artnum=6171&name=-p-2543
This however opens up a can of worms of misconnection:

connection by one or multiple pin off
connection in reverse direction
shorting the pins on the board

Against sorting, you shall have a multifuse on the power pins, say, 250mA. On each IO pin, you shall have a series resistor of 470 ohm, this ensures that no miswiring can destroy the Arduino.
On the sensor-side, things are a little more tricky. You need a shottky (or an equivalent P fet diode) to ensure that reverse polarity connection will not destroy your sensor. If the sensor has output pins, also use a series 470 ohm resistor.
Considering all the hassle, using a standard subD9 connector is a way easier:

it has enough dedicated pins for I2C, SPI, and a generic IO for dumb sensors
the pins can handle more current, and there are more pins you can connect in parallel to have enough power for small motors
it is impossible to misconnect (once all sensor sockets use identical wiring)

Don't forget ESD protection
In any case, it is a good idea to have some sort of ESD protection whenever you have connectors, and wires, and rough external world.
Have at least a TVS diode on the power pins (say, an 5.8V or 6V unidir TVS will do). On IO pins you can use a simple series resistor, or you can opt for a TVS.
During hot plug and play, it may happen that sensitive sensors get powered in a strange way. E.g. first 5V then the sensor output is getting connected, but no GND for a short moment. Some sensor may get damaged in this case. Use diodes to fix this.
For sensors requiring sudden current peaks (e.g. WIFI, or a motor), add at least 470uF/16V electrolyte capacitor right to the sensor end of the connector. This way once the sensor is connected to a long extension wire, you still have acceptable power to use in sudden current peaks.
Some sensors (e.g. IR receivers) are sensitive to power glitches. Consult their datasheet, use the suggested RC filtering network on the power pins.


Addressable RGB strip works fine individually but cannot set all LEDs to full white I have a 5 meter strip of 12V digital RGB LEDs. The chip is WS2811 (see photo of IC). There are 50 addresses on the strip.

Using the FastLED library, I am able to run the "FirstLight" example that chases full white with a single address at a time, up and down the length. That works fine. So I know they individually perform properly.

However, if I set all LEDs to full white (255), the first few addresses look white but then the higher the address, the more red it is. See photo below. The strip starts in the center of the reel.

#include <FastLED.h>

// How many leds are in the strip?
#define NUM_LEDS 50

// Data pin that led data will be written out over
#define DATA_PIN 5

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

// This function sets up the ledsand tells the controller about them
void setup() {
    // sanity check delay - allows reprogramming if accidentally blowing power w/leds
    delay(2000);
    Serial.begin(115200);
    Serial.print("### SETUP ###");

      //Both strips are ordered BRG
      FastLED.addLeds<WS2811, DATA_PIN, BRG>(leds, NUM_LEDS);
      //FastLED.addLeds<UCS1903, DATA_PIN, BRG>(leds, NUM_LEDS);

}

void loop() {

   for (int i = 30; i < NUM_LEDS; i++) {

       leds[i] = CRGB::White;

   }

   FastLED.show();
}

To debug, I tried turning on just the last half. The result was still problematic:

for (int i = 30; i < NUM_LEDS; i++) {

    leds[i] = CRGB::White;

}

I then tried setting all LEDs to white at half brightness, and that looks much better, but the LEDs at the outside are still off-color compared the inside:

I've tried setting the whole strip to full blue, and that works fine.

I also have another nearly identical LED strip that instead uses the 1903 chip. The same code (initialized for 1903 instead of WS2811) works just fine on the 1903 strip!

Other things I've ruled out:

I'm using a bench power supply capable of 5A, this strip pulls less than 1.5A on full white.
I have verified the supply holds at 12V
I have not let the LEDs heat up while coiled in the reel. I make sure to unplug them after observing their color.

What could cause this on the WS2811 strip while the 1903 strip works perfectly?

I would suspect that it is a voltage drop in the power rails caused by the current draw. Probably cheap construction with copper tracks that are just too thin and so have too high a resistance.

To combat it you will need to inject power into the strip at various points along it.  Initially to prove the theory you can try connecting the power to both ends of the strip and see if the "dull" spot is half way along the strip.  If it is, then it's certainly a voltage drop.  (incidentally, a voltage drop will cause the blue LEDs to fade out first making it go yellow-red. Then the green ones would probably be next, making it go red).

Then, once proved, you will need to add extra power connections into the strip at the middle of any dim sections and feed the voltage directly in at those points.


How to read data directly from lcd display Referring to post: LCD data read and show on computer
It was not clear what the final code is. Could you post the code and schema again, and if possible, an explanation of how it works?

My problem:

I need to read the information of a lcd 20x4 display, which is controlled by a PLC (which has the protected hex code), and send the data through the serial port.

For this I am using an arduino one to do the reading. I connected the arduino in parallel with the display data bus, to try to read the bits and convert later.

This is the schematic I'm using:

Note: I have placed 1k resistors to make the pulldown on each pin, to avoid reading errors.

With this code:

The problem is that I'm having these results in reading:

No matter what appears on the screen, they are always invalid characters.
If someone identifies where my problem is, I'll be very grateful.

I would recommend ditching the the digitalRead in this case - it is performed sequentially, and is rather slow.
As you only need to read 8 input lines, consider using Port register: The Arduino Uno comes with a total of three Ports which "hold" all of the I/O pins.
Those are

PORTB = Digital Pins 8 through 13 plus the crystal pins
PORTC = Analog Input 0 through 5, reset pin
PORTD = Digital Pin 0 through 7

Since you need the RX and TX lines (Digital pin 0 and 1) for your serial communication, you will have to split the signal onto two registers.

I would recommend connecting D0 through D3 to Digital Pins 8 through 11 for the first four bits (meaning they'll go to bits 3 to 0 of Port B), and D4 through D7 to Analog Pins 0 To 3 (meaning they'll go to bits 3 to 0 of Port C).
RW goes to Pin 7, RS to Pin 6, E to Pin 5.

The code you would then use to read the data would be this:
    uint8_t byte_displaydata = 0x00;
    uint8_t RW = 7;
    uint8_t RS = 6;
    uint8_t E = 5;

void setup() {
  Serial.begin(1200); //perhaps increase this a bit
  pinMode(RW, INPUT); //some speed is lost compared to register manipulation, but that is likely insignificant
  pinMode(RS, INPUT);
  pinMode(E,INPUT);
  DDRB &= ~((1 << DDRB0) | (1 << DDRB1) | (1 << DDRB2) | (1 << DDRB3)); //technical not necessary since they're initialized with 0
  DDRC &= ~((1 << DDRC0) | (1 << DDRC1) | (1 << DDRC2) | (1 << DDRC3));
  PORTB &= ~((1 << PORTB0) | (1 << PORTB1) | (1 << PORTB2) | (1 << PORTB3)); //disable internal pullups
  PORTC &= ~((1 << PORTC0) | (1 << PORTC1) | (1 << PORTC2) | (1 << PORTC3));

}

void loop() {
  if(digitalRead(RS) == HIGH && digitalRead(E) == HIGH){
    byte_displaydata = 0x00; //reset byte_displaydata
    byte_displaydata = PINB << 4; //push PINB bits 3 to 0 to bits 7 to 4
    byte_displaydata |= (PINC & 0x0F); //filter PINC bits 3 to 0 and OR them into result bits 3 to 0
    Serial.println(byte_displaydata,BIN);
  }
}

Please note that I have not tested this, and only recently have gotten started in AVR / Arduino.
If anyone can look this over, I'd greatly appreciate it.

Source: Microchip ATmega328P datasheet, Arduino pin mapping


Can I safely power my UNO and DC motors with the 5v1A and 5v2.1A ports on a USB charger? I have USB charger battery pack with two output ports (Fremo C510).  One is marked as 5 volts 1 amp, and the other as 5 volts 2 amps.

I'm building a toy robot and would like to run the UNO off of one of those ports, and the motors off of the other.

Can I safely do that?  I have two main concerns:

Can I safely power the arduino with that current?
If I power both the motors and the arduino from that source (two usb ports connected to the same battery), will I still have to worry about spikes from switching the motors on and off?  I don't know how those ports are wired to the actual battery inside.

You can power the Arduino from either side, since it will only draw what it needs, and most arduinos are powered from a .5 amp USB port. But you'll want to reserve the higher current side for the motors.

Make sure your motors' total draw (including starting current) doesn't exceed the 2 amps available.

Unless you can find out for sure that the two power ports are isolated from one another, you're better off to assume they are not and provide motor spike damping yourself.


Phase and frequency correct PWM mode Arduino Mega 2560 I wrote a code to generate 1kHz Phase and frequency correct PWM signal from Arduino mega 2560 using timer 4. When I try the code with fast PWM mode it works perfectly. But phase correct mode didn't provide the expected outcome. What is wrong with my code?

unsigned int b=7999;
void setup() {
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);

TCCR4A=0;
TCCR4B=0;
//Timer 1 1kHz mode 8: phase and frequency correct pwm oc1a non inverting

TCCR4A=(1<<COM4A1)|(0<<COM4A0)|(0<<WGM41) ;//| (0<<WGM40)
TCCR4B=(1<<WGM43)|(0<<WGM42);//
ICR4=b;
OCR4A=int(b*1/5);
TCCR4B|=(1<<CS10);
TIMSK4 |=(1<<OCIE4A);
}

void loop() {
  }

ISR(TIMER_COMPA_vect){

  }

The output of the code for different duty cycles are as below
Duty cycle:0.2 (OCR4A=b/5)

Duty cycle:0.2 (OCR4A=b/2)

You wrote:

  TIMSK4 |= (1<<OCIE4A);

and then never defined ISR(TIMER4_COMPA_vect). As soon as you get a
compare match, you get a bad interrupt, which defaults to resetting your
program and restarting again from reset vector.


Problem with PWM pins on Arduino uno I am working on an Arduino Uno Project of a car with two motors. The motor driver board is an L9110 H-Bridge. Here is how everything is connected:

And here is the code I am trying to run:

//Define all the pins for the motors
#define motorPinA1 3  //A pin right motor
#define motorPinB1 5  //B pin right motor
#define motorPinA2 6 //A pin left motor
#define motorPinB2 9 //B pin left motor

//Movement functions
void stopCar();
void frwrd(int motorSpdRight, int motorSpdLeft);
void back(int motorSpdRight, int motorSpdLeft);

//Global Variables
int motorSpeedRight = 0;  //The speed of the right motor
int motorSpeedLeft = 0;   //The speed of the left motor

void setup() {
  //Movement
  pinMode(motorPinA1, OUTPUT);
  pinMode(motorPinB1, OUTPUT);
  pinMode(motorPinA2, OUTPUT);
  pinMode(motorPinB2, OUTPUT);

  //Serial Monitor for debugging
  Serial.begin(9600);

  motorSpeedLeft = 100;
  motorSpeedRight = 100;

  frwrd(100, 100);
  delay(2000);
  stopCar();
  delay(1000);

  back(100, 100);
  delay(2000);
  stopCar();
  delay(1000);
}

void loop() {

  Serial.print("Forward");
  Serial.print("\n");

  frwrd(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

  back(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

}

// functions we need to make the code run
void stopCar(){
    Serial.print("Stoping Car\n");
    // Put motor 1 in halt
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, 0);

    // Put motor 2 in halt
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, 0);
}

// For the farward direction A pins will be high
void frwrd(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in forward motion with speed = motor_spd
    analogWrite(motorPinA1, motorSpdRight);
    analogWrite(motorPinB1, 0);

    // Put motor 2 (Left) in forward motion with speed = motor_spd
    analogWrite(motorPinA2, motorSpdLeft);
    analogWrite(motorPinB2, 0);

    /*
    // Put motor 1 (Right) in forward motion
    digitalWrite(motorPinA1, HIGH);
    digitalWrite(motorPinB1, LOW);

    // Put motor 2 (Left) in forward motion
    digitalWrite(motorPinA2, HIGH);
    analogWrite(motorPinB2, LOW);
    */
}

// For the backward direction B pins will be high
void back(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in backward motion with speed = motor_spd
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, motorSpdRight);

    // Put motor 2 (Left) in backward motion with speed = motor_spd
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, motorSpdLeft);

    /*
    // Put motor 1 (Right) in backward motion
    digitalWrite(motorPinA1, LOW);
    digitalWrite(motorPinB1, HIGH);

    // Put motor 2 (Left) in backward motion
    digitalWrite(motorPinA2, LOW);
    digitalWrite(motorPinB2, HIGH);
    */
}

Pins 3, 5, 6 and 9 are PWM so I can alalogWrite() to them and control the speed of the motors. Code uploads fine but although both motors move forward normally motor 1 (on pins 3, 5) doesn't move backward. The strange thing is that if I use digitalWrite (the commented code in the two functions) instead everything works normally but the motors move in full speed so it's not usable for my project. I have tested all the pins in other projects and everything worked fine so I know my board is not faulty.

I have also taken some measurements with a multimeter while the code was running. In the forward motion, both pairs of pins measured 1.95V. In the backward motion, the problematic pins measured 0V.

Any help would be appreciated!!

Try different pins than 5 and 6, because those PWM generators share the timer with delay(), which I'd interpret as: You use analogWrite() to set the timer to fire every n microseconds to toggle your PWM signal  -- and then you call delay(1000), which sets that same timer to fire in one second to continue the program.

Pins 10 and 11 do use a different timer, so try these.

Reference: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

  "The PWM outputs generated on pins 5 and 6 will have
  higher-than-expected duty cycles. This is because of interactions with
  the millis() and delay() functions, which share the same internal
  timer used to generate those PWM outputs."


ESP8266 Upload hex file Arduino IDE I am using ESP12E Wifi module, using library based on Arduino. Is there any way I can upload hex file of the project to esp8266 using Arduino or any tool?
I need to send hex file instead of code to my client. Is there any way?

I see the main question you are asking is: "I need to send a hex file instead of code to my client. I want to keep my source code with me."

The mechanics of the final hardware solution aren't supplied but I will guess that your client is also using an Arduino or at least the same Atmel chip that you have in your Arduino, and will be using that chip to control the ESP8266.

When you build your sketch, there is a .hex file created that you can send to your client.

There are a few ways to keep the hex file around, and IDE 1.6.5 and up has a way to easily find this file:

Sketch > Export Compiled Binary
The sketch will compile.

Sketch > Show Sketch Folder
The .hex file will be in the sketch folder.

You can send this hex file to your customer.

If he is using an Arduino or ATMega-based solution to connect to the ESP8266, then the hex file can be loaded into his Arduino or to his Atmel chip. However, the Arduino IDE doesn't support import of hex files at this time.

Your client would have to load that hex file onto the Arduino with an ISP programmer of some sort. There are many ways to do this, and the best one for you will depend upon your circumstances and your client's skill set.

If the client is using an Arduino or has just embedded the same ATmel chip that is in your Arduino into his solution, you could also just program your Arduino, and then send him that chip.


Conflicts with USB and external power supply I want to power an Arduino Leonardo with an external power supply and simultanously communicate via USB. I have read some other threads on this topic, therefore, I know that if one supplies more than 7V over the power jack, the board will use the external power supply in this case.

My suspicion is rather concerning the ground connection. From the schematic, I can tell that the USB ground is connected via a tiny coil to the board ground, so with DC it is shorted. Wouldn't that cause problems if the computer's USB ground is at a different potential than the external power supply of the board, resulting in a voltage between the two grounds? What if this voltage is up to several Volts?

Thanks a lot!

Why do you suspect a potential difference? Where is th 7V coming from? If the 7V power supply is free floating and used for nothing else, there is no source for potential difference.

A typical wall wart will have a free floating output.


74HC595N shift register with separate power supply I have wired up a 74HC595N with an Uno, and the standard 8 LEDs and resistors, per the usual youtube "shift register tutorial" and written a sketch that works.  For example, I wrote a routine to walk from values 0 through 255 and light up the LEDs as a hex number.  So my wiring and code are correct.

As an experiment, I tried disconnecting the pin on my breadboard's power rail that goes to the Arduino 5V, and the pin that goes to Arduino ground, and instead plugged in a breakout (if that's the right word) that plugs into the breadboard and provides 5V on the power rail when a 9V battery is plugged into it.  (It's been checked with a multimeter, it's just under 5V.)  The only pins still going to the Arduino are for DS, SHCP and STCP.

Things sort of work, but not really.  It seems clear to me that the shift register keeps getting reset. (All of the LEDs briefly light back up in each iteration as I'm running my hex number display routine.) All of the other wiring remains the same; specifically OE-bar is still connected to ground on the power rail.  But it still seems to reset.

Can someone explain why the shift register keeps resetting?  Also, am I doing anything that might burn up the Arduino and/or shift register?

All ground connections except those which are explicitly isolated must be connected together in order to provide a common voltage reference for the circuit. Any breaks in the ground connection can result in gross misbehavior such as what you are experiencing.


Where can I find the Arduino Mega core code? I am looking to modify the receiving hardware serial buffer size for the Arduino Mega. To do so I need to redefine it in HardwareSerial.h in the core code. However, I can't seem to find a copy of the Arduino Mega core code. A search for HardwareSerial.h on my computer returns no results. I am using Windows 10.

Arduino Mega is part of the Arduino AVR Boards core. The location of that core depends on whether you are using the core version included with the Arduino IDE or have updated the core version using Boards Manager(in which case there will be multiple copies of the core installed on your computer but only the updated version will be used). The easiest way to find it is:

Tools > Board > Arduino/Genuino Mega or Mega 2560
File > Examples > EEPROM > eeprom_clear
Sketch > Show Sketch Folder
Move up folder levels until you reach the avr folder.
If there is a version number folder in the avr folder then open that folder.
HardwareSerial.h and the rest of the core files are located in cores/arduino.

Remember that you will need to redo any changes to the core after any Arduino IDE and/or Arduino AVR Boards updates.


Taking voice input from raspberry pi and sending converted text to arduino to turn on relays I have one raspberry pi B+ and an Arduino uno. I know how to control a relay from an Arduino. I searched a tutorial about voice recognition on arduino but got to know that arduino cannot take in audio inputs. It can just sense if there is an audio. Now I think that I can use the raspberry pi to take inputs and convert it to text with software and then send it to arduino. Then Arduino can control the relay. Is there any way to do that?

Probably the easiest way would be to set up a serial link between them, although there are many ways it could be done; This link looks helpful, as both boards have serial capability, or USB with Pi as host & Arduino as slave should work perfectly well (but a more expensive bit of wire).

An alternative might be an Arduberry?

On the Pi side, there is a sort of meta-answer here - obviously, the Raspberry Pi stackexchange would be the better forum to look at that half of the project.


Debouncing Multiple Buttons I'm creating a binary calculator with my Arduino. This will take two different binary numbers and add them together. I am focusing right now on the Byte One Input screen. For this, I can use two buttons, the left to change to selected bit to either 0 or 1 when pressed, and the right button to move to the next bit, or when at the end, to move to the next screen. I am having difficulty with the debouncing of the buttons.

Right now, the debouncing is not working and the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button.

Any help would be great!

Fixed Code: See accepted answer below.

       #include <LiquidCrystal.h>
/*(RS, E, D4, D5, D6, D7)*/
LiquidCrystal lcd(12,11,5,4,3,2);
#include <Button.h>

int page = 0;
int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int con = 80;
char btn_push;
int pos = 0;

const int button1Pin = 8;
const int button2Pin = 9;
int button1State = HIGH;
int button2State = HIGH;
int lastButton1State = HIGH;
int lastButton2State = HIGH;

unsigned long debounceDelay = 50;

//****************************************************************setup*****************************************
void setup() {
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);

  Serial.begin(9600);
  analogWrite(6,con);
  mylcd.begin();
  lcd.print("Welcome");
}

//************************************************************loop************************************************

void loop() {

  int reading1 = digitalRead(button1Pin);
  int reading2 = digitalRead(button2Pin);

  if (reading1 == lastButton1State &&
      reading2 == lastButton2State)
    return;  // do nothing if no change

  delay (debounceDelay);  // debounce

  // re-read so we can catch both buttons down at once
  reading1 = digitalRead(button1Pin);
  reading2 = digitalRead(button2Pin);

  // save for next time
  lastButton1State = reading1;
  lastButton2State = reading2;

  if (reading1 == LOW && reading2 == HIGH)     // first one down
    btn_push = 'D';
  else if (reading1 == HIGH && reading2 == LOW)  // second one down
    btn_push = 'U';
  else if (reading1 == LOW && reading2 == LOW)  // both
    btn_push = 'S';
  else
    return;  // nothing interesting

 Serial.print("btn_push = ");
 Serial.println(btn_push);

    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    }

}

// The rest is the same, excluding the functions that are no longer needed

Your first problem is here:

char ReadKeypad(){
  if(button1.isPressed() && !button2.isPressed()){
    return 'D';
  }
  else if(button2.isPressed() && !button1.isPressed()){
    return 'U';
  }
  else if (!button1.isPressed() && !button2.isPressed()){
    return 'N';
  }
  else if (button1.isPressed() && button2.isPressed()){
    return 'S';
  }
}

The compiler gives a warning, which you should pay attention to:

In function 'char ReadKeypad()':
warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

The warning basically is that if no button is pressed you are returning an undefined value. It would be better to add to the end:

return 0;  // no button pressed

Then later on in page1 function:

  for (int i; i<16; i++){
    lcd.print(binary[i]);
  }

Another compiler warning:

In function 'void page1()':
warning: 'i' may be used uninitialized in this function [-Wmaybe-uninitialized]
       for (int i; i<16; i++){

You haven't initialized i so it could have any value. That should read:

  for (int i = 0; i<16; i++){
    lcd.print(binary[i]);
  }

Ditto further down.

If I add some debugging here:

void MainmenuBtn(){
  btn_push = ReadKeypad();
  Serial.print ("btn_push = ");
  Serial.println (btn_push);
 // WaitBtnRelease();
}

And then press a button, I see:

btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D

So that is registering as many presses, not just one. You should test for "has the button state changed?". That is:

Is the button closed now?
Was it closed before?
If the two are different, then the button has just been pressed.

Adding debugging prints is very helpful in general when things aren't going to plan.

If you had added those extra prints to your MainmenuBtn function you would immediately have seen that it looked like the button was pressed hundreds of times (until you let go) rather than once.

  the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button

Exactly. Since it is treating a button press as a multiple press you would expect exactly that to happen. Effectively you have built in a very fast auto-repeat (unintentionally).

Edited to add:

Your code is so confusing I've rewritten the state change stuff.

#include <LiquidCrystal.h>
/*(RS, E, D4, D5, D6, D7)*/
LiquidCrystal lcd(12,11,5,4,3,2);
#include <Button.h>

int page = 0;
int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int con = 80;
char btn_push;
int pos = 0;

const int button1Pin = 8;
const int button2Pin = 9;
int button1State = HIGH;
int button2State = HIGH;
int lastButton1State = HIGH;
int lastButton2State = HIGH;

unsigned long debounceDelay = 50;

//****************************************************************setup*****************************************
void setup() {
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);

  Serial.begin(9600);
  analogWrite(6,con);
  mylcd.begin();
  lcd.print("Welcome");
}

//************************************************************loop************************************************

void loop() {

  int reading1 = digitalRead(button1Pin);
  int reading2 = digitalRead(button2Pin);

  if (reading1 == lastButton1State &&
      reading2 == lastButton2State)
    return;  // do nothing if no change

  delay (debounceDelay);  // debounce

  // re-read so we can catch both buttons down at once
  reading1 = digitalRead(button1Pin);
  reading2 = digitalRead(button2Pin);

  // save for next time
  lastButton1State = reading1;
  lastButton2State = reading2;

  if (reading1 == LOW && reading2 == HIGH)     // first one down
    btn_push = 'D';
  else if (reading1 == HIGH && reading2 == LOW)  // second one down
    btn_push = 'U';
  else if (reading1 == LOW && reading2 == LOW)  // both
    btn_push = 'S';
  else
    return;  // nothing interesting

 Serial.print("btn_push = ");
 Serial.println(btn_push);

    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    }

}

// The rest is the same, excluding the functions that are no longer needed

I made the buttons INPUT_PULLUP so that they normally read HIGH if not pressed, thus LOW means pressed (therefore the switches should be wired from the digital pin on one side to Gnd on the other side).

It still isn't perfect but that should give you something to play with. Add some more debugging prints to see what is going on in the other functions.


How to get constant readings from hall effect sensor Im using linear Hall effect sensor to sense the magnetic flux at a point.
Values from the sensor is read using arduino's analogRead function.
This value changes as other devices are connected to arduino, like lighting a LED.

My guess is since the current passing through the Hall effect sensor also changes the magnetic flux and hence the reading, it might affect the reading in some way.

Any help is appreciated.. thank you.

Does the value change if there is nothing else connected?
Do you have a constant supply from your PSU?

I'm not great with electronics, but since its a real device not a theoretical device I suspect you are always going to get some fluctuation.  Could you look at adding extra components to smooth the flow to the device, possibly a capacitor?  Is it possible to supply the sensor from an independent supply that you smooth and then any devices added to the Arduino would cause an affect.

Is it possible you are not supplying enough power to the Arduino?

Could you look at taking an average with a sliding window say the last 10 values?


A word after function arguments braces I'm just reading through a header files for task code in ESP8266 SDK.
I found this line and wondering what does the word PRIVILEGED_FUNCTION after the function arguments braces means ?
void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION;

PRIVILEGED_FUNCTION is defined here, but why it's used after the function braces ?
/* Ensure API functions go in the privileged execution section. */
#define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions")))
#define PRIVILEGED_DATA __attribute__((section("privileged_data")))

That's impossible to tell without looking in the source code for that SDK.
However it will just be a pre-processor macro which probably expands out to one or more attributes, some of which may be specific to the XTensa LX106 compiler.

Update after your edit:
It places the function in the privileged_function section. That section is then placed into a specific area of memory by the linker.
To further examine what it does you will have to look in the linker script to see how it handles that section, and what that means from the chip's perspective, by cross-referencing that with the chip's technical datasheet.


Set the timeout - Ethernet Shield library Does anyone know if you can set the time for the timeout Ethernet Shield library? Let me explain:

I created a very simple function (below) that attempts to connect to an address if it is not accessible returns 0 if it is available returns 1. Problem is that when the site is not available, the microcontroller is waiting for an answer for a long time, wanted to reduce it.

uint8_t ping(const char* address)
{
    EthernetClient http;

    if(http.connect(address, 80)) {
        http.stop();
        return 1;
    }
    else
        return 0;
}

In the stream class there is a setTimeout(ms) function. e.g.

String str;
Serial.setTimeout(5000) ;
str = Serial.readStringUntil('\r');

Where this does timeout the initial connection attempt in http.connect(). Whereas I found it also important to timeout each line, as a web page may not disconnect at the end or not send anything.

int httpGetHeaders() {
  String request, response;
  int result = 0;
  long startOfHttpResponseTime;

  client.setTimeout(1000) ;
  response = "";
  inHeaders = true;
  startOfHttpResponseTime = millis();
  while((client.connected()) && inHeaders && ((long)(millis() - startOfHttpResponseTime) < HTTP_RESPONSE_TIMEOUT)) {
    String header = client.readStringUntil('\n');
    header.trim(); // trim off white spaces including CR and LF at end.
    Serial.print(F("head["));
    Serial.print(header.length());
    Serial.print(F("]:\""));
    Serial.print(header);
    Serial.println(F("\""));
    if (!header.length()) { // first blank line indicates end of headers
      inHeaders = false;
      Serial.println(F("No longer in Headers"));
    }
    else {
      if (header.startsWith("HTTP")) {
        Serial.println(F("HTTP Found"));
        int firstspace = header.indexOf(" ");
        result = header.substring(firstspace + 1, header.indexOf(" ", firstspace + 1)).toInt();
        Serial.print(F("result = "));
        Serial.println(result);
      }
    }
  }

  Serial.print(F("Result code = "));
  Serial.println(result);
  return result;
}

You may want to review the whole code at https://github.com/lansing-makers-network/StatusBotArduino/blob/master/StatusBotArduino.ino I have reduced the connection to a sequence of commands that can be used consectutively in the desired order to meet different needs. The above is just to read a headers response.


Arduino code for thermistor respiratory monitor I have designed a thermistor-based respiratory monitor which detects changes in temperature during respiration, but I am having problems with the coding part. Can someone help, my code given below is not working.

void setup() {
  Serial.begin(9600);
}
unsigned long timer;
void loop(void)
{
    delay (500)
  int sensorValue = analogRead(A0);
timer=millis ();
    if ( sensorValue<200) {
unsigned long currentTime = millis();
float period_respiration = currentTime-timer;
float breathrate= 60000/period_respiration;
Serial.println("Respirations per minute:");
Serial.println(breathrate);
  }
}

The sensor value is 600-800 during inspiration, and about 100 during expiration.

The primary reason your code doesn't work is very simple: every time you go around the loop you set

timer = millis();

and if the reading is greater than 200 you set

currentTime = millis();

but those two statements are executed just a few microseconds apart, so the difference between them (in milliseconds) will almost always be zero (it might occasionally be one if you happened to cross a tick boundary, but it will never be more than that).

There are a few other problems with the logic of your code, which I think you'll understand when you look at some code that will work. Try something like this:

enum respState {
    Inhaling,
    Exhaling
};
unsigned long prevRespTime = 0;
unsigned long currRespTime = 0;
respState currentRespState;
int movingAvgRespRate = 0;

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

void loop()
{
    //delay(500);
    // don't need to delay because we'll only fire once per inhalation and once per exhalation
    int sensorValue = analogRead(A0);

    if ((sensorValue > 300) && (currentRespState == Exhaling))
    {
        currentRespState = Inhaling;
        prevRespTime = currRespTime;  // save time from last cycle
        currRespTime = millis();

        float period_respiration = currRespTime - prevRespTime;
        float breathrate = 60000 / period_respiration;
        Serial.print("Inhaling /tRespirations per minute: ");
        Serial.println(breathrate);
    }
    else if ((currentRespState == Inhaling) && (sensorValue < 200))
    {
        currentRespState = Exhaling;
        Serial.println("Exhaling");
    }
}

The above code will give you the instantaneous respiratory rate, which probably will jump around a bit more than you would like. You probably want to add some dependency on prior history (hysteresis) to smooth it out a bit. One easy way is to put this through a low-pass filter algorithm to get a moving average value for the respiratory rate. That way the rate goes up when you breathe faster and down when you breathe slower but it doesn't instantaneously jump around on every breath.  Here's what that might look like:

// Global variables
enum respState {
    Inhaling,
    Exhaling
};
unsigned long prevRespTime = 0;
unsigned long currRespTime = 0;
respState currentRespState = Exhaling;
float breathrate = 0;
int movingAvgRespRate = 0;

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

void loop()
{
    //delay(500);
    // don't need to delay because we'll only fire once per inhalation and once per exhalation
    int sensorValue = analogRead(A0);

    if ((sensorValue > 300) && (currentRespState == Exhaling))
    {
        currentRespState = Inhaling;
        prevRespTime = currRespTime;  // save time from last cycle
        currRespTime = millis();

        float period_respiration = currRespTime - prevRespTime;

        if (period_respiration == 0)
            breathrate = 0;
        else
            breathrate = 60000 / period_respiration;

        Serial.print("Inhaling /tResp Rate: ");
        Serial.print(breathrate);

        if (movingAvgRespRate == 0)
            movingAvgRespRate = breathrate;
        else
            movingAvgRespRate = (int) ((0.2 * breathrate) + (0.8 * movingAvgRespRate));

        Serial.print("/tAvg Resp Rate: ");
        Serial.println(movingAvgRespRate);
    }
    else if ((currentRespState == Inhaling) && (sensorValue < 200))
    {
        currentRespState = Exhaling;
        Serial.println("Exhaling");
    }
}

This code compiles, but I did not happen to be near an arduino with a sensor, so I didn't run it -- there could be issues, but this should be enough to put you on the right track. Good Luck!


Informations lost in a string At first, I sorry if I make some English faults but I'm French.

So, I'm making a connection between a client and an Arduino Uno. I receive all data that I need but when I send a response to my client some characteres are lost.
I receive this format : GET /?b=7&p=100$ (for exemple)
And my Arduino sends this to my client : GET /?b=7&p=1d

This is the function where I get all data from my client :

void read_data(int *state, int *progress_program){
  // Check if there is a client
  EthernetClient client = server.available();
  if (client) {
    url = "";
    index = 0;
    Serial.println("\nnew client");
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.println(c);
       if(c != '$') { // if end of char
          url[index] = c;
          index++;
        } else {
          url[index] = '\0';
          int i;
         Serial.print("\n");
          for(i=0;i<index;i++)
            Serial.print(url[i]);
          if(interpret(state, progress_program)){
            action();
            delay(100);
          }
          answer(client);
          break;
        }
      }
    }
    url[0] = '\0';
    // give the web browser time to receive the data
    client.stop();
    delay(100);
    Serial.println("\nclient disconnected");
  }
}

And the response sent to the client :

void answer(EthernetClient client){
  Serial.print("\nResponse"); // debug
  delay(100);
  client.print(url);
  Serial.print("Response Sent");
  delay(100);
}

With client.write(url) there is the same problem.

Have you got a solution?
thanks

So, the solution was very simple,
My pointer "url" received a constant null string with url=""; at the beginning. To initialize a string as null we need to make this :

 url[0] = '\0';

thanks


Incomplete serial string input I am using an Arduino M0 Pro and have a device connected via Pin 0 and 1 of it. So I am using the predefined Serial5 interface to receive data from it. I have the following code snippet/method that tries to read an answer from Serial5 if it is available. Otherwise it returns an empty string.

String read_answer() {
  String str = "";
  // Check if bytes are available
  if (Serial5.available()) {
    char c;
    // Read an character unless the read() method returns -1
    // The -1 is identical to 255
    while ((c = Serial5.read()) != 255) {
      // Append the read character to the string array
      str.concat(c);
    }

    // Output the string on the serial debug interface
    Serial.print("Read: \"");
    Serial.print(str);
    Serial.print("\"\n");
  }
  // Return the read string
  return str;
}

If I send an the following string "ABCDEF HIJKL MNOPQR" via an FTDI towards it the first times it correctly printed :

Read: "ABCDEF HIJKL MNOPQR"

But suddenly it just stops reading the complete string. The output is something like that:

Read: "ABCDEF HIJKL MN

It is just cut off and everything stops working, over and over again. It might be a very stupid mistake but I don't know where to check next. If I missed something to explain or more context is needed pls tell me.

Your code has no idea when the string is finished. At the moment it is just waiting until the receive buffer is empty (Serial.read() returns -1), but since serial is a slow protocol that could happen at any time, not just at the end of the string.

You need something to terminate your string so it knows when the end is. The most common way is to use a line feed character (\n, character 10) or a carriage return (\r, character 13) or a combination of the two.

char c;
while ((c = Serial5.read()) != '\n') {
    if (c != 255) {
        str.concat(c);
    }
}

// Output the string on the serial debug interface
Serial.print("Read: \"");
Serial.print(str);
Serial.print("\"\n");


Can arduino nano drive two circuit I am building a robot snake with a bunch of servos and ov7670. As I see, ov7670 operate with 3.3v and servos needs 5v. I will use Lipo battery for servos for this I need to connect ground pin of arduino and input of battery. But For ov7670, I already connect the ground pin of arduino. Can I connect ground with a jumper to another breadboard to connect with lipo battery and servos or I need two arduino nanos?

You can use a common ground in fact it's the normal thing to do with external circuits such as relays, servos etc


Adafruit libary and CC3000 shield I have a Arduino Uno and a CC3000 shield. When I run the example code for Webclient from Adafruits libary it works perfect.

When I switch out address for reading a corresponding text file from my own server the code completes sporadically. The output in the serial window stops at differens places every time.

Does anyone have any idea how I can fix this?

The Adafruit points to this URL: http://www.adafruit.com/testwifi/index.html
While mine points to this URL: http://a.sjsd.li/test/test.html

I have arrived at a solution that works for me. Instead of using Adafruit library I have adopted Sparkfuns library.

Some adjustments in the setup for the pins:

#define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       5   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno
#define SD_CS           4   // Chip select for SD card

Then some adjustemnt in the block for the HTTP request:

client.print("GET /index.html HTTP/1.1\r\n");
client.print("Host: ");
client.print(server);
client.print("\r\n\r\n");
client.println();
Serial.println();

This is not a solution for the Adafruit libary. But it helped me to continue my project.


Uno with LCD acting strangely - power issue? I've got a Uno (Elegoo UNO R3) running with
- Ethernet shield (Kuman K15),
- 4 relay board (Elegoo 4 Channel DC 5V Relay Module with Optocoupler )
- Matrix Orbital 2041 LCD connected via I2C (11mA typical, 90mA with backlight)
- A series of buttons connected

The Uno is currently running plugged in via USB to my macbook pro.

All of these devices are powered by the 5V pin on the Arduino.

The LCD goes wonky from time to time, and other times will work fine, it starts flashing the backlight, and just behaves oddly, sometimes even rebooting, when buttons are pushed (which activate the relays).

I'm wondering if this a power issue, perhaps the Uno isn't able to supply enough current to run everything.

My reading indicates that the USB port should be able to provide ~400mA, and when on an external supply I should able to draw 900 mA when using an external power adapter.  However even with on an external supply (12v, 2A) I still have these issues.

Any thoughts would be much appreciated.
Thanks

System resets can be caused by power droop and by noise at the Reset pin, among other reasons.  The problems mentioned could be due to power issues, or to electrical noise, or to wiring issues.

The total current draw apparently could approach or exceed the 400 mA mark mentioned in the question.  With all four relays on, and coils drawing 50 mA each, that's 200 mA.  LCD backlight and Arduino current make another 100, after which the ethernet shield could bring the total above 400 mA.

However, having the problems persist even with an external supply in use would suggest the root of the problems isn't power – if, of course, the external supply actually is supplying power directly to some of the peripherals, rather than via the regulator on the Uno.

When relays switch, they typically produce an electrical noise pulse.  If this is the problem, it could be mitigated using ferrite beads, chokes, noise filters, etc.  Using a separate power supply for +5 V to the board also should help.

Wiring issues include ground bounce and ground loops.  If you are using a breadboard, there may be poor ground or power connections.  Check that the grounds of peripheral devices and external supplies are solidly connected by decent wire and/or connected at a common point.


Arduino Mega2560 Hardware ID Do all Arduino Mega2560's have the same VID/PID identification numbers when seen by a PC as a device? I am planning on designing I specific driver to work with the 2560 and wondering if I will be able to use the same driver for multiple Arduino. Can anyone confirm this? Thanks!

VIP/PID is realized by Atmega16u2 driver which implements USB device driver. Probably all revisions of *Arduino Atmega2560*s has implicitely the same VID/PID. Each piece has unique serial number. But you can upload own firmware into 16u2 to modify USB as you wish (ideally using LUFA library). It's clean solution for production hardware because you cannot use Arduino VID because of USB rules.


Using Arduino to control a high voltage DC device I am an amateur hobby electronics enthusiast , and given the situation , I too am trying to make a contactless hand Sanitizing system like everyone else. My project requires a 36V DC solenoid valve to be actuated through the arduino momentarily for the sanitizer to drop. Obviously I will be using a relay module to electrically isolate both the circuits. But I don't have a 36 V DC adapter . So what is the best way to power up the solenoid valve? Batteries are available to me right now? How do I calculate how many 9v batteries do I need ? How many AH would they require ? Would they get drained too fast?

Batteries are going to be annoying because they're run out and have to be recharged/replaced. A mains power supply would be easier to "set and forget.
I did a google search on "36V DC power supply" and found a 4A power supply from "Alitove" on Amazon for $22.99 US. That should be fine. (Assuming you are somewhere with 120VAC mains power. If you live somewhere with 240VAC mains power you would need a different unit, but since I found one, I would expect a google search in your region would find one for your area.)
I would suggest using a logic-level MOSFET transistor + flyback diode to switch your DC power. That's easier to do than a relay (That would require another power supply.)


Why does servo library conflict with irremote? I am building an Arduino Mega robot. I am planning to use IRremote.h library for it. I am using multiple libraries in my code and I do not know which timers are taken. I always get errors when compiling because I am using the wrong timer. Here are the libraries I am using:

#include <LiquidCrystal.h>
#include <Wire.h>
#include <RTClib.h>
#include <Servo.h>
#include <IRremote.h>

I get this error message when compiling:

libraries\IRremote\IRremote.cpp.o: In function `__vector_42':

C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\IRremote/IRremote.cpp:339: multiple definition of `__vector_42'

libraries\Servo\avr\Servo.cpp.o:C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\Servo\src\avr/Servo.cpp:95: first defined here

c:/users/lyuba/desktop/nick/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

Here is the code in the library where I can change the timers:

// Arduino Mega
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  //#define IR_USE_TIMER1   // tx = pin 11
  //#define IR_USE_TIMER2     // tx = pin 9
 // #define IR_USE_TIMER3   // tx = pin 5
  #define IR_USE_TIMER4   // tx = pin 6
  //#define IR_USE_TIMER5   // tx = pin 46

What can I do to use irremote library? Looking at the error message, the servo library conflicts with irremote. How can I fix this?

Usual problem is trying to use the same counter for both. For example arduino pins 6,7,8 are on TC4 and if you try to use IR on pin 6 and servo on 7 or 8, it won't work. You can't use pwms on these pins with servo either (it is possible to do it directly in registers, but in arduino framework it might get bad behavior)


Improvised Keyboard? I want to make a keyboard type panel, which will only have 7 buttons and two knobs, and connect it arduino to program it with functions, he heard that he needed the Keyboard library. but it is not available with arduino uno, which is what I work with, he heard about what I should do a keyboard mapping, it would help me explain to lay a foundation and carry out the project that I want "please do not leave me with the doubt". first of all, Thanks.

If you plan to trigger function on a PC by keystroke and want to simulate a PC keyboard on the PC with your computer than I recommend to use the keyboard lib which is able to map your button to key codes and send them to a PC over USB. But the communication over USB and the simulation of a HID (Human Interface Device) connection is (as far as I know) not possible with an Arduino. (You need a 32u4 or SAMD micro based board) like the leonardo.

But if you just plan to trigger functions, that run on the Arduino, the kb lib is not necessary. That a standard job for the Arduino and can be done with 7 input pins and 2 analog pins.


How to I measure the duration of touch with a soft potentiometer? I'm having a soft pot meter here and I would like to register the duration of the touch event. I'm having a different variable, which keeps going from 1024 to 0 , which regularly takes 60 seconds, but for every second you touch the soft pot meter the count adds 50 up to 1024. Like returning the clock backward.

How would I register/code this?

You have to go with timer interrupts. Here is the documentation: http://playground.arduino.cc/code/timer1

Roughly, when you detect a press, an interrupt is raised and the same thing goes for releasing. Using the timer values from both these events, you can accurately measure the time that the press lasted.


Program an Arduino Uno with an Atmel ICE When I connected my atmel ice to my arduino uno everything went okay.
Then I tried debugWIRE and since then I can't connect to my ATMEGA328p.
I get the error
Failed to enter programming mode. ispEnterProgMode: Error status received: Got 0xc0, expected 0x00 (Command has failed to execute on the tool)
I think one of the fuse bits is wrong but can't connect to the ATMEGA328p to change them. Does anyone have a idea what to do?

Your Ardunino is stuck in debugWIRE (The debug wire fuse is set). Here is a tutorial on how to get it back to programming mode.

In the tutorial I am using the AVR Dragon with AS6, but the process is the same with Atmel ICE and AS7.

You have to be in Debug Mode to disable debugWIRE. While in debug, Click Debug>Disable Debug Wire and Close.