Problem importing a library in .h file I have following code:

MyApp.ino:

#include "DfRobotLcdShield.h"

void setup() {
}

void loop() {
}

DfRobotLcdShield.h:

#include <LiquidCrystal.h>

When I try to compile, I'm getting the error:

In file included from MyApp.ino:1:0:
c:\temp\build5856181074637812172.tmp\DfRobotLcdShield.h:4:27: fatal error: LiquidCrystal.h: No such file or directory
 #include <LiquidCrystal.h>
                           ^
compilation terminated.
Error compiling.

When I add

#include <LiquidCrystal.h>

directly to the .ino file, it works. I'm using the latest Arduino-IDE 1.6.3.

This seems to be a general problem of the Arduino IDE: It only recognizes libraries that are included in the (primary) .ino file.
If you look at the invocation of the compiler, the path to any given library is only added if this library's header file is included in the .ino file.
I tested this with the EEPROM library. If this library is included in the .ino file, the compiler is called with
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs -I/usr/share/arduino/libraries/EEPROM /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where the important part is the -I/usr/share/arduino/libraries/EEPROM.
If I now remove #include <EEPROM.h> (but still have it in another header file which in turn is included in the .ino as in your case), the compiler call changes to
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where now the include path to the library is missing.
TL;DR
If you need to use a library, just (also) add an include to the .ino file. It doesn't cost you anything and will solve your problem ;)

#include <file> vs. #include "file"
From the gcc documentation:

#include <file> is used for system header files. It searches for a file named file in a standard list of system directories. [...]
#include "file" is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. [...]

Try #include "LiquidCrystal.h"

Or where is the library located?
Be sure the include specifies the location.

You might have to add the library location to your environment variables.


ledkeypad shield not responsive I recently purchased several of the DFRobot ledkeypad shields: https://www.dfrobot.com/product-1407.html

I have Arduino Leonardo (which also had some problems in the beginning, being recognized as modems).
My OS is Linux Mint, and I'm using the last Arduino IDE.

The library I use is the one recommended on the website of the vendor, LedKeypad.h, and works fine with the other shields of the same model from the same batch.

Some shields worked fine but I am now having trouble with one of them, which seems unresponsive. I can load for instance the blink program in the arduino, and it works, but the shield does not work. When it is plugged in, the fours dots are slightly red, and I cannot turn them off.

I tried displaying something on the serial monitor when the buttons are pushed, and only one of the 5 buttons works (the KEY_DOWN one).

Is there anything I can attempt to fix the problem ? Or should I just give up on this shield ?

... and works fine with the other shields of the same model from the same batch.

So had you considered that the shield might be faulty? Have you contacted the manufacturer or vendor for support?


EthernetUdp2 does not name a type I'm using arduino Ethernet shield 2 form arduino.org and the arduino IDE 1.7.10 also from arduino.org
the code is :

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp2.h>
#include <Twitter.h>
#include <util.h>

#include<SPI.h>

EthernetUdp2 udp;
void setup() {
  // put your setup code here, to run once:

}

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

}

and it is giving the following Error :

Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

Error compiling.

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

after Enabling Show verbose output I got :

Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

Build options changed, rebuilding all

Using library Ethernet2 in folder: C:\Program Files\ArduinoOrg\libraries\Ethernet2

Using library SPI in folder: C:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI

C:\Program Files\ArduinoOrg/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\cores\arduino -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\variants\standard -IC:\Program Files\ArduinoOrg\libraries\Ethernet2\src -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp -o C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp.o

UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

Error compiling.

any Help please

These libraries came with the IDE and were not added by me and all the includes
were added automatically after using Sketch --> Import Library --> Ethernet2

The error you see, 'EthernetUdp2' does not name a type, means exactly that - there is no type EthernetUdp2 defined.

If you look at the source of EthernetUdp2.h, you'll see that the class declaration is EthernetUDP. See:

class EthernetUDP : public UDP {
    private:
        // Private members...
    public:
        EthernetUDP();  // Constructor

      // Public members...

};

class EthernetUDP : public UDP defines a class called EthernetUDP that inherets from the base class UDP. The constructor is what gets called when you instantiate a new object of type EthernetUDP.

Replace the line EthernetUdp2 udp; in your code with EthernetUDP udp; and it should work because the types will match. For reference:

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp2.h>
#include <Twitter.h>
#include <util.h>

#include<SPI.h>

EthernetUDP udp; // <---- This works

void setup() {
  // put your setup code here, to run once:

}

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

}

As it was answered above by Cheirbriados, the library is EthernetUdp.h not EthernetUdp2.h. I'll post you an example code, but you can also analyze it by yourself, by going on tab Examples of the Arduino IDE and choosing Ethernet -> UDPSendReceiveString:

#include <SPI.h>         // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h>         // UDP library from: bjoern@cs.stanford.edu 12/30/2008

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8888;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];  //buffer to hold incoming packet,
char  ReplyBuffer[] = "acknowledged";       // a string to send back

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;


Controlling multiple 24V solenoids with Arduino I'm building a pump for which I need 4 medium strength solenoids (20-50N). 24V is probably the minimum I will need to put through them, but this is something I need to test, once I've got them working. At 24V they draw 400mA.

I've found various posts with very useful info, especially https://playground.arduino.cc/Learning/SolenoidTutorial and https://forum.arduino.cc/index.php?topic=417030.0

Will the attached sketch below work for one? If so what resistance should R1 be?
And if so can you see any problems with hooking up 4 working at different intervals?

The power supply is an LRS-350-24RS, and the Mosfet has a max gate source voltage of 35V. The 5v-24v optocoupler is off ebay -  https://www.ebay.co.uk/itm/152904980799

Many thanks for your help!!

No, it won't:

The diode D1 is backwards.
The opto-coupler is wired completely wrong.

You don't actually need the opto-coupler as long as the threshold voltage of the MOSFET is low enough for the Arduino to switch.  However if you do want (or need) to use it you should wire it like this:

simulate this circuit – Schematic created using CircuitLab

R1 is a pull-down that keeps the MOSFET off when not being turned on (just like with a button). The value doesn't matter much.  R2 is a resistor just like you use for any LED with an Arduino.  D1 must be connected reverse biased or it will just short out your solenoid. The opto-coupler must be connected with the transistor the right way around or it will not work (or melt, or create a black hole...)

To ditch the opto-coupler you can just treat it like any other load on the Arduino (as long as the MOSFET's threshold voltage VGS is below 4V):

simulate this circuit

The MOSFET, to be driven from Arduino directly, needs to have a Logic Level gate.
I've been using AOD514. Logic level gate, Low Rds, rated for 30V.
https://www.digikey.com/product-detail/en/alpha-omega-semiconductor-inc/AOD514/785-1357-1-ND/3060919
SMD only, they seem to have cancelled their thru-hole line of parts that I used to use.
I have up to 32 of them on a board with the gates driven by 74HC595 shift registers for driving 1A loads (only limited by trace widths, not the transistors), with diodes added at the coil if needed.
http://www.crossroadsfencing.com/BobuinoRev17/


How to use ESP8266-12E with PCF8574 as an I/O extender I am using ESP8266-12E with a PCF8574 as an I/O Pins Extender.
There are videos on youtube to use the PCF8574 with an ESP8266-01, but my problem is that I'm unable to analyze the pin connections with an ESP8266-12E.
In the youtube tutorial it is said that the GPIO0 AND GPIO2 will go to the SDA and SLC pins of the PCF8574, but then, in the case of ESP8266-12E, the pins will go to the PCF8547.

Thanks in advance.

Found the answer .
The data sheet of ESP8266-12E explains everything.
The pin diagram has the given tags which shows which pins we can use.


How to write a function to return matrix? I need a function to return a 2x2 rotation matrix, something like:

float matrix(float phi){
  float R[2][2] = { {cos(phi), -sin(phi)},
                    {sin(phi),  cos(phi)} };
return R;
}

But it doesn't work obviously. What is the best way to write this function?

You cannot return an array from a function. There are several
alternatives, though. One of them is to allocate the memory for the
array within the function, as suggested by user2912328's answer. I would
not recommend this approach though, for the reasons already stated in
that answer.

For an overview of the other possible options, see this response to the
question “Returning an int array from a function”.

Now, your problem is slightly different, as you have a 2D array.
The C/C++ syntax for dealing with those is tricky, but here we go.

If you opt for the “static array” solution (make sure you understand the
implications), you could write:

float (*matrix(float phi))[2]
{
    static float R[2][2];
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

and you would use it like this:

float (*M)[2] = matrix(angle);

If you instead let the caller manage the allocation, then

float (*matrix(float phi, float (*R)[2]))[2]
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

Or maybe forgo the return value to make the syntax simpler:

void matrix(float phi, float (*R)[2])
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
}

and you could use it like:

float M[2][2];
matrix(angle, M);

The “array in a struct” solution is more straightforward.

If the syntax for dealing with 2D arrays bothers you (which would be
understandable), you can instead use arrays of pointers to 1D arrays.
This are easier to deal with but trickier to allocate. That approach
could warrant another answer...

Edit: One common way to simplify a convoluted array syntax is to use
typedefs. As an identifier for a 2x2 array decays to a pointer to an
array of 2 floats, you can name that type:

typedef float (*pmatrix)[2];  // pointer to an array of 2 floats

Then, instead of

float (*matrix(float phi))[2] { ... }
...
float (*M)[2] = matrix(angle);

you would write

pmatrix matrix(float phi) { ... }
...
pmatrix M = matrix(angle);

One way would be to make the function return a pointer to float ie create a new array and return it

float** matrix(float phi){
   float** R= (float **)malloc(2 * 2 * sizeof(float));
   R[0][0]= cos(phi);
   R[0][1]= -sin(phi);
   R[1][0]= sin(phi);
   R[1][1]= cos(phi);
   return R;
}

Do not forget to free the memory once you do not need it any more!

However, I would advise you not to do it but rather pass the array to the function. See How can I declare an array of variable size (Globally) and Is using malloc() and free() a really bad idea on Arduino? for an explanation why it might not be a good idea to allocate the memory in the function (in an embedded aka Arduino environment)


Voice recognition without module, is it possible? I'm trying to figure out how to process a voice signal for simple purposes. Wherever I look people using or suggesting recognition modules for Arduino.

What I'm wondering: is this possible to make a simple command recognition with Arduino, without modules?

I just simply want to attach a microphone to my Arduino and after I convert it I want to handle signal and program it in MATLAB or in an Arduino itself. How can I achieve that?

As you can see I'm newbie in this. Any help is appreciated. Thanks!

No, it's not possible. The Arduino is not powerful enough to run the algorithms needed.

You need something with far more processing power, memory and storage. Something like a Raspberry Pi, maybe, or a desktop PC.

Or just use one of the many commonly available VR modules you can buy on the internet for next to nothing.

is this possible to make a simple command recognition with Arduino, without modules?

absolutely.

a few examples:

1) use loudness: a loud shout-out means "turn on the led", and a whisper means "turn off that led";

2) use frequency: a high pitched sound means "close that relay", and a low pitched sounds means "open that relay";

3) or use sound patterns, ....

your creativity is the limit.


TinkerCAD switch seems to be not working (always closed) I am using TinkerCAD to simulate the functionality of a slide switch. Please comment if you think this question is off-topic.

/*
  LiquidCrystal Library - Hello World

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time.

  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */
#include <LiquidCrystal.h>

const byte pin8 = 8;

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(9600);      // open the serial port at 9600 bps:
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Welcome.");
}

void loop() {
  byte val = digitalRead(pin8);
  Serial.println(val);
  if(val == HIGH)
  {
    lcd.setCursor(0, 1);
    lcd.print("Switch on right.");
  }
  else
  {
    lcd.setCursor(0, 1);
    lcd.print("Switch on left.");
  }
}

The serial monitor and the output of the LCD screen are showing the slide switch to always be on the right side (not creating an open circuit when the switch is on the left side).

As seen in the picture, the switch is on the left. And the code, I think, is correct. So it should display, "Switch on left." This is because pin8 is low (not connected to 3.3V).

So I'm very confused. The switch appears to be shorting all three rails to which it's connected. When the switch is removed, that part becomes open; pin8 is low.

As  Sener said, "use a pull-down resistor (10K) from pin8 to GND."

And in case anyone notices, yes, I'm aware of clear().

TinkerCAD must be assuming a floating input reads high instead of an intrinsically floating ground. The most simple solution is adding pinMode(pin8, INPUT_PULLUP); to the setup() function. Then, tie the opposite (than with a resistor) side of the switch to ground: Modified circuit TinkerCAD simulation.


I bought an Arduino WDLduino uno board I thought I was buying an Arduino Uno board and received a "WDLEle WDLduino uno" board.  I think I got ripped by China, but can anybody tell me what driver to use, where to get it, or what the heck this board is?

HELP

I got the same problem here. But I found the solution. You must install a driver for chip CH340G. Here is all the steps http://www.instructables.com/id/Instalar-driver-para-CH340G/


Help with Serial.print() How does the Serial.print() transmit the data? Can you please explain this with respect to TX buffers?

Also, What would happen if i try to output the data that is greater than 64 bytes? How is this transmitted?

And please explain the difference with Serial.write()

Thanks!

Serial.print() feeds the data into the TX buffer one character at a time (through the Print class's inherited .write() function which HardwareSerial implements). If there isn't enough room in the TX buffer for the next character it waits for there to be room available.

Characters are removed one at a time from the TX buffer and sent through the physical UART by the UART's TX interrupt.

To put it in more detail:

When you call Serial.print() it's actually calling Print.print(), because Print is a parent class of the HardwareSerial class.
Print.print() repeatedly calls Print.write() for each character to print.
Print.write() is a pure virtual function (which means it's only got the definition in the Print class and child classes must implement it).
HardwareSerial.write() implements the Print.write() function which takes the character and (with possible blocking while waiting for space) adds it to the TX buffer.
Serial is an instance of the HardwareSerial class.

Its simple, add one byte wait till the byte is transmitted,
And add another byte till the input data isn't exhausted.

There is rx bufffer not tx buffer of 64B.


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

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

VL6180X sensor;

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

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

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

  sensor.setTimeout(500);

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

}

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

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

  Serial.println();
}

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

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

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

  return range;
}

Here is my serial monitor:

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

Any help would be greatly appreciated.

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

"Desoldering led and voltage regulator on Arduino Pro Mini"

Regards


ESP8266 Returns 'invalid' - Cause 4 I have tried to get the Ai-Thinker ESP8266 working at all. If you hook it up to an Uno you have garbage returned no matter what the baud rate is. Tried softwareSerial on D3 and D4 (switching pins doesn't help) and over D0 and D1 with no sketch (to send AT commands directly to the device because softwareSerial wasn't working).

I'm using a logic converter from 5v to 3.3v to handle the voltage correctly.

I also know for a fact you can do that. I've done it a bunch with Bluetooth. HC-05.

NOTE: Pins in the wrong order won't return anything, in order to get garbage it needs to be wired correctly.

I also have a FTDI module that functions as another passthrough unit for this. It has a jumper for 3.3v to 5v and will stay on 3.3v as these units are unable to handle 5v.

I used PuTTY in order to view the boot information of this chip. On boot it returns this information.

So here's my issue.

ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x40100000, len 816, room 16
tail 0
chksum 0x8d
load 0x3ffe8000, len 788, room 8
tail 12
chksum 0xcf
ho 0 tail 12 room 4
load 0x3ffe8314, len 288, room 12
tail 4
chksum 0xcf
csum 0xcf

2nd boot version : 1.2
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd▒C▒
Ai-Thinker Technology Co. Ltd.

invalid

At the end of the day this invalid line means that the wifi information (from what I understand) is corrupted. It also refreshes this information over and over and WILL NOT accept AT commands so I can't seem to chase it down.

I am afraid that by attempting to update it if this kind of issue happens it will be bricked.

Both of these modules are opened today and I have tested another 8266 with similar results.

Any help would be appreciated.

Alright so I figured it out. Thanks to user Butters for pointing me in the right direction.

The Arduino Uno DOES NOT have enough power to handle the ESP8266 itself. It needs a power source using a 5v to 3v stepdown chip. The 3v3 rail doesn't handle it by itself.

I don't know what this "invalid" means I am getting this on every boot but my device is working fine. I have tested downloading webpages and it's working. So maybe just ignore this. use cutecom it works there, didn't work in minicom maybe because of carriage return absent.


DigitalWrite Cannot Power HC-06 Bluetooth To save power consumption, I tried to connect the HC-06 bluetooth module to a digital pin of my Arduino Nano. (HC-06 +5V <=> pin 11, HC-06 gnd <=> gnd) In that way, I can toggle the bluetooth when I am not using it. However, when I tried to pinMode(11, OUTPUT) and digitalWrite(11, HIGH), the led on HC-06 does not turn on which means it is not powered. I have tried to connect the HC-06 +5V to the 5V output of arduino and the HC-06 can turn on sucessfully. I have also tried to use a multimeter and the digital pin outputs a voltage of 5V. As the digital pins of Arduino can give 40mA while the HC-06 draws 30mA - 40mA, it should have enough power. I have also tried to use other digital pins as well but still the HC-06 cannot be powered.
What have I done wrong?

A digital IO pin is only capable of powering an LED or an incredibly low powered device. It is not suitable for powering meaty RF modules.

Instead you need to control the power to your module using a P-channel MOSFET as a High-Side switch.

For instance, assuming a 5V module with built in 3.3V LDO:

simulate this circuit – Schematic created using CircuitLab

Note that /RFEN is active low - set the pin OUTPUT and LOW to turn the module on. M1 should have a threshold of no lower than -4V, better -2V or higher.

Also be sure to set RX and TX to be INPUT when you power down the module or back-powering through the TX/RX pins may occur.

R2/R3 is a simple logic level shifter for the 3.3V logic signal the RX pin expects.

it should have enough power.

Probably not. Debugging is about challenging all assumptions, especially implicit ones.

Put a high side switch there and it should be ok.


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

Give power to gsm shield with 9v adaptor. It may work. I too used power to gsm module from arduino, but there is no connnection.after i used 9v adaptor ,then it works well.


Read only one line in SD card I have some C++ code, but I cant convert it to Arduino language.
I just want to ask, what is the same as getline() (C++ code) function in Arduino?

I just wanted to get the first line in my SD card...
I can only display all text inside my SD card...

Example:

line1   <-   only this line should display(and this line will delete in text
             file... but that is another issue... i will just focus to get the
             line1 and get the value)

line2

line3

line4

line5

This code displays all lines

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

    File myFile;

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

       Serial.print("Initializing SD card...");

       if (!SD.begin(4)) {
         Serial.println("initialization failed!");
         while (1);
       }
       Serial.println("initialization done.");

       // open the file. note that only one file can be open at a time,
       // so you have to close this one before opening another.
       myFile = SD.open("test.txt", FILE_WRITE);

       // re-open the file for reading:
       myFile = SD.open("test.txt");
       if (myFile) {
         Serial.println("test.txt:");

         // read from the file until there's nothing else in it:
         while (myFile.available()) {
           Serial.write(myFile.read());
         }
         // close the file:
         myFile.close();
       } else {
         // if the file didn't open, print an error:
         Serial.println("error opening test.txt");
       }
     }

     void loop() {
       // nothing happens after setup
     }

There is no builtin way to do that but you got all the necessary tools at hand.

End of line should be signaled by a decimal 10, aka LF(Line Feed) character.
So what you do is keep reading until you encounter LF or end of file, which then is the entire line you want to read.

while (file.available() && file.peek() != 10) // peek returns the next character without incrementing the read index
    file.read();

This code does exactly that. Now you could either store the read bytes in a buffer (big enough!) right away or instead find out the number of bytes beforehand to create a precisely sized buffer afterwards and use the read(buffer, length) overload to read all bytes at once.

Please keep in mind that the LF character has to be there in order to be read. So if you are the one creating the files, be sure to place it. (most desktop text editors do that for you)

Example:

char buffer[20];
uint8_t i = 0;

while (file.available() && file.peek() != '\n' && i < 19)    // note how this also prevents the buffer from overflowing (18 max to leave space for '\0'!)
{
    buffer[i] = file.read();
    i++;
}
buffer[i + 1] = '\0';    // it is good practice to end strings with a terminating NULL character

If I understand you correctly, it depends on what you want to do with that code. Do you want to execute lines of C++ code in/on the SD card or are you merely attempting to convert what you have in C++ to "Arduinoese?"

If you need to, you can actually execute microcontroler-based C/C++ code on your arduino if it has an AVR in it, and you have the proper AVR Toolchain.

Elliot William's "Make: AVR Programming" book is a great place to learn about this.


Nano-like Board - Programmer Not Responding I am trying to upload a basic sketch to my unofficial Nano-like board and keep getting this error. I understand that it is a generic connection error between the Arduino and my PC, but can't figure out why it is having this problem.

Semi-compatible nano-like board
Drivers
Arduino IDE 1.8.3 freshly installed
Windows 10 64-bit
Also tried on Mac OSX with the same result

I've looked up the drivers from the manufacturer's website and installed them, and the Arduino Nano shows up just fine under my Device Manager. The green power light comes on, it is recognized by my PC, and blue flashing 'L' light blinks, making me think that the manufacturer had uploaded the Blink sketch to test it. However, when I try to upload a sketch from the IDE I get this error:

avrdude: stk500_recv(): programmer is not responding

Under 'Tools" I have the board set to 'Arduino Nano', the processor set to 'ATmega168' and the port the same COM port as what it's listed as in Device Manager. Assuming that all of those are correct, I have tried a few things with no luck:

Reinstalling the IDE, drivers and restarting my computer.
Letting Windows find its own driver.
Pressing the 'reset' button just before hitting 'upload' in the IDE
Using different micro USB cables and USB ports on my computer.

Any other ideas or is the unit possibly just faulty?

Please note that I have already at similar questions and tried a bunch of their suggestions with no luck.

That is a Chinese NANO clone, using the notorious CH340G chip.

macOS does NOT have a driver, and it is difficult, if not impossible to get a driver which 1. macOS will let you install, and 2. Actually works.

I do not know the state with current Windows.

In my experience, in addition to poor support the chips are unreliable and fail to respond.

You could try using a Uno as ICSP, bypassing the boot loader, or (untried) use an external USB serial interface. Both of these approaches are documented on the Arduino site.

It's a wiring problem (soldering), check by multimeter (continuity mode).
between RST and GND. Then between ICSP pins. you have to get (1) that mean no shorts between the PINS.
Good luck!


Wrong characters received with Bluetooth Mate Gold using Software Serial I have a Bluetooth device from Sparkfun which I would like to use with the Arduino Mega. If I connect the module via the hardware serial pin everything works fine but when I use other pins like 12 and 13 with SoftwareSerial, the communication doesn't work as expected.

THE CODE

#include <SoftwareSerial.h>

int bluetoothTx = 12;
int bluetoothRx = 13;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available())
  {
    char toSend = (char)bluetooth.read();
    Serial.print(" Receiving: ");
    Serial.println(toSend);
  }

  //Read from usb serial to bluetooth
  if(Serial.available())
  {
    char modeS = Serial.read();
    Serial.print(" Writing Blu: ");
    Serial.println(modeS);
    bluetooth.print(modeS);
  }
}

I'm using an Android App (BlueTerm) to test the communication.

Here is what I get when sending a letter from Android to Arduino.

 Receiving: ÿ
 Receiving: ÿ
 Receiving: ÿ
 Receiving: ÿ
 Writing Blu: d
 Writing Blu: d
 Writing Blu: d

I'm not able to receive anything from the Arduino.

I've tried decreasing the baudrate but nothing changed. Do you have any advice?

Update

I have tried without the following lines but nothing changed... It seems that the module can be used only with the hardware serial pins 0 and 1... It's a shame

bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);

Maybe you fixed your issue, but I'm writing to help other people.

void loop()
{
  if (bluetooth.available())
  {
    dataFromBt = bluetooth.read();
    Serial.print("Receiving:");
    Serial.println((char)dataFromBt);


What is the difference between declaring a variable outside of loop and declaring static inside loop? These are two ways I can hold a variable outside of loop (or any function).

First, I can declare it with global scope outside of loop:

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

int count = 0;

void loop()
{
    Serial.println(count);
    count++;

    delay(250);
}

I can also declare it static inside the loop:

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

void loop()
{
    static int count = 0;

    Serial.println(count);
    count++;

    delay(250);
}

What difference, if any, will this make?

The most basic difference is of scope.

In the first case, you are declaring a global variable. It is a variable that is accessible in every scope after its definition.

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

void inc();
int count = 0;

void loop()
{
    Serial.println(count);
    count++;

    inc();

    delay(500);
}

void inc() //Can edit the value of count
{
  count=count+1;
};

In the second case, you are declaring a static variable with local scope. The variable will persist for the entire program run similar to global variables, but will be accessible only in the code block it is declared in. This is the same example, with only one change. count is now declared as a static variable inside loop.

void inc();

void loop()
{
    static int count = 0;
    Serial.println(count);
    count++;

    inc();

    delay(500);
}

This will not compile as the function inc() does not have access to count.

Global variables, however seemingly useful, come with some pitfalls. These can even cause damage when it comes to writing programs that can interact with the physical surroundings. This a very basic example of something that is quite likely to happen, as soon as programs start getting larger. A function may inadvertently change the state of a global variable.

void setup()
{
    Serial.begin(9600);
}
void another_function();
int state=0;

void loop()
{
    //Keep toggling the state
    Serial.println(state);
    delay(250);
    state=state?0:1;

    //Some unrelated function call
    another_function();
}

void another_function()
{
  //Inadvertently changes state
  state=1;

}

Such cases are very hard to debug. This type of problem however, can easily be detected, by simply using a static variable.

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

void loop()
{
    static int state=0;

    //Keep toggling the state
    Serial.println(state);
    delay(250);
    state=state?0:1;

    //Some unrelated function call
    another_function();
}

void another_function()
{
  //Results in a compile time error. Saves time.
  state=1;

}

According to Atmel's documentation: "If a global variable is declared, a unique address in the SRAM will be assigned to this variable at program link time."

The complete documetation is here (Tip #2 for global variables): http://www.atmel.com/images/doc8453.pdf


Is there a constant for the Maximum Unsigned Long value in an Arduino compiler? I am writing a timer function that uses the micros() function which generates a unsigned long value.  To compensate for a roll over condition, I would like to use the maximum value for that variable type.  I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.

Is there a MAX_UNSIGNED_LONG constant in the Arduino compiler files somewhere?

I have tried that name and know it probably isn't that.  Still poking around.

Various limits.h files in the avr-gcc hierarchy define ULONG_MAX, which may be the value you want.  For example, on my system such files have paths ending with hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h or with hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h and contain definitions like the following.

/* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
#undef ULONG_MAX
#define ULONG_MAX (LONG_MAX * 2UL + 1UL)

Note, LONG_MAX also is defined in limits.h.

Note, arithmetic done in a form like

timeDelta = micros() - prevTime;

will be correct (regardless of whether micros() overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.

From network, seems to me, it is not that easy to find the right answer of the maximum value of micros() of my own arduino boards, too.
In my case, seems that micros() rolls over about every 17 seconds.
Finally, I wrote the Setup() for myself to catch 0x1111111 as the maximum value of micros() as follows.

void setup () {
  Serial.begin( 115200 ); // set the baud rate for writing messages.
  int go = 1; // set the flag to continue do-while loop;
  int n, nMin = 0, nMax = 0; // see how many more the numbers of calling micros() to get different value;
  int d, dMin, dMax; // see the time interval of micros() having different values;
  unsigned long currT; // the time of current micros() calling
  unsigned long lastT = micros(); // the time of last micros() calling
  unsigned long T[200]; // keep tracking 200 different lastT values
  int it = 0; // use T[it%200] to keep each lastT (circular buffer)
  do {
    n = 0;
    while( (currT=micros()) == lastT ) n++; // get a different value
    T[ (it++) % 200 ] = currT; // save the value
    d = currT - lastT; // get the difference
    if ( d<0 ) { // if micros() rolls over
      go = 0; // stop this do-while loop
      Serial.println(); // print new line
      for ( int i=it-200, j=0; i<it; i++ ) {
        Serial.printf( "%9x", T[i%200] ); // the last 200 different lastT values
        if ( ++j%5==0 ) Serial.println(); //
      }
      Serial.printf("\nat %d ms lastT 0x%x currT 0x%x n=[%d..%d] d=[%d..%d]\n",
        millis(), lastT, currT, nMin, nMax, dMin,dMax);
    }
    if ( !nMin && !nMax ) nMin = nMax = n, dMin = dMax = d;
    if ( nMin>n ) {
      PRINTF( "\nat %d ms nMin %d > n %d ", millis(), nMin, n);
      nMin = n;
    } else if ( nMax<n ) {
      PRINTF( "\nat %d ms nMax %d < n %d", millis(), nMax, n );
      nMax = n;
    }
    if ( dMin>d ) dMin = d;
    else if ( dMax<d ) dMax = d;
    lastT = currT;
  } while( go );
}


How to package a 16 bit integer to send it with serial.write? I am trying to display the values i get from reading a potentiometer (0-1023) in the program called 'processing'.

when I just use Serial.write(integer) and display the value on a line graph in 'processing' the line will max out at 256 and loop back around to 0 as i vary the potentiometer.

I understand that this is because the serial.write can only write in bytes(8 bits) so I would need to package the 16 bit integer into 2 bytes.

i was considering using a union but as you can probably guess i am very new to arduino so i haven't been able to make that work.

here is the code i have tried:

union Data{  uint16_t now; } data;

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

}

void loop() {   // put your main code here, to run repeatedly:
    uint16_t sensorVal = analogRead(A1);
     union Data data;

    data.now = sensorVal;

    Serial.println(data.now);

    //Serial.write(sensorVal);
    delay(10); }

You need to send the uint16_t as the two the individual bytes it is composed of, one at a time, in whatever order your Arduino code and the code on the PC agree on: (MSB first, aka, big-endian; or LSB first, aka little-endian).

Since it would be possible for the two devices to get out of sync, you may also want to package up the two bytes with a third, or "start-byte". Pick some fixed value (such as 0xCC) that has a couple of its MSbits set, then the MSB, then the LSB. Your receiver can know to look for that fixed value, then the MSB (which it knows can't have those high bits set because the analog data is only 10-bits), then the LSB (which could have any value).

The PC should only accept a three-byte packet when it has received one that fits that scheme. Otherwise it waits for another 0xCC (or whatever value you choose), collects two more bytes, and tries again.

If you ask for number representation only then try to use itoa() function.

Warning: The buffer must be large enough to hold the largest number, plus sign and terminating null: e.g. 32 bit base-10: "-2147483648\0" = 12 characters.

Example:

char buf[5]; // to keep string representation
Serial.write(itoa(sensorVal, buf, 10)); //itoa(value-to-convert,where-to-keep,base)


Esp8266 server unreachable. Port doesn't open I have followed all the instructions provided on  http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/

I have got the correct setup, I have got the message "Server Ready" in the serial monitor, i have an app similar to this, means the only thing i have done different from the web page is removing two buttons from the app.

But then also whenever i use my app to send request parameters to arduino it says "connection to 192.168.x.x:xx refused" , when i put the same ip and port in chrome, it says Server not reachable, the website may be down, What to do ? , Please help...

The ESP module is not that difficult to work with, if you send the correct parameters to it AND you have the correct power it should work as expected.

My main suspicions will be cabling (just triple check that connections are as expected) and power source (the ESP is VERY power hungry, if you are powering the ESP from the Arduino that is your problem, you need a very good and stable power for the ESP to work (it might show up on your network but will not have enough power to actually send anything and it will disconnect (that will still show up on your router, it depends on how fast it connects/disconnects but won't be able to send anything).

This link can provide some good information about this subject:

http://bbs.espressif.com/viewtopic.php?t=133

I had the same problem and it worked when I disconnected my phone from 3g/4G.


#Ardunio Send Float values with bluetooth.print in arduino I have been creating the example for bluetooth communication with arduino with hc_05  Problem I am facing are below.

String statuss= "1.00,2.00,3.00";
bluetooth.print(statuss);
Serial.print(statuss);

This is the code where is get only last 2 digits i.e 00 in android while its showing me complete string in serial monitor.

String statuss= "Hello";
bluetooth.print(statuss);
Serial.print(statuss);

Then I get the output as ello in Android n in Serial monitor it show Hello

Can Anybody suggest the whats the problem

I suspect (at first sight) a speed problem. Android runs Bluetooth at 115200 Bauds. So you must set your HC-05 o HC-06 at this speed to get proper result.

But as you perform "bluetooth.print(statuss);" and also "Serial.print(statuss);" this mean you have created a virtual port, probably using the Software Serial lib.
Unfortunatly, this lib is not very efective. At speed higher than 19200 Bauds, you lost data (I've had a lot of problem with that before understanding!!)
The only right way is to use directly the RX and TX port of the Arduino (pin 0 and 1) and use (eg) a LCD Display to display data and help you debugging your Arduino code (as when you plug the HC on Pin 0 and 1 you lost the access to the serial monitor).

A trick: with the HC on pin 0 and 1, each time you send the sketck to the Ardino, you must unplug RX as it's used for sending the code.

Hope this will help.

It is difficult to know your exact problem since you have not provided your code. However, I believe that you don't have a clear starting bit and a clear end bit, so that the modules don't know when to Start and End.


Why isn't DigiSpark automatically recognized on other computers? I bought a DigiSpark (it is a development board based on the ATtiny85 microcontroller) yesterday and I wrote my first script.

I have no problems to run it on my personal PC (which I am using to program my DigiSpark). The problem is when I try to plug my DigiSpark to another PC, which doesn't have DigiSpark drivers installed. I tried to run it on two different PCs (Windows 7) and Windows just can not find DigiSpark drivers so my script does not run.

Of course I tried to plug in to different USB ports - unfortunately it did not help.

Any ideas what can I do to make my DigiSpark run on other PC without installing drivers by myself?

Thank you.

You will need to install the drivers before you can use it on other computers.
The drivers tell a Windows PC how to talk to the device.  The device is not a generic device so Windows can't use a fall back driver, like it could with a keyboard or monitor.

I faced the same issue when I first time used DigiSpark. After searching on the internet I found the solid answer that worked for me.

Arduino IDE from 1.66 to onward have not driver for DigiSpark so you have to install the driver manually when you will use Arduino IDE 1.66 or latest. But Arduino IDE 1.65 and some lower versions have support for DigiSpark.

When you will use say Arduino 1.65 and connect DigiSpark to USB port, then your PC/Laptop will automatically install the driver for DigiSpart.


Is it possible to generate an exact 15 kHz clock pulse using an Arduino? I want to generate a 15 kHz pulse with an Arduino using Timer1, but the problem is that if we want a 15000 Hz clock we need to initialize the timer with 1/15000 seconds or 66.66 microseconds, but we can only pass integers without any decimal precision in the Timer1.initialize(66); function which generates a frequency of 15155 Hz.
So is it possible by any other means to generate an exact 15000 Hz or frequencies between 15000 Hz - 15155 Hz?
#include <TimerOne.h>

void setup() {
  pinMode(9,OUTPUT);
  Timer1.initialize(66);  // Frequency, 100 µs = 10 kHz
  Timer1.pwm(9,255);
}

void loop() {}

You can get pretty close if you program Timer 1 directly (not
through the library), and have it run with the prescaler set to 1.
Ideally, you want the period of the timer in clock cycles to be:
F_CPU / 15 kHz = 16,000 kHz / 15 kHz ≈ 1066.67 CPU cycles
If you round this to the nearest integer, you get
F_CPU / 1,067 = 16,000 kHz / 1,067 ≈ 14.9953 kHz
This is about 0.03% too slow, well within the tolerance of the ceramic
resonator clocking the Uno.
Here is my attempt at this. I have tested it.
constexpr float PWM_FREQUENCY = 15e3;  // 15 kHz
constexpr uint16_t PERIOD = round(F_CPU / PWM_FREQUENCY);

void setup() {
    // Configure Timer 1 for 15 kHz PWM on pin 9 = PB1 = OC1A.
    DDRB  |= _BV(PB1);    // set pin as output
    TCCR1B = 0;           // stop timer
    TCCR1A = _BV(COM1A1)  // non-inverting PWN on OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock @ F_CPU
    ICR1   = PERIOD - 1;  // period
    OCR1A  = PERIOD / 4;  // duty cycle
}

void loop(){}

Yes, you can. Sort of...
A 66.6 µs delay means one delay of 66 µs and then two delays of 67 µs.
You could keep a close loop that calculates the micros() divided by 66 and modulo by 2 for every iteration. This will give you an alternating 1 and 0. Save the previous value to check this value for a change and digitalWrite HIGH or LOW.
I have no means at the moment to test the code, but in (semi-pseudo) code this would look something like:
void loop()
{
  int freq=15000;
  float interval = ((float)1000000/(float)freq)/2;//33.333333
  byte state=0;
  byte previousState=0;
  while (1)
  {
    unsigned long currentMicros=micros();
    previousState=state;
    state = (unsigned long)((float)currentMicros / interval) % 2;
    if (state==1 && previousState==0) digitalWrite(9,HIGH);
    if (state==0 && previousState==1) digitalWrite(9,LOW);
  }
}

This method will guarantee that after one second exactly 15000 periods have passed. The timing of the individual periods, however, might vary a little.


Floating pins: digitalRead returns always high or always low I was trying to see whether my board operates as expected with random readings on floating pins. Oddly it does not. The following code produces all HIGH readings:

#define PIN_MISO 12

void setup() {
  pinMode(PIN_MISO, INPUT);
  Serial.begin(9600);
}

void loop() {
  uint16_t data = 0;
  Serial.print("MISO digitalRead: ");
  data = digitalRead(PIN_MISO);
  Serial.println(data, BIN);
  delay(300);
}

MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1

I tried grounding pin 12 and after a few seconds the readings all came back LOW as expected. However leaving it floating produces all HIGH instead of random readings.

I tried the same program for pins 3 and then A3 with more weird output: all LOW.

What am I missing here?

Floating means it would generate any value. This could be a result of innumerable factors and it is HIGH in this case! you cannot expect anything other than a HIGH or LOW.

Think of it this way-
It's fluctuating in a range of about 900-1000 but the range is still very close to 1023 hence it results in a HIGH.

Some other time it may be near the lower values then it would show LOW.

Change:

pinMode(PIN_MISO, INPUT);

to

pinMode(PIN_MISO, INPUT_PULLUP);

This will enable the internal 20k pull-up and you should then always read HIGH is the pin is floating.

Using INPUT does not enable the internal pull-up (Ref: https://www.arduino.cc/en/Reference/pinMode)


Using Arduino to show images in Serial Monitor Some time ago I came across a Vedic in which a person has hacked an optical mouse's camera and displayed the image in the Serial Monitors.
My question:
How to use Serial Monitor to display an image captured by the Arduino

Based on this guide, he doesn't actually display the images on the serial monitor, only the image data for each pixel.

Then another program (Javascript and some HTML) on the PC side collects the data and converts it to a greyscale image.

I think him just rewrite the source of arduino IDE, you can do that by rewriting the source as when you receive some characters, show some glyph
than orginal text, the standard Serial Monitor can show ASCII only.


Serial is freezing arduino I'm using a LinkIt ONE Arduino-like to send sensor data via MQTT.
It always worked very well, then out of the blue, it stopped printing anything using Serial.print();
But if I ommit the "Serial.begin(9600);" line, the code runs normally, sending sensor data via MQTT, even if I can't see debug output.
This shows the problem is on the Serial handling.
Since I can't show the entire code here, here's two test cases:
1.
void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial1.println("This came from serial 1"); //does nothing
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

It shows me the following output:

This came from serial 0
This came from serial 0
Thi

Looks like the module freezes before the third iteration.
But if I omit the lines that aren't printed, from Serial1:
2.
void setup(){
  Serial.begin(9600);
  while(!Serial);  //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

No output is shown on Serial monitor.
What is the reason behind this? Since Serial1 prints nothing, why can't I remove it?
Observations:
I tested the code in two LinkIt ONE modules of the same model.
I tested it in Arduino SDK 1.6.8, 1.5.6r2 and 1.6.5.
Edit:
Just made another test using the code below. It blinked two times showing that
Serial.begin(9600); runs
while(!Serial); runs (it didn't freeze the module waiting for Serial to initialize)
But Serial.println(); freezes
void setup(){
  pinMode(13, OUTPUT);
  blink();
  Serial.begin(9600);
  blink();
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  blink();
  delay(1000);
}

void blink(){
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);
}

The problem was solved by:

making a clean install of Arduino IDE 1.6.9
uploading the LinkIt SDK on board manager from version 1.1.17 to 1.1.23.

Then the Serial function returned back to normal.

This shows the problem is on the Serial handling.

The problem isn't actually in Serial, it's somewhere else.  Many things are able to make the Arduino hang in mid-write.  Show us the any code that you have written, plus links to the libraries you are using, and you'll have your answer in short order.

I will guess that you have a low-RAM condition, perhaps exacerbated by heap usage.  Do you use String?  I notice you're not using the F macro to save RAM.


How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan I'm a newbie to Arduino so please excuse the easy question and guide me to the appropriate sources or forums.  I just bought an Arduino Uno Starter Kit that comes with the "Arduino Projects Book" by Scott Fitzgerald et al and I'm happily working my way through the projects.  I downloaded the Arduino IDE (version 1.7.10) onto my mac and am turning on lights, etc.  However, I'd like to see the underlying code.  For example, I use the code "digitalWrite" to turn off/on LEDs.  I'd like to see the code for this.  I can imagine that it's just a write of 1 or 0 to a particular memory address, but I'd still like to see it.  I was hoping there was a right-click->"Go To Definition", but I don't see it. I downloaded the Arduino IDE to my Downloads folder and run it just from there. It's called Arduino.app.   I don't see a folder with .c and .h files as suggested in this post:  Arduino IDE, Underlying Code and Libraries  Maybe I'm missing them?

Also, is it possible to set a breakpoint?

Again, sorry if these are "obvious" questions.  And I did look at the Arduino site without any success.

Thanks,

Dave

The simplest way is to look at the source on Github:

https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino

Can you set a breakpoint? No. The Arduino IDE and the bootloader don't support such functionality. To do that you need a real IDE (like Atmel Studio) and a hardware debugger.

Yes, they need a right-click->"Go To Definition"

Assuming the first appearance of a variable is the definition (variable declaration), use the following easily learnt "hack"..

Double click variable, then ^F, Esc, ^Home, ^G

..(where ^ = Ctrl).


Reduce PWM Frequency Arduino DUE I'm newbie in arduino due. I need to reduce the default PWM frequency of arduino Due. Anyone have any tutorial to do this? (Frequencys like 25hz, 50Hz for example)

I read in some posts, if i change the PWM frequency, i make changes in internal timers of arduino and i loss functions like delay(), millis(), etc.

Exits any form to not lose these functions?

Thanks a lot!

The Palatis Softpwm library can generate PWM on any digital pin with (almost) any frequency. Example for 25Hz:

#include <SoftPWM.h>
SOFTPWM_DEFINE_CHANNEL(0, DDRB, PORTB, PORTB2);  //Arduino pin 10
void setup() {
  // begin with 25Hz pwm frequency
  Palatis::SoftPWM.begin(25);
  Palatis::SoftPWM.set(0, value); // value is 0 to 255 just like normal Arduino analogWrite
}


ESP8266-01 Wifi module + Wifi shield not present + ESP8266-01 libraries not working? I have Arduino IDE v. 1.8.13.
I bought an ESP8266-01 module which I want to use in my Arduino-UNO board to send fingerprint registration confirmation (ID) via HttpClient to a xampp server since I dont want to store the fingerprint image in the database.
My ESP connection is as below:

In the serial monitor, my AT commands work well when I connect the module to my wifi using AT+CWJAP="ssid","password".
When I upload my code, which is supposed to connect to wifi, it says WiFi shield not present.
Im new to this, is there anything I am missing?
Thanks in advance.
Here is my code:
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;

char serverAddress[] = "localhost/bel/arduino/scannerstatus/php";  // server address
int port = 80;

WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;

void setup() {
  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

Basically, my uploaded code does not go past the wifi connection stage. Even though the AT commands individually can connect to wifi.
I have tried different ESP8266 libraries and HttpClient libraries but they all seem to not connect to wifi.
Is there any other way to call a php script from arduino without using wifi?

Can you please include some explanation of how the Arduino Uno and ESP8266-01 are connected. You will need to program for the ESP8266 ESP-01 module like shown below,

You will need to write code for the ESP module to connect to the WIFI and listen to its Serial Com Port. The ESP will need to handle the message interpretation & WIFI updating.
The Arduino Uni will not be capable of directly using the ESP-01 module as a WIFI shield. It will need to communicate with the ESP via a serial coms link, you will need to send commands that include instructions & a Message to the ESP from the Arduino.

https://create.arduino.cc/projecthub/jeffpar0721/add-wifi-to-arduino-uno-663b9e - Link to the above image document, this should help explain my concept in more detail
I apologies if my comments above miss the point but with the amount of information provided I don't think I can help further.


How to make a servo sweep from 0 to 180 on press of a button on PS2 controller? (without delay) I am working on a project that requires the servo to make a complete sweep once on pressing a button say r2 on the pS2 controller. I am using the Arduino Mega 2560,a PS2 controller clone, Bill porter's Ps2x library.

I have figured out a way to do so by adding a delay to the code but when the delay is used I can't use other parts of my project. What should I do?

int pos = 0;    // variable to store the servo position
int button = 2;  // The button will be on Pin 7
void setup()
{
myservo.attach(9);  // attaches the servo on pin 9 to the servo object
pinMode(pos, OUTPUT);
pinMode(button, INPUT);
digitalWrite (button, LOW);
}

void loop()
{
if(ps2x.ButtonPressed(PSB_RED))

for(pos = 0; pos < 90; pos += 90)  // goes from 0 degrees to 90 degrees
{                                  // in steps of  degree
 myservo.write(pos);

}
  if(ps2x.ButtonReleased(PSB_RED))

 for(pos = 90; pos>=90; pos-=90)
 {
myservo.write(pos);
delay(50);                             // waits 50ms for the servo to reach the position

If you already have the code, if you have a good understanding of how it works it shouldn't be too difficult to implement, but you would multitasking it by creating several objects that use a central time value. It should all be here, if you follow them and read them they can explain better than I: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview

Many ways of doing it. I prefer to use a timer and flip a pin in the timer interrupt.


Problem activating HC-05 AT command mode with Arduino Uno Bluetooth shield Please be gentle with me. I am attempting to modify the configurations of my HC-05 bluetooth module by using the AT command set. The method by which I'm trying to do this is by implementing the following connection:

HC-05 GND --> Arduino GND;
HC-05 3.3v --> Arduino 3.3V;
HC-05 TX --> Arduino Pin 10;
HC-05 RX --> Arduino Pin 11;
HC-05 KEY --> Arduino Pin 9

This is the code which I uploaded to my Arduino (btw my arduino uno is an SMD clone): (code's from http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/step2/The-Arduino-Code-for-HC-05-Command-Mode/)

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more

 }

void loop() {
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());

}

The problem is I can't seem to activate the AT mode. I don't get any response from the Serial Monitor whatever AT command I try. I double-checked the wiring and it's all good. I can't figure out what the problem is.

After 3 hours I magically solved my pretty simple problem myself. If you wired the HC-05 and arduino correctly, the module should indicate that it's in AT Mode by blinking the LED in an interval of 2 seconds. You should get response in the Serial Monitor by typing the AT commands by switching from "No line ending" to "Both NL and CR". That's about it.

In setup() put pin 9 to low, and delay it for about 1 second and then put it to high.


RTC interrupts and coin batteries Summary

I'm having problems with my RTC draining its coin cells quickly - fresh batteries are drained in a few months. The RTC is set to signal an interrupt every 5 minutes, and I wonder - if there is no other power attached to the circuit, is that enough to drain the coin cell?

Details and my troubleshooting:

Problems with my RTC - if I leave the circuit unpowered for a few days (so that the only power to the RTC is from the coin cell backup), the time resets to 00:00 January 1, 2000. This doesn't happen immediately when I unplug it. If I disconnect it from the computer, plug it back in the next day, the time is ok. If I leave it unplugged for a few days, then plug it in, the date is reset.

This suggests the battery is bad. So I tested it with my meter (and an 100 ohm load, as described here: https://www.youtube.com/watch?v=HcikzMG7mMU). And sure enough, the batter has dropped quite a bit from its 3V start value.

That's all good, except that this battery is only a few months old, and it should last for years in an RTC. I've got two batteries purchased in the last year and used in RTC modules, and both are now drained.

My current hypothesis is that, after I unplug my circuit from the computer, the RTC continues to run on the coin cell, firing interrupts every 5 minutes, and it is these interrupts that are causing the drain. Does this make sense? If not, what else could I check?

Setup

Breadboard arduino, DS3231 RTC on a breakout, connected

RTC SDA -> Arduino A4
RTC SCL -> Arduino A5
RTC GND -> Common GND
RTC VCC -> Common 5V (from ftdi/USB cable, when plugged in)
RTC SQW -> Arduino D2

The RTC is 'active-low', and the SQW pin is held at 5V between interrupts. With my multimeter, the brief drop to 'LOW' is undetectable. I also can't detect any current flow from the SQW pin with my multimeter.

Sketch

Including only the code related to the RTC (SD card and temperature bits removed).

/*-(Import required libraries)-*/
#include <Time.h>
#include <DS3232RTC.h> //source: https://github.com/JChristensen/DS3232RTC

/*-( Declare Constants )-*/
const int wakeUpPin = 2;
#define resolution 5 // frequency in minutes to wake from sleep

/*-(Declare Variables)-*/
time_t t;
int nextLoop;

/****** SETUP: RUNS ONCE ******/
void setup()
{
  Serial.begin(9600);

  Serial.println();
  pinMode(wakeUpPin, INPUT);

  t = RTC.get();

  nextLoop = ((minute(RTC.get()) / resolution) + 1) * resolution;
  if (nextLoop >= 60) {
    nextLoop -= 60;
  }
  Serial.print(RTC.temperature());
  Serial.print(",");
  Serial.print(RTC.oscStopped());
  Serial.print(",");
  Serial.println(nextLoop); // the minutes when the next reading will be taken

}

/****** LOOP: RUNS CONSTANTLY ******/
void loop()
{
  t = RTC.get();

  Serial.print(year(t), DEC);
  Serial.print("/");
  Serial.print(month(t), DEC);
  Serial.print("/");
  Serial.print(day(t), DEC);
  Serial.print(",");
  Serial.print(hour(t), DEC);
  Serial.print(",");
  Serial.print(minute(t), DEC);
  Serial.print(",");
  Serial.print(second(t), DEC);
  Serial.print(",");

  goToSleep();
}

void goToSleep(void) {
    Serial.print("Sleeping until: ");
    Serial.println(nextLoop);
    Serial.flush();
    RTC.setAlarm(ALM2_MATCH_MINUTES, nextLoop, 1, 1);
    RTC.alarmInterrupt(ALARM_2, true);
    attachInterrupt(0, wakeUp, LOW);

    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
    detachInterrupt(0);
    RTC.alarm(ALARM_2);
    nextLoop += resolution;
    if (nextLoop >= 60) {
         nextLoop -= 60;
    }
}

void wakeUp(){
  // Handler for the pin interrupt.
}

Check your battery, it is behaving like a rechargeable one without a charger.  Mine have the letter "R" at the end of the part number.  There are a lot of RTC modules that charge the battery. Conversely they are some that do not charge the battery. Are you powering it with something other then the coin cell.

1) Could be a short in your PCB. As suggested, try another module if possible.

2) Shouldn't you somehow program SQW pin to be an interrupt? By default I remember it outputs a squarewave.

3) Try calling clearAlarm(); for your RTC to see how it goes.

4) Having the RTC sitting there, by connecting GND and a digital input from an Arduino, can you digitalRead(); the pin? That way you'll see if it keeps firing interrupts.


Arduino or Raspberry Pi for my project A brief description of what I'm doing here. I wanna make a pet project, basically a device (be it Arduino or raspberry pi) that I can connect to via bluetooth / wifi (both preferably), that will be connected to a stereo system and allow me to play music. I essentially want to make a wireless sound system in my house.

My question is, is raspberry pi more adequate for my needs? Or would arduino get the job done? I know that raspberry pis are essentially mini computers, so I feel that the raspberry pi would be too much, since all I really need to do is design a bluetooth / wifi interface and send the signal to the aux cable connected to the stereo.

Any help would be really useful here. I've never worked with either/or, and this is my first project with Arduino / Raspberry pi (hello world). Thanks in advance.

EDIT: In response to comments below, a greater idea of what I want to do:

I want to design an item that will appear on local wifi as a sound device. i.e. on an imac / macbook I'd be able to right click on the speaker icon in the upper right and select it there). From there, I'm hoping to stream audio to the device, and have it play to a stereo that the arduino / raspberry pi would be connected to. I'd love to make this universal (i.e. possible to connect via your android phone / a windows machine), but I can imagine that part being a lot more difficult. I'd also like to add bluetooth functionality at some point, but that'd be in the future. Hopefully this gives everybody more of an idea of what I'd like to achieve here! I appreciate all the help so far.

As mentioned in the comments, a Raspberry Pi would be superior here.

The standard AVR (not Due/Galileo/Yun) Arduino is superior to the Pi in only one area: IO. It has a 5V logic that's more compatible than the Pi's 3.3V (although you can use a logic level shifter). The Arduino also features more PWM pins and an ADC, along with interrupts. An Arduino also is a lot simpler to use for basic projects, but it becomes impractical when you need more computing power.

A Pi excels at the data-crunching side of things. It can handle a lot more data than the Arduino could ever dream of, and then some! Just to put things in perspective, the Pi has a clock speed of 700 MHz by default and the Arduino Uno has one of 16 MHz (with a less powerful architecture).

For your purpose, the Pi's audio jack and ethernet port are unmatched on the Arduino. Sure, you can get shields that replicate these behaviors, but the Pi's built in functionality doesn't cost extra and it's more powerful.

While it might be an interesting project, the overall quality of the sound generated by such do-it-yourself contraption, is likely to be highly disappointing, because of the not-stellar quality of the final analog stage in the audio output.


Why is my real time clock getting the wrong time from my PC? I want my real-time clock to set its time as the time on my PC. However, when I run the following sketch, the real-time clock reports the time as being 32-33 seconds earlier than my PC says the time is.

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

RTC_DS1307 RTC;

void setup () {
  Serial.begin(57600);
  Wire.begin();
  RTC.begin();

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
// uncomment it & upload to set the time, date and start run the RTC!
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop () {
  DateTime now = RTC.now();
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(' ');
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
}

I have also tried manually setting the time on the RTC, but I end up with the same problem: the RTC is always 32-33 seconds behind what I set it to. The lag happens as soon as I run the sketch. It seems very odd to me that no matter how I try to set the time, I end up with exactly the same error. I can tell the Arduino to report the time as being 33 seconds after what the RTC says it is, but this solution seems kind of sketchy, and I am worried that something is fundamentally wrong with my RTC or the way I am using it.

I am using an Arduino Uno with an Assembled Data Logging Shield from Adafruit. The data logging shield uses a DS1307 RTC. Has anyone had this problem before, or have any ideas about what could be causing it? Any help would be much appreciated.

The __DATE__ and __TIME__ are set when the code is compiling so they will naturally be behind since the code still needs to finish compiling and then be flashed to the chip.

See the Arduino Playground for an example of how to sync it to your computer over serial.

  TimeSerial.pde shows Arduino as a clock without external hardware.

  It is synchronized by time messages sent over the serial port.   A
  companion Processing sketch will automatically provide these messages
  if it is running and connected to the Arduino serial port.

The Arduino takes the computer time and sends it to the DS1307. The time it takes to copy is the one you are seeing wrong. I would solve the problem by advancing the computer time the necessary seconds that you say is delayed and when programming you should have the exact time.


Sending Analog Data with and IR LED This is the idea. I have 2 Arduinos. One with an IR LED and the other with an IR receiver. I want to read the values of multiple sensors and transmit it to the other Arduino via IR. I know how to send data like a fixed HEX code but I dont know how to send values from a potentiometer.

Just think of how a quadcopter sends and receives data from the joysticks, thats somewhat what I want to do.

[EDIT]

This is a precision of what I want to do. I'll read the values of let's say 2 potentiometers, map the values from 0-99, and then I want to send it to the other Arduino with IR and not anything else.

Seems to me you first need to establish a protocol.  Could just be a simple one you make up,  with it you will eventually find that repetition and retransmission will need to be explored, and you may want to include things such as a CRC if the application suits it; or not...

As part of the thought process you need to look at your sensors, see how they put out their data, you seem to indicate analog, so that would be read on an a to d converter and that d value might be directly sent as the data part of your chosen protocol.

Or some joysticks packages might have have a I2C or SPI driver built in to which the A to D wouldn't be required.

But using IR you will find timing and validation very important so that the receiver knows where the beginning and end of data is at.

Thinking about it there must some libraries out there already.
Or entirely completed projects to study.

Now you didn't ask but if reliable communication is desired you might want to go wired serial or use a managed protocol like an Ethernet peripheral.


Send Processing color data into Arduino I am trying to send color() data from Processing to Arduino.

Here is my code from Processing:

import processing.serial.*;
Serial myPort;

void setup(){
  myPort = new Serial(this, Serial.list()[7], 9600);
}

void draw(){
  color[] c1 = {color(99,0,0),color(255,0,0) };
  for (int i = 0; i < c1.length; i++ ){
    int value = int(red(c1[0]));
    myPort.write(value);
    println(value);
    delay(2000);
  }
}

It sends the 99.0 data to Arduino. Here is the Arduino code for getting:

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

void loop(){
  while(Serial.available() > 0){
    int recieved = Serial.read();
      Serial.print(recieved);
    }
}

The problem is when Arduino receive data it doesn't take one by one. When i watch Arduino serial monitor, the data comes at different chunks like, 9...99...999..9.. etc.

I am trying to send several color info from Processing into arduino, it might be a long array of value. What is the best way to achieve this?

The 'best' solution depends on many things, your skill, the performance of the system, and the other tasks it needs to do in the available time. There are some examples of doing data transfer between Processing and the Arduino in the Arduino example programs. So it is worth looking through them.

There seems to be some inconsistencies in your question.

You wrote "It sends the 99.0 data to Arduino", which has a decimal point.

Yet the code is printing an int i.e.

int value = int(red(c1[0]));
myPort.write(value);

Further, the processing code only looks at the red component of c1[0]:

int value = int(red(c1[0]));

so it can only send a sequence of '9'. So that looks like a bug.

There are a few basic strategies to write data that can be easily read. Two popular ways are:

send fixed length messages, or prefix a message with the size of the
data, and have a fixed format of data. For example, use a one byte
count to say how many colours are being sent, then send three bytes,
in the same order, for each colour
use non-data bytes to separate the data. For example use a ','
between R, G or B and '\n' to mark the end of the data. To keep
things simple, never use those values as data values. That is pretty
much how programming languages work. It is much more complex to read
than fixed format data, but can give more flexibility.

Data is often sent as printable characters (e.g. 173 would be three bytes havig the ASCII values '1', '7', '3'). If it is fixed format, it would always be three bytes. For your purposes, I'd probably send each data byte as two hex characters (ASCII '0' to '9' and 'A' to 'F'. This is slightly more complex than pure binary. However it is fixed format, and more importantly it is easier to test by hand using the Arduino serial monitor, you can just type stuff and it is relatively easy to do.

Pure binary data is much more difficult to fully test, and often relies on a piece of software which also needs testing.

Summary: There are a couple of ways, it is hard to say which is best. For simplicity try to make it simple by being fixed format.

The communication between the arduino and processing is 9600bit/s I suppose.

This will mean, that one bit needs 0.104ms to be sent. But with your Arduino code and the while-function you don't wait till the 8 bits of your byte are arrived and the arduino-loop is to fast for the serial connection. Wit other words: you cant use our wihile() function, use an if statement:

int x;
if (Serial.available()>0) {
  x = Serial.read();
}

and for debugging you can include once more the Serial.print()-function

(Sorry for my terrible English...)


For loop not running I've been trying to get a for loop to run 9 times using the below code but can't get the loop to run.

void output() {
  int r;
  r = 1;
  Serial.println("Output");
  digitalWrite(Latch, LOW);
  for (int r=1; r >= 9;  r = r + 1) {
    Serial.println("Test");
    digitalWrite(DataOutput, Q[r]);
    digitalWrite(ClockPin, HIGH);
    digitalWrite(ClockPin, LOW);
  }
  Serial.println("Done For");
  digitalWrite(Latch, HIGH);
  digitalWrite(Latch, LOW);
}

Change

for (int r=1; r >= 9;  r = r + 1) {

to

for (int r=1; r <= 9;  r = r + 1) {

The for loop will only run while the second part is true.

As the 2 before me have said, you need to change

  r >= 9;

to

  r <= 9;

That should get it fixed for you.


Changing timing intervals with millis() My goal is to run a vibrating motor for specific time intervals. I am using the millis() function to successfully turn the motor on and off, but only if the intervalOn = intervalOff. The problem comes when I try to change the intervals to turn the motor on for e.g. 120 ms, then turn off for 200 ms etc. My code seems to cause AVR restart and my motor sometimes stays running. First I thought this is caused by insufficient decouple capacitor (I have 100 uF one) but when running the millis() code with one no-changing interval, it all works flawlessly...
Is there any other way to change the intervals?

The Vibrating() function gets called from the loop() whenever vibrEnabled = true

unsigned long interval = 0;
unsigned long previousMillis = 0;
int last = 120;
int pause = 200;

void Vibrating()
{
unsigned long currentMillis = millis();
static byte cyclesPassed = 0;

if((unsigned long)(currentMillis - previousMillis) >= interval)
{
    PORTC ^= (1<<PC1);//toggle motor

    if(interval != last) //this part causes the problem
        interval = last; //
    else                 //
        interval = pause;//

    cyclesPassed++;
    if(cyclesPassed == 8)//motor is on 4x
    {
    cyclesPassed = 0;
    vibrEnabled = false;
    }

    previousMillis = millis();
 }
}

Maybe your vibrating motor is actually shaking something loose. A dodgy batter clip or something.
Maybe your vibrating motor is drawing too much current and power-cycling the board.
Maybe your vibrating motor is doing weird, bad things like generating back-EMF spikes that it's sending back into the arduino.

It's probably number 3. Generally speaking, you never power motors off an output pin. Run the output into a mosfet or something with a flyback diode across it. Google "circuit to power motor from digital out".

The problems were caused by the vibrating motor. It's shaking caused the rotating part touched the surface and the motor stopped for a while.
Thank you for you help.


GPS module not working with sensor I am connecting my Soil Moisture Temperature Sensor SHT10 with GSM Module SIM900A and GPS GY-GPS6MV2. Individually, all components work properly and give proper values. But when I interface all three components with Arduino, only Temperature sensor seems to work and GPS does not give any values.
Even If I connect only SHT10 and GPS with Arduino Uno (without GSM), only SHT10 gives values but GPS doesn't.

My code is:

#include <AltSoftSerial.h>
#include <TinyGPS++.h>
#include <SHT1x.h>

AltSoftSerial gpsSerial (11,12);

TinyGPSPlus gps;

#define dataPin 6
#define clockPin 7
SHT1x sht1x(dataPin, clockPin);
float TEMP, HUMID;

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

void loop()
{
TEMP = sht1x.readTemperatureC();
HUMID = sht1x.readHumidity();
Serial.println(TEMP);
Serial.println(HUMID);
gps_value();
}

void gps_value()
{
while(gpsSerial.available())
{
gps.encode(gpsSerial.read());
}

if(gps.location.isUpdated())
{
Serial.println("Latitude: ");
Serial.println(gps.location.lat());
Serial.println("Longitude: ");
Serial.println(gps.location.lng());
Serial.println("Altitude Feet: ");
Serial.println(gps.altitude.feet());
Serial.println("Horizontal Dilution of Precision: ");  //lower the better
Serial.println(gps.hdop.value());
Serial.println("");
}
}

What is happening here ?

Datasheet of SHT10

You could have used SoftwareSerial instead of AltSoftSerial.Since you are using AltSoftSerial please go through its library file to check how you need to deal with it.
For Software Serial you need to use predefined Rx , Tx pins of Arduino rather than defining any other pins of it for Rx,Tx
for connecting those to Rx Tx of tempterature sensor.
For GPS try to define any 2 pins of Arduino as Rx Tx so that you can connect them to Rx Tx of GPS.Hope this helps you.


What's the best way to control a USB-powered desk light I recently bought a USB-powered desk light. Is it possible to control (turn on/off) it with the Arduino Uno? The desk light has 3W so needs 600mA.

Should I connect the USB wire with the 5V pin of the Arduino (which can spend up to 800mA) or should I use an external USB power supply ?
How to control the light when using an external USB power supply ?

You have a couple options here. The main idea is that you're going to add a switch to the light's circuit and that switch will be controlled by the arduino. It's important that you keep the electronics for the light and the electronics for your arduino separate, 600mA will damage your arduino which no one wants. You can power the light and arduino from the same power supply, make sure it can handle the power draw though.

To actually switch the circuit you could use an NPN transistor as mentioned above, with the lamp's - terminal flowing into the C pin, an arduino GPIO pin connected to the B pin and the E pin grounded. When you set your arduino's pin HIGH the transistor will allow current to flow and light up the lamp.

Another option that actually physically separates the circuits is to use an opto-coupler. They're little IC's that serve this exact purpose. The have a light and a light sensitive transistor inside them, so when the light illuminates, the transistor allows current to flow. In your case, you would hook up an arduino pin to the + pin on the light side of the coupler and ground the - pin. Then connect your lamp in the same to the other side, +5v into the + pin on the transistor side and the lamp's positive terminal to the output pin. Again, when the arduino pin goes HIGH, the lamp will light up.

power lamp from 5v source ( not from the arduino 5v port, but could be spliced into the same line powering the arduino or use a hub )
use a transistor to switch the usb 5v line

connect the base pin (and resistor) of the transistor to any arduino digital out pin


Is there a way to get my MacBook's date and time into Arduino IDE? I am using a DS3231 RTC module. It requires to set the time every time it is reset. I was wondering if I could read my MacBook's time and date and feed into the module at the setup stage. Is this possible?

P.S. I do not have to use a battery.

You can use __DATE__ and __TIME__ compiler time constants in IDE and do check inside of your setup() function if the RTC clock is zeroed then parse and set compile time values.

char cr[] = __DATE__;
char ct[] = __TIME__;

At the compile time these macros will be replaced with text constants "Apr  4 2019" and "10:35:22" respectively.

You could use softRTC library to get date/time from your system. So program flow could be get date/time from softRTC library during setup part and then use those variables in loop set your DS2321 RTC which will always be running till you poweroff.


Is 1MB flash enough for OTA upload in ESP-01? I'am asking this question, because in my ESP-01 OTA upload always fail. In fact update won't even start. When update was triggered esp wifi led(build in blue) indicates "working" , but after cca one second esp reset itself. And The original program remains and starts again...

Yes, 1MB is fine for OTA. There are, though, a few caveats when working with OTA that you must observe regardless of the flash size:

The maximum OTA program size is less than half the available flash size. Typically it is about 500kB. Two copies need to be stored in flash, plus the partition table and NVRAM. The rest of the flash on larger chips is most often dedicated to FS storage.
The device must first be programmed through USB with an OTA-compatible partition layout.
After programming through USB it must be manually reset or power cycled to set the boot mode correctly.
You can not change the partition layout over OTA programming. You need to make sure you have the same partition layout selected as when you originally programmed through USB.
ArduinoOTA.handle(); has to be called very regularly to handle the programming request. You can't have any blocking code in your sketch that might stop that from being called.

Observe all those and you should be able to program over WiFi with no problems.

Yes. 1 MB flash is enough for OTA update.


Checking for multiple values in IF separated by commata My code is:

if ((minute == 31) && (hour == 4, 6, 9, 11))
{
  digitalWrite(8, HIGH);
}

I want to turn on the LEDs when it is exactly

04:31,
06:31,
09:31,
11:31

However, the code above doesn't work.
Might be the multiple values the reason for this?

Yes, the list of values 4, 6, 9, 11 does not mean what you think it does.

if ((minute == 31) &&  ((hour == 4) || (hour == 6) || (hour == 9) || (hour == 11))) {
    digitalWrite(8, HIGH);
}

Optionally, you could store the values in an array and go across all of them with some code like this:

int hours = [4,6,9,11];

function isInArray(inputValue, array) {
    boolean isIn = false;

    for ( int i = 0; I < array.length; i++) {
        // "isIn |= statement" is shorthand for "isIn = (isIn || statement)"
        isIn |= (array[I] == inputValue);
    }

    return isIn;
}

if (isInArray(variable, hours)) {
    //do whatever
}

//might be able to do
if (isInArray(variable, [4,6,9,11])) {
    //do whatever
}


Which thermometer for home brewing Hello,

I have an Arduino Yun and I brew beer.

I would like to log the temperature of the beer at all time during the fermentation process (final stage).  This means the thermometer would have to remain in the beer during this time (10 days).  The temperature would be < 40 degrees Celsius (probably around the 20 degree mark).

Question: What temperature sensor would be best suited to this task?

It must be:

Food grade
Can be used in alcohol for extended periods
Can be hooked up to Arduino (i.e. add a library and ready to go)

Thanks, Dan.

You are looking for a thermocouple.

They need some specific chip to be read, so you'll probably want to spend a bit more and get a chip with a digital interface, there are some witch has arduino library, like MAX6675 (output at 1Hz, 0.25° precision).

As this chip read "C type" thermocouple, you just have to find the right probe for your needing, with probably can be found in many specialized store.

You may even buy a normal k probe, and then wrap it up in some protective case. Obviously that case should be designed to let the heat flow easily, but without short circuiting the probe; a food plastic bag;

or just spend a little more money and buy a stainless steel probe


Code uploads successfully on esp8266-01 but doesn't run I am using esp8266-01 board. It was working fine few days ago, the codes uploaded and ran successfully. But now that I upload code to it, it gets uploaded successfully but it doesn't work.

I am using arduino nano to program it. It is connected as:
esp-01       arduino nano
tx-------------tx
rx-------------rx
vcc------------3v3
ch_pd----------3v3
gpio0----------gnd
gnd------------gnd

the code is basic blink code:

void setup(){
   pinMode(2, OUTPUT);
   }
void loop(){
   digitalWrite(2, HIGH);
   delay(500);
   digitalWrite(2, LOW);
   delay(500);
   }

This code gets uploaded successfully (According to IDE atleast) but it doesn't run. LED connected to gpio2 is always on. I also tried gpio0 and gpio1 but no luck.

I have already spend days trying to fix this. Please Help.

if you are using a nodemcu, the pin numbers do not correspond to the digital pins, they correspond to the gpio pins. The digital pin 2 is the gpio 4 and the digital pin 4 is the gpio 2.
Here you have a list of digital and gpio pins:

D0 = GPIO16;
D1 = GPIO5;
D2 = GPIO4;
D3 = GPIO0;
D4 = GPIO2;
D5 = GPIO14;
D6 = GPIO12;
D7 = GPIO13;
D8 = GPIO15;
D9 = GPIO3;
D10 = GPIO1;


compiler says I have to declare my hexidacimal I try to compare #include <IRremote.h>

int RECV_PIN = 11; // IR Receiver - Arduino Pin Number 11
IRrecv irrecv(RECV_PIN);
decode_results results;

int led = 12;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if(irrecv.decode(&results)) //this checks to see if a code has been received
{
    if(results.value == FF6897) //if the button press equals the hex value FF6897
    {
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);               // wait for a second
        digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);               // wait for a second//do something useful here
    }
    irrecv.resume(); //receive the next value
}
  }

The issue is in the second if in the void loop the error I get is

  exit status 1 'FF6897' was not declared in this scope

why does he do this? Why doesnt it just accept my IRcode for comparison.

Nothing here that hasn't been covered in comments already but just putting it in the form of an answer to save digging...

How is the compiler supposed to know that a number is hex rather than decimal?

Sure 1234beef is obviously hex but what about 12345678? Is that hex or decimal?

You need some method for the compiler to know.

You also need some way for the compiler to know if something is a number or a variable. Take the code if (x == deadbeef) {...} is deadbeef a hex number or a variable name?

C uses a very simple convention. If it starts with a number it's a number, if it starts with a letter it's a variable. This is why variable names can contain numbers but can't start with them.

If an integer starts with an 0 e.g. 0123 then it's in octal.
If an integer starts with 0x e.g. 0x123 then it's in hex.
If an integer starts with something other than a 0 e.g. 123 then its in decimal.

e.g.

printf("123 = %d\r\n0x123 = %d\r\n0123 = %d\r\n", 123 , 0x123 , 0123);

returns

123 = 123
0x123 = 291
0123 = 83

This convention, especially the 0x prefix for hexadecimal, is very widely used in other programming languages.

By comparing my code to another one, I found out that putting 0x in front of the hex will fix it, I don't have a clue why this is though.