Sending data from Arduino to laptop via bluetooth using java

I was able to establish bluetooth communication between Arduino and my laptop successfully. I made some observations, which I'd like to share. BlueCove library which I've been using, ultimately communicates to the Arduino by constructing a bluetooth URL. This bluetooth URL is of the form btspp://bluetooth_address_without_colon:1;authenticate=false;encrypt=false;master=false.
To find the bluetooth address of a device, enter the following command in the terminal

hcitool scan

This will display a list of devices along with their addresses.
For instance, if my HC-05 has an address  20:16:10:09:47:93 then the bluetooth URL can be formulated as
btspp://201610094793:1;authenticate=false;encrypt=false;master=false.
Note that the '1' here represents the rfcomm channel. By observation, I've found that HC-05 modules use rfcomm channel 1.
In your project, ensure that you import the two jars of BlueCove libraries viz bluecove-2.1.0.jar and bluecove-gpl-2.1.0.jar (latest version). You can download them from here.
This is the Java code for communicating with the Arduino to turn an LED ON/OFF:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
public class HC05 {
boolean scanFinished = false;
String hc05Url =
"btspp://201610094738:1;authenticate=false;encrypt=false;master=false"; //Replace this with your bluetooth URL
public static void main(String[] args) {
try {
new HC05().go();
} catch (Exception ex) {
Logger.getLogger(HC05.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void go() throws Exception {
StreamConnection streamConnection = (StreamConnection)
Connector.open(hc05Url);
OutputStream os = streamConnection.openOutputStream();
InputStream is = streamConnection.openInputStream();
os.write("1".getBytes()); //'1' means ON and '0' means OFF
os.close();
byte[] b = new byte[200];
Thread.sleep(200);
is.read(b);
is.close();
streamConnection.close();
System.out.println("received " + new String(b));
}
}

This the Arduino code for controlling the LED:

int ledPin = 13;
int flag = 0;
int receivedData;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(9600);
}
void loop() {
if(Serial.available()>0){
receivedData = Serial.read();
flag = 1;
}
if(flag == 1){
switch(receivedData){
case '0':
digitalWrite(ledPin, LOW);
Serial.println("LED Turned OFF");
break;
case '1':
digitalWrite(ledPin, HIGH);
Serial.println("LED Turned ON");
break;
default:
Serial.println("Nothing here");
break;
}
flag = 0;
receivedData = 12;
}
Serial.flush();
}

Thanks to @Sigma for sharing some valuable information

Reference:

https://stackoverflow.com/questions/33473926/best-practice-java-serial-bluetooth-connection-hc-05


Weird arduino bug, using microphone and relay

I've looked through your code and can't see anything obvious that is causing the problem, so I have refactored it a bit in the hope that the problem becomes more obvious.

/* DEFINE PINS */
const int PinBuzzer = 2;
const int PinMic = 0;
const int PinRelayLED = 9;
const int PinRelayLights = 8;

const int sampleWindow = 50;
const int MaxSamples = 50;

// Simple enumeration to clarify which state is on and off.
enum EOnOff { Off, On };
EOnOff lights = Off; //lights on or off
EOnOff leds = Off; //leds on or off

double soundArray[MaxSamples]; //array to check claps

void setup()
{
    pinMode(PinRelayLED, OUTPUT);
    pinMode(PinRelayLights, OUTPUT);
    digitalWrite(PinRelayLED, ConvertOnOff(leds));
    digitalWrite(PinRelayLights, ConvertOnOff(lights));
}

void loop()
{
    for (int sample = 0; sample < MaxSamples; ++sample)
    {   // Get the samples
        soundArray[sample] = getVolts();
    }
    switch (clapCount())
    {   // Analyse the samples
    case 2:
        lights = ChangeRelay(lights, PinRelayLights);
        playSound();
        break;
    case 3:
        leds = ChangeRelay(leds, PinRelayLEDs);
        playSound();
        break;
    }
}

/// Count the number of 'claps' in the sample data
int clapCount(/*clap array is global*/)
{
    int claps = 0;
    for (int sample = 0; sample < MaxSample; ++sample)
    {
        if (soundArray[sample] > 3.0 && soundArray[sample] < 3.5) /* Why 3.5?? */
        {
            ++claps;
        }
    }
    return claps;
}

/// Convert an EOnOff value to a HIGH or LOW value.
// OFF = HIGH
int ConvertOnOff(const EOnOff& state)
{
    return state == Off ? HIGH : LOW;
}

/// Change a relay to the given state.
/// Return the new state.
EOnOff ControlRelay(const EOnOff& state, const int& relayPin)
{
    EOnOff result = state == On ? Off : On;
    digitalWrite(relayPin, ConvertOnOff (result));
    return result;
}

/* gets mic volts */
double getVolts()
{
    const unsigned long startMillis = millis();  // Start of sample window
    unsigned int signalMax = 0;
    unsigned int signalMin = 1024;

    unsigned int sample;
    // collect data for 50 mS
    while (millis() - startMillis < sampleWindow)
    {
        sample = analogRead(PinMic);
        if (sample < 1024)                  // ?? Should this be 1024 or signalMin?
        {
            if (sample > signalMax)
            {
                signalMax = sample;  // save just the max levels
            }
            else if (sample < signalMin)
            {
                signalMin = sample;  // save just the min levels
            }
        }
    }
    const unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
    const double volts = (peakToPeak * 5.0) / 1024.0;       // convert to volts
    return volts;
}

void playSound()
{
    tone(buzzer, 1000);
    delay(100);
    tone(buzzer, 500);
    delay(100);
    noTone(buzzer);
}

What I have tried to do is to reduce the number of lines of code.  If there are less lines then there should be less bugs :)

You used a bool to record the on off state, I changed that to an enumeration because that adds a bit of clarity, and when working with mains voltages I like things being clear.

I changed your while loop into a for loop, I think it looks cleaner.  This was also the reason I changed your if statements into a switch statement.

The guts of the if statements have been removed and placed in a function ChangeRelay(), it returns the new state of leds or lights.  I could have gone with a reference to make state an in out parameter, but decided a return was simpler.

ClapCount() and GetVolts() are relatively unchanged apart from a bit of const'ing of variables to make things easier to read.  Also you might have noticed I, j and N have all been removed, because single letter variable names are my nemesis, who knows what q means and why r and t are being added to it to make z?

ControlRelay lets you route all you relay switching through one function, if there was a copy and paste bug in your code (which I don't think there was) then they will either all work or not work now.

There is a big difference between "my" code and yours, you won't be able to switch both on at the same time because the switch statement won't let you.  So in a way you problem is solved.  If you really wanted to you could add:

case 5:
    lights = ChangeRelay(lights, PinRelayLights);
    leds = ChangeRelay(leds, PinRelayLEDs);
    playSound();
    break;


I think that in this case you will need multiple solutions for generating the power.

You need to know how much power you need.  This depends on you solution, I can't help there.
You need a backup battery, ideally one that doesn't mind constant trickle charge and deep discharge.  Sealed lead acid are probably the best.
Your battery must have enough power over a long enough time.
You need a power generator, wind, solar, water, chemical. And they should all have a common interface so you GeoCache is modular, so the GeoCaches can be plugged into any of the power sources, maybe even more than one source.

The problem with the power source is it is going to be a visual clue to where the cache is, probably also an audio clue.
The battery, if SLA, is going to be a great big lump that could be dangerous if damaged.
The caches are not going to be cheap, just because of the power source and battery, so I hope you have deep pockets.

Rather than looking for a ESP01+BT4 module look for any microprocessor with BT built in, it maybe a better way to go.


I2C Temperature Sensor Communication Issue

Wire.requestFrom(Temperature_Register_DATA, 1);

This should have the WeatherAddress as parameter instead of the register.

Wire.requestFrom(WeatherAddress, 1);


This is part of the code I have been using for an extraction fan, The button text is tested and if the button matches the command the fan is turned on or off and the button text is changed accordingly. Hope this helps.

void b19PopCallback(void *ptr) //Extraction Fan
{
  NexButton *btn = (NexButton *)ptr;
  memset(buffer, 0, sizeof(buffer));
  btn->getText(buffer, sizeof(buffer));

  if (strcmp(buffer, "ON"))
  {
    //COMES BACK AS A FALSE (0) IF BOTH STRINGS MATCH
    digitalWrite(b_motor, LOW);
    strcpy(buffer, "ON");
    btn->setText(buffer);
  }

  else
  {
    digitalWrite(b_motor, HIGH);
    strcpy(buffer, "OFF");
    btn->setText(buffer);
  }

}


does EEPROM.write() only writes changed data?

From library Library, see fragment:

  EEPROM.write does not write to flash immediately, instead you must
  call EEPROM.commit() whenever you wish to save changes to flash.
  EEPROM.end() will also commit, and will release the RAM copy of EEPROM
  contents.

Probably to prevent too many writes into the same page (mostly EEPROM is divided in pages), the write stores it into some temporary buffer and the commit actually writes it to EEPROM. This decreases the number of writes, and since the number of writes has a maximum, the lifetime of the EEPROM is increased.

Update: Majenko's comment mentions no EEPROM is used, but flash, see below.


How do I get sensor values using transmitter and reciever

First: A short excourse about c-strings
In C a string is an array of characters. Such an array is defined with
char msg[10];

10 being the size of the array. Every valid c-string needs to be terminated with the null character \0. This character is not printable, thus you don't see it normally. But the standard string functions (like printf(), strlen(), etc) use the null character to find the end of the string. So when handling strings as char arrays, you absolutely always need to terminate the string with the null character. The standard functions are incrementing through the array, until they find the null character. If it is missing, they don't stop at the end of the array.
Needing the null character also means, that the above char array can only hold 9 characters (since the 10th is the null character).
The standard functions for creating a string (like printf() and its siblings) already terminate the string correctly with the null character.

You are obviously trying to send an ASCII encoded string. But sensorval is not a string, it is of type int (a number). In C/C++ one does not simply implicitly convert a number to a string (please insert the image of boromir from Lord of the Rings here in your head). You actually have to say the compiler how to convert the number to a string. Also sensorval cannot itself hold that string (as it is an integer number). For that you need a char array (often called c-string) for saving all the characters of your string.
So first we need to define the char array to hold our string:
char msg[10];

This creates a char array with 10 elements, each one can hold a character of your string. So you have space for 9 characters. If you need more, you can increase that number.
Now we need to build a string in msg, that represents the value of sensorval. For that we can use sprintf(), which lets us format a string out of data and save it in a char array.
sprintf(msg, "%d", sensorval);

The first parameter is the char array to put the string in. The second parameter is called format-string. That is a string literal, that defines the format. %d represents an integer value; it is a placeholder for the actual data and describes, how it should be formatted (you can read about the different format options in the C++ documentation if you search for printf()). The following parameters (here only one) are the data values for the placeholders in the format string. Let's take an example: Assume sensorval is 1000. Then msg will be:
1000\0

The \0 being the null character.
So in your code you would replace
const char *msg = sensorval;

with
char msg[10];
sprintf(msg, "%d", sensorval);

What you have done in your code:
This line
const char *msg = sensorval;

will NOT create a string. You are defining msg as a pointer to a constant character (a pointer is a variable, that holds the address another variable in the memory, use google terms like "C pointers" for more info). And then you set the pointer to sensorval, which of course is not a valid pointer (valid meaning pointing to something reasonable here). It just points somewhere in the memory.
The example, that you got it from uses:
const char *msg = "hello";

This works, because the compiler takes all string literals (the strings enclosed by the double quotes) and puts them fixed into the memory, somewhat like a variable without a name. So here the compiler instructs the microcontroller so save the string "hello" in the memory. With the above line we define a pointer to the place in the memory, where this string is saved.
So this works good for string literals, but not, if you first need to actually build the string.


Can I connect my arduino ground to an external battery ground? Are they the same when said battery is powering the arduino?

A battery's ground is floating. That means that it's "happy" to take on any absolute value by simply connecting it to another ground - it just stops floating. This is why it's easy to connect a battery-powered phone directly to a computer to get the photos off or whatever.

The only time you shouldn't connect two grounds is if neither are floating. A good example would be the grounds of two different houses, which are physically connected to the Earth (as in the planet). It'd be difficult to budge the whole Earth's ground level!

But shouldn't they be the same? Unfortunately not. You could measure a distinct voltage difference (sometimes in the hundreds of volts) between two house earths due to the differences in their makeup.

One small note: if you do connect two grounds, only connect them in one spot. If you have two other ground pins a small distance away from the connected ones, there may be a voltage difference between them: now the two are explicitly relative to each other, so neither can be considered floating relative to each other. The pair as a system - if neither are earthed at least - is still floating.

These so-called "ground loops' can induce current where none is desired.


Unfortunately, no, as the FT232 would have to act as a USB host device. A USB host shield might work if someone has written driver code to support 3G modems.


Arduino IDE fails on Fedora with arduino-builder error "Parameter 'tools' is mandatory"

I don't understand why this worked, but I found this comment in Redhat Bugzilla (it doesn't seem to be a bug report specifically about that...but anyway):

    Parameter 'tools' is mandatory
    [...]

  However, if I create the packages directory in ~/.arduino15, compilation now works.

mkdir ~/.arduino15/packages

Seemed like an easy thing to try, and voila -- after an hour of fuss.

I do not understand why this is so (nothing ends up in that directory, either) but I'm leaving this in hopes it may save someone else some time.


You can just connect the pins used on the shield the the corresponding pins on your custom board. Check the Schematic to see what pins are used for what (and which can be left unconnected)

The only thing you need to lookout for is, that the ethernets shield seems to require 3.3v (the shield has it's own 3.3v regulator, so you only need to connect 5v)

That 16u2 doesn't do anything but usb-to-serial. It's not needed for the ethernet shield.

The ISP header is just 5v, GND, and the 3 SPI pins and reset. But those SPI pins are also broken out to the pins 11, 12 and 13.


Why doesn't pin 19 work when powering the EzSBC Esp32 board from batteries?

There is a subtle design choice in this board that took be hours to figure out.

According the connection schematic the blue leg of the LS3528RGB LED is connected to IO19 through a 1k resister (R2-1).  However the power leg is connected to Vusb not 3.3V like the other RGB LED.  This means that the LED connected to IO19 is only usable when the board is connected through the micro-USB port and not when connected directly to battery.

This can be useful for programmatically reading whether the board is running on battery or USB.


Path relater errors on compilation in Arduino IDE 1.8.5 under Windows XP

I have realized that the root cause was the windows user with the Cyrillic name. So creating a new user wiht base Latin name and running Arduino IDE from it helped


I think you are asking

if (value > 5)
{
  StatementOne;
  statementTwo;
}

But I think you might want to write a function, which would look like this

void doThing(int button, int led)
{
  if (digitalRead(button))
     digitalWrite(led);
}

[Edit after reading your comment]
So you need to store the state of the system as a variable in the code.

bool state = false;
if (button1 && !state)
{
  state = true;
  // Your on code.
}
if (button2 && state)
{
  state = false;
  // Your off code
}

You need to add your existing code for turning your LCD and LED on and off where the comments are.
The state variable holds the on or off state of your LCD and LED.
You can of course split it even further so your LCD and LED come on separately of each other.

Does that help?  If so don't forget to mark it as answered.


Not sure if this is just an academic exercise on your part to learn (which is totally cool), but if you're just trying to move forward and get something working you may consider one of the many excellent button libraries out there for Arduino.

I recently used a library called ButtonKing that allowed me to do some very sophisticated menu interactions on a MKR1010 with a display and single button interface.  There are several other libraries out there as well that take care of debouncing, long clicks, double clicks, etc.


Digispark uploading not working in KDE Neon (Linux)

I had the same problem when using the snap package of the Arduino IDE. I solved the problem by installing the Arduino IDE from the official web page: https://www.arduino.cc/en/software
You might have to run the Arduino IDE with sudo or better add a custom udev rule in case you now get following assertion error:

'micronucleus_connect: Assertion `res >= 4' failed.'

Solving the assertion error is further described in following post: https://digistump.com/board/index.php?topic=106.0


How to do run time calibration for MPU9250?

I used this script to calibrate the MPU6050, which is the same as the MPU9250 minus the digital compass. This guide explains how to calibrate the MPU9250's magnetometer.


What kind of Arduino should I pick for a calculator?

Start with the biggest (AVR) Arduino you can afford, and worry about miniaturizing it once you have the basics in place. You may find that you don't actually want an Arduino in the end, but something like the ATmega169PA instead so that you have native LCD support (instead of having to use a discrete LCD module).

  P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Doesn't matter. Most of your x86 assembly experience will easily transfer to AVR (but not all, since the AVR core is simpler than x86).


problems with Blue Pill (stm32f103c8t6) direct register manipulation

you need to use something like this:
ADC1->CR2 = ... ;

note 2 things:

you need to use ADC1, ADC2 ... to access the registers. not just ADC.
you need to use arrow (->) operator to access the registers

and you may need to include the header file, something like this :
#include <stm32f030x6.h>

find the proper header file for your MCU. (it's not the same as stm32f1xx, but if proper definitions are made somewhere, it may also work)


What's on an Arduino board? Can i build one of these boards myself?

When I first built my first Arduino clone, I fount very useful the Fritzing examples (boards and schematics). http://fritzing.org/home/

Mind that in order to upload sketches, an FTDI module is very handy (unless you use ISP via another Arduino board).

In any case, I should recommend you to build an Arduino clone on a breadboard, before trying soldering.

Good luck.

Additionally, you may use this picture (this is how  I create an Arduino on breadboard):

External power (battery) is connected to the screw pins (bottom left of the breadboard).


Yes, and yes.

A module without an antenna is exactly the same as a module with an antenna, it's just that the antenna is part of the PCB. Yes, the module with the antenna will have more sensitivity (able to receive fainter signals) as well as more transmitting power.

The same is true of the modules with the power amplifier.  They again have even more sensitivity and transmitting power.

It is quite common to have a single powerful transceiver with power amplifier and antenna as a base station and then smaller modules as the remote slave devices.  Especially if you couple the base station with a suitable parabolic or uni-directional high gain antenna to point directly at where the slave devices are.


Arduino ultrasonic distance meter doesn't display correct distance

To solve a problem like this you need to break it down into smaller pieces so that you can build up some confidence about what is working and what is not. When you share a problem like this as a question it helps if you can give us some idea of your experience level and of what you've already done to debug the problem – that helps with avoiding telling you what you already know and makes it easier to focus in on where the problem might be.

From what you've said it appears that you have things working well enough that you get a display on the LCD but it does not represent a meaningful distance.

Looking at your schematic the first thing that comes to my mind is that you have the ultrasonic sensor at the opposite end of the breadboard from the LCD. Many breadboards split their power rails at the middle. So start by confirming that you have power to the sensor.

After that, double-check the rest of your wiring.

The next step for me would be to confirm that I understood the sensor and to try and prove that it was working as I expected. Look for some sample code that is known to work (often the site you bought the sensor from will have links to beginning tutorials or code samples). Try that to see if the sensor works with the sample code.

If that doesn't work then check to see what you can do to prove the sensor is good (or bad). You might also contact the vendor to see if they can give you advice on proving that the sensor works.

Basically, break the problem down into "bite sized" chunks and work through it one step at a time, doing the simple stuff first. Try not to assume anything…


Calculate battery (18650 Li-ion) voltage using ESP8266-12E

Everything was correct and my circuit is also good. The only difference i found is to this below line:
temp = (analogvalue * 3.3) / 1024.0;
Which should be
temp = (analogvalue * 1.0) / 1024.0;
We are multiplying because we are referencing the voltage from voltage divider circuit as 1 volt.
After doing this, i am getting the exact values battery voltage which then i convert to percentage.
Thank you!


bluetooth module with stk500_recv() error

How did you upload the sketch? With the Bluetooth module still connected? In that case please disconnect it and the upload. Connect again after the upload.


How to connect ESP8266 12e directly to Arduino Uno (without shields)

Make sure to specify as SoftwareSerial's Rx pin, the pin# connected to the ESP's Tx pin. They have to be crossed. (I just fumbled that myself, a couple of hours ago ):

It is the ESP's Rx pin that needs the voltage divider.

Also pullup the ESP's reset pin.

Update:

ESP-01 and ESP-12 modules use the same ESP8266 chip. The differences are in the number of pins brought out from the chip and made available on the board. Other differences include the firmware interpreters installed on them before shipment: "NodeMCU" is one. ESP-01 is usually shipped with the AT+ command interpreter unless it specified otherwise; I would expect the same for the others. Bottom line is they are connected pretty much alike. Interacting with them serially from an Arduino (or other device) then depends on the installed firmware, including whether you've installed your own. So far, I've used all of mine as WiFi modules using the AT+ interpreter they came with.

  How can I pullup the reset pin? Also do I need to pullup it just for
  initial setup (changing baud rate and such) or should it be pulled up
  at all times?

I use a 10K-Ohm resistor to +3.3v as a pullup. You need it pulled up anytime you are not trying to force a hardware reset; grounding it resets the chip. I have never used a reset button on my ESPs. I just leave them pulled up. If you want one, it should short the reset pin to ground.

Update 2 (wiring):

You've powered the ESP with 3v but your pullups are taken to the Arduino's 3.3v supply. Most chips have a slim tolerance for signal levels above their supply voltage. I'd suggest driving the entire ESP from your 3v battery - power & both pullups.

I don't know the ESP-12E's pinouts to check them; I'm sure you have, and you might want to label the diagram so someone else can look over it too.

Then there's whatever "chicken dance" is needed on the reset and the GPIO line that needs to get toggled to start an upload. I don't know that sequence, but I think you need a grounding buttons on on each one to be able to sequence them.


Arduino Yun with PoE does not work when powered via PoE

PoE Adapter

Silvertel AG9600 1R requires a 100µF 16V Electrolytic Capacitor between it's PIN 7 and PIN 8

According to the PoE Yún Thread the capacitor polarity should be as follows:

  PIN 7 --> Capacitor_Negative. PIN 8 --> Capacitor_Positive

solved my problem. I think the default 470uF capacitor might not be able to charge-discharge appropriately with data signals in the PoE.


How is the bootloader activated when device is running?

On microcontrollers with bootloader (not just AVRs), the bootloader is a separate executable in flash, and it's typically the program that runs on system startup.  The application will have a special trigger, such as a button sequence, getting a specific byte sequence over I2C, or really anything that will tell the bootloader to enter into its "update" mode.  From there, the bootloader will have some communication (I2C, USB, WiFi, serial, etc) to download and the flash the new application image.

This link has more information about the Arduino bootloader

  On the PC side, to trigger a reset on the RESET pin, the PC (avrdude.exe or GNU/Linux equivalent) opens the serial port to Arduino when your press upload and the code is ready to upload. This causes the Data Transmit Ready (DTR) line of the USB/TTL chip to go LOW. The Arduino board has a capacitor charging circuit that uses this LOW (charging the capacitor) signal to momentarily pull down the RESET line of the ATMEGA328P chip before returning it to HIGH (capacitor charging completes). So Arduino resets each time its serial port is opened.

  Upon reset, Arduino enters the bootloader.

  The bootloader looks at the source that caused the reset. There are several sources that can cause a reset. If the reset was caused by the RESET pin, then it waits for one second for the PC to send in commands. When it receives valid commands, it will start accepting new Arduino code in HEX format and erase the existing code to load new one. If it doesn’t receive valid commands, it times out after one second and triggers a Watch Dog Timer (WDT) reset.

For Arduinos with built-in USB, such as the Micro, the Arduino library (firmware) triggers the system reset.  There's a little chunk of code that looks for the virtual COM port to open at 1200 baud and then close.  When that happens, the code triggers a system reset (by writing a register, typically) which launches the bootloader.

  Rather than requiring a physical press of the reset button before an upload, the Micro board is designed in a way that allows it to be reset by software running on a connected computer. The reset is triggered when the Micro's virtual (CDC) serial / COM port is opened at 1200 baud and then closed. When this happens, the processor will reset, breaking the USB connection to the computer (meaning that the virtual serial / COM port will disappear). After the processor resets, the bootloader starts, remaining active for about 8 seconds. The bootloader can also be initiated by pressing the reset button on the Micro. Note that when the board first powers up, it will jump straight to the user sketch, if present, rather than initiating the bootloader.

  Because of the way the Micro handles reset it's best to let the Arduino Software (IDE) try to initiate the reset before uploading, especially if you are in the habit of pressing the reset button before uploading on other boards. If the software can't reset the board, you can always start the bootloader by pressing the reset button on the board.

Personal story: I wrote an I2C bootloader for the PIC32.  The only communication with the device was through the I2C bus.  The main application had a special 3 byte trigger that would set a non-initialized variable in RAM, and then trigger a system reset.  The bootloader, which runs on system startup, would check that variable and if it was set, would wait for commands over I2C to download and flash the new application image.  That variable in RAM had to be specially marked as non-initialized, otherwise the C startup code would clear it and the bootloader would never update.

The bootloader also calculated a CRC32 over the application image to validate it before attempting to boot.  If the calculated CRC32 didn't match the stored CRC32 (which was part of the application image), then the bootloader would enter its firmware update mode.  This was a guard against trying to run a corrupted firmware image, which could happen if power was pulled during the update process.


Arduino reads string from another Arduino only if the string is in a loop why?

exit(0) is not the command to use, it is used to completely stop the program, although I'm not sure what happens exactly for an Arduino sketch.

To stop a loop (and continue, normally a break statement is used. This works inside a while or for loop and the sketch continues after the while or for loop where the break statement is executed.

Note, you also can start at the beginning of the while or for loop with the continue statement.


You have to #include <Arduino.h>, or compile with the -include Arduino.h flag. The Arduino IDE normally does that for you, but you have to do it yourself if you are working outside the IDE.

There are a couple of Arduino Makefiles floating around the Web which, just like the IDE, take care of this for you.


You cannot check, if a servo or a wire is physically connected to the pin, without extra effort. The Servo library uses Timer interrupts to create a PWM signal for the servo on the used pin. For this the pin is configured as OUTPUT and cannot measure anything except of the value, that was written to it. In most servo motors the PWM input is high impedance, so that the current draw from the PWM pin is very low.

To solve your problem you have 2 possibilities:

Use a special connector, that has 2 extra pins with a mechanical switch, which gets closed, when the connector is put together. (The same principle as in SD card holders)
Measure the current, that the servo uses through it's power supply pins, with a suitable circuit.


As it sounds like you do not own the buzzer (it is part of the appartment), someone may not like you directly connecting to it.

If this is a classic buzzer with an electromagnet, consider using a Hall Effect Sensor.  The magnetic field generated by the buzzer may be able to activate the Hall Effect Sensor and inform the Arduino the buzzer has been activated.  This article talks about Hall Effect sensors and an Arduino.

Image of Arduino and Hall Effect Sensor from linked to article:

Further, this is a much safer way connect to a buzzer.  As a classic buzzer can generate very high voltages that can damage processors and other sensitive electronic devices when directly connected.


I don't know if it's thread safe or not. However I would be inclined to play it sage and use a queue and notifications.

Create a queue
Create a "sender" thread that waits for notification then sends anything in the queue through UDP
Create any number of "sensor" threads that place items into the queue then notify the sender thread.


Limit to number of sensors attached to Arduino

There is no answer that can be given to you that is "correct". However, there are things for you to consider in your design process:

Can you fit all the code in flash, and the required variables in RAM?
Does the chip have all the IO you need, and can you use the required internal / interfacing peripherals in the right combinations to satisfy your requirements
Do the devices fit within your power budget (battery capacity, required run-time, power regulation efficiency).

The Arduino is just a component. It belongs in a circuit, and that circuit is what determines everything else. The ATMega328P has certain power requirements, as do all the other components in your circuit. It is up to you to design the right power system to provide that power with the right efficiency and power saving options (switching off circuit segments when not needed to save power), etc.

For prototyping and experimenting the Arduino provides a rudimentary power supply which is wildly inefficient. Not recommended for any battery powered scenario or any high current usage.


Native function name w/o parens -- expected behavior?

I've made up a test case:

const unsigned long GATE_OPEN_TIMER = 7000;
const unsigned long GATE_CLOSE_TIMER = 12000;
unsigned long gateStopTime = 0;

void setup()
{
  if (millis >= gateStopTime) {  // if current delay expired
    gateStopTime = millis + GATE_CLOSE_TIMER;
  }
}
void loop()
{
}

Under IDE 1.6.9 I get these errors:

/tmp/arduino_modified_sketch_345879/sketch_oct27a.ino: In function 'void setup()':
sketch_oct27a:7: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
   if (millis >= gateStopTime) {  // if current delay expired
                 ^
/tmp/arduino_modified_sketch_345879/sketch_oct27a.ino:8:29: warning: pointer to a function used in arithmetic [-Wpointer-arith]
     gateStopTime = millis + GATE_CLOSE_TIMER;
                             ^
sketch_oct27a:8: error: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int' [-fpermissive]
     gateStopTime = millis + GATE_CLOSE_TIMER;
                           ^
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]

Under IDE 1.6.12 they are downgraded to warnings:

/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino: In function 'void setup()':
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:9:21: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]
       if (millis >= gateStopTime) {  // if current delay expired
                     ^
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:10:33: warning: pointer to a function used in arithmetic [-Wpointer-arith]
         gateStopTime = millis + GATE_CLOSE_TIMER;
                                 ^
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:10:31: warning: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int' [-fpermissive]
         gateStopTime = millis + GATE_CLOSE_TIMER;
                                   ^

Sketch uses 512 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 13 bytes (0%) of dynamic memory, leaving 2,035 bytes for local variables. Maximum is 2,048 bytes.

So, the compiler isn't totally letting you get away with it. You should check the warnings. But why are the warnings only warnings?

Checking the generated compile command (using verbose compiling) I see that 1.6.12 has an extra option: -fpermissive.

From the documentation:

  Downgrade some diagnostics about nonconformant code from errors to warnings.  Thus, using -fpermissive allows some nonconforming code to compile.

So you have "nonconformant code" but you are getting away with it.

I don't know why the Arduino devs did that. The whole point of making things like that errors is so you fix them at compile time, rather than scratching your head about why things don't work at run time.

Clearly the symbol millis exists. But it is a function (or perhaps a pointer to a function) and thus shouldn't be just compared to a number or have a number added to it. That's what those errors were about in 1.6.9.

Just remember, in C, C++ and the ilk, to call a function you always use parentheses, even if you are passing no arguments.


First of all: 9V means that you are using a 9V "transistor" battery (like this), right?

If so it won't last very long: I suggest you to use a different approach (e.g. four AA batteries in series).

As for your question, I couldn't find the power consumption for these leds. Try to measure it yourself, setting the max brightness and white color. I think that, anyway, the max current for each LED should be 60mA (20mA for each color). This means that each strand absorbs 1.2A (quite a lot!).

This power requires you to use at least a switching regulator. I always used some small modules I found on ebay (they have a LM2596 IC, so just search LM2596 on ebay to find them). They are rated for 3A, so you should put at least two of them (1.2 * 3 strands = 3.6A > 3A).

The connections are quite straightforward: the board has four pins: IN+, IN-, OUT+ and OUT-. IN+ of all the modules go to the positive terminal of the battery, IN- and OUT- of all the modules go to the common ground node (negative terminal of trinket, battery and leds), OUT+ is the 5V regulated output. Oh, by the way, they are adjustable modules, so BEFORE ATTACHING THE LEDS use a multimeter to set the correct voltage (if you attach the leds without regulating the voltage you can destroy them).

Since you will have a lot of current left on the second module, you can power the trinket from there (so you will not waste a lot of power).

One last thought: 9V batteries usually have a capacity of around 600mAh; if you use one of them with the switching modules and drain 4A from the 5V your battery will last 0.6Ah / 4A * 9/5 = 0.27h = 16 minutes; if you switch to 4 AA batteries (around 2000mAh) it will last 2Ah / 4A * 6/5 = 0.6h = 36 minutes. More than double (calculations made rounding up the power drained by 21 leds set at max brightness and white color)


ATtiny85 communication with computer through USB

Digispark made a lot of these as part of a "cheap Arduino USB interface" project a while back.

This is my Digispark, it's pretty cute:

They have a web page here.

I got them for about $2 each. The board has the ATtiny85, a voltage regulator, and a handful of other parts.

Schematic (courtesy of Digistump Wiki):

More information about the Virtual USB idea at USB-Keyboard with Arduino and V-USB library, an example.


Can I daisychain multiple Arduino Nanos to a single USB port (specialized purpose)

For a USB topology to operate one needs a USB controller which knows about all the different USB protocols necessary to communicate with all the different USB peripherals (this is why a USB controller is usually a fully capable computer) all connected through a USB hub.  It is unlikely a USB network could be created using only peripheral USB devices which were wired directly together.

To communicate between several Arduinos and a computer it would be much easier to use a serial bus made for multiple drops like RS485. There are many RS485 to USB converters available like this one for computers that do not have an RS485 port.


Using Bluetooth module HC-05 when Arduino is powered using a battery

6F22 (PP3) batteries are among the wimpiest of batteries available.  They are not a good choice for anything except extreme low power applications, and anything involving radio transmitters is definitely not an extreme low power application.

Use a better battery.  I would recommend 6 AA batteries (you can get 6xAA battery holders with the same connector as a PP3 battery) which will give you considerably more power than a little PP3.

Either that or a 7.2V "2S" Li-Ion battery pack.


Merging strings and constants causing scope errors

Maybe? Not sure, but give this a try.

#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"


How to control 6 servo motors with an Arduino Mega board?

The Arduino Mega can handle at most 40mA on the I/O pins, and 200mA on the 5V/GND pins. Six servos will draw far more current than the max of 200mA. You could try hooking up the servo power to a separate power source and the data pins to the Arduino. Hope this helps!


MAX7219 powered on via digital pin set to HIGH is not working good (I < 25mA)

After some research I eventually solved my problem, so here's the answer.

  Why does it happen?

This LED display draws much more current than I measured on Vcc line between Arduino and display because of ghost powering via signal lines (DIN, LOAD, CLK). The display (although slightly dimmed) can even run without Vcc line connected! Real current draw was about 30-40 mA with peaks up to 100 mA.

  Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

Yes, by limiting display current draw.

For an unknown reason these cheap MAX7219-driven LED boards has very small current control resistor RSet of 10 kOhm, resulting in huge Iseg ~= 40 mA. Replacing it by something like 62k will limit per-segment current to ~10 mA.

This is what the datasheet says:

And this is how it can be done:

Works perfectly! Now I can power off LED display completely, so it consumes no current when the device is sleeping.

NOTE: it's important to properly re-initialize MAX7219 after power on!

In the colorized table above one could find display current draw for different software-set intensity settings in case of using RSet = 62k. GND line values (blue column) seems to be correct as they well correspond with overall device's current draw (the most correct measurement, I suppose).


I hope there must be an inbuilt pull-up resistance for each GPIO registers of ESP.

Test like this and post your observation:
 1. Don't connect anything(ULN2003 jumper wires) to your ESP and check the GPIOs you selected whether they are floating or not. If no float in reading then it's fine.
 2. Connect the load and test the GPIOs are floating or not.


I did not experience the problem because I usually use a Makefile instead of
the Arduino IDE. I now tried with the IDE version 1.0.5 and I had the same
problem as you. The fix is to explicitly declare the function before
defining it:

void Move(Dir direction, int distance);
void Move(Dir direction, int distance)
{
     direction = forward;
}


Any idea why my LED fails to operate with the if statement

The LED fails to operate with the if statement because calling the return statement Terminates a function and returns a value from a function to the calling function, if desired. Try your sketch with the return statement as the "last thing" in the function.

#include <LiquidCrystal.h>

float tempC;
int tempPin = 0; // BS E D4 D5 D6 D7
int buzzer = 4;
int LED = 2;
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
unsigned char i;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Temp C ");
  pinMode(LED, OUTPUT);
  pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
}

void loop() {
  tempC = getTemperature();
  lcd.setCursor(6, 0); // Display Temperature in C
  lcd.print(tempC);
  delay(500);
}

float getTemperature() {
  int tempReading = analogRead(tempPin); // This is OK
  double tempK = log(1000000.0 * ((1024.0 / tempReading - 1))); //Temperature in Kelvin
  tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
  if (tempC>0) digitalWrite(LED,HIGH); else digitalWrite(LED, LOW);
  return (tempK - 273.15);
}


No response in Serial Monitor from es8266 with Arduino nano

If it is not a genuine Arduino (Chinese clone probably) and it has the CH340 USB to Serial converter chip, then it will not work as the digital Signal on TX does not get pulled to ground when transmitting a digital LOW, (if that's the right way to say it). There seem to be resistors on the board that cause this effect, or something. I do not guarantee that this is your problem but it's highly likely.
Use an FTDI USB to Serial board or similar and you might have better results.


Problem with Arduino and INA226 power meter module

There is a discrepancy in pin terminology between your schematic & what TI uses in their datasheets. I don't see anything in their datasheets using I+ or I-. I only see V+ & V-. These 2 pins perform all your voltage & current measurements depending on the "mode" you tell the IC to use.

As near as I can tell based on your schematic, you should be seeing the voltage reading based on what is applied between V+ & V- (In your case, 3.3vdc) if you've told the chip to read the bus voltage channel.

You should also be getting a current reading between the V+ & V- pins if you've told the chip to read the shunt voltage channel. Since the part is designed for a full scale voltage differential of 36v between the V+ & V- pins, I suspect a reading of about 10% of max (based on a 3.3v differential).

I confess to not knowing the board or its operation but having looked it up on the TI website, it does appear to have a few jumper settings & a calibration routine to follow. There's a user guide on TI's website as well as the usual technical data pages. Perhaps those will assist in setting the jumpers correctly. ina226 data sheet & eval board user guide
bc


Set up an Arduino Cellular Shield SM5100B

/*
 Band Management

 This sketch, for the Arduino GSM shield, checks the band
 currently configured in the modem and allows you to change
 it.

 Please check http://www.worldtimezone.com/gsm.html
 Usual configurations:
 Europe, Africa, Middle East: E-GSM(900)+DCS(1800)
 USA, Canada, South America: GSM(850)+PCS(1900)
 Mexico: PCS(1900)
 Brazil: GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

 Circuit:
 * GSM shield

 created 12 June 2012
 by Javier Zorzano, Scott Fitzgerald

 This example is in the public domain.
 */
 // libraries
 #include <GSM.h>

 // initialize the library instance
 GSMBand band;

 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
   }

   // Beginning the band manager restarts the modem
   Serial.println("Restarting modem...");
   band.begin();
   Serial.println("Modem restarted.");

 };

 void loop()
 {
   // Get current band
   String bandName = band.getBand(); // Get and print band name
   Serial.print("Current band:");
   Serial.println(bandName);
   Serial.println("Want to change the band you’re on?");
   String newBandName;
   newBandName = askUser();
   // Tell the user what we are about to do…
   Serial.print("\nConfiguring band ");
   Serial.println(newBandName);
   // Change the band
   boolean operationSuccess;
   operationSuccess = band.setBand(newBandName);
   // Tell the user if the operation was OK
   if(operationSuccess)
   {
     Serial.println("Success");
   }
   else
   {
     Serial.println("Error while changing band");
   }

   if(operationSuccess)
   {
     while(true);
   }
 }

 // This function offers the user different options
 // through the Serial interface
 // The user selects one
 String askUser()
 {
   String newBand;
   Serial.println("Select band:");
   // Print the different options
   Serial.println("1 : E-GSM(900)");
   Serial.println("2 : DCS(1800)");
   Serial.println("3 : PCS(1900)");
   Serial.println("4 : E-GSM(900)+DCS(1800) ex: Europe");
   Serial.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am.");
   Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)");

   // Empty the incoming buffer
   while(Serial.available())
   Serial.read();

   // Wait for an answer, just look at the first character
   while(!Serial.available());
   char c= Serial.read();
   if(c=='1')
     newBand=GSM_MODE_EGSM;
   else if(c=='2')
     newBand=GSM_MODE_DCS;
   else if(c=='3')
     newBand=GSM_MODE_PCS;
   else if(c=='4')
     newBand=GSM_MODE_EGSM_DCS;
   else if(c=='5')
     newBand=GSM_MODE_GSM850_PCS;
   else if(c=='6')
     newBand=GSM_MODE_GSM850_EGSM_DCS_PCS;
   else
     newBand="GSM_MODE_UNDEFINED";
   return newBand;
 }


Doorbell for someone with hearing issues

I know you are keen on using your Arduino.  But simpler solutions abound.  For instance, if the door bell already works at a lower then main voltage it might be easier to determine the feasibility of connecting a low voltage lamp to the door bell.

However, I can see a situation that an Arduino can fit very nicely into:

Events: 1) The door bell rings. 2) The Arduino senses this and starts turning on and off a room light at about 5 second intervals. 3) This can last until someone notices and resets the Arduino.  4) If no one is home to reset the Arduino, the Arduino stops turning on and off the room light after a minute passes (12 flashes).

There are 2 tricky bits that may need explaining.  The first is how to sense the door bell.  If mechanical you could use a micro switch:

That way you don't need to worry about isolating the Arduino from what is likely a strong electrically noisy solenoid.  The other tricky bit is controlling a room light.  I would suggest using a COTS remote controllable light switch (I just did a search and there are loads of them in every price range) and hack the (battery powered) remote control into the Arduino.


Random characters transmitted from ESP8266 to Arduino

The baud rates, voltages, and timing all have to match up for serial communication to work right.

So, set both of your devices to the same baudrate (you specify the number in Serial.begin()), and ensure they're connected properly. (voltages match, TX to RX, and ground is connected)

You can just read/print the serial input to the arduino with something like Serial.print(softSerial.read()) in your code if you think you don't have serial wired up right.

Also in an unrelated issue; the esp32 spits out data on its main serial line at 115200 when it boots up which you can not disable. you can use the serial port afterwards though.

Here's a copy of what gets printed out on one of mine;

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac


how to send argument to ESP8266WebServer objects on function

Use server.arg() to pass commands from the web as GET params:

digitalWrite (5, relay1);

becomes

digitalWrite (server.arg("pin").toInt(), relay1);

where the URL is something like http://192.168.1.5/relay1?pin=15

Of course, the rest of your code probably needs to be adapted to manage the extra states, read/write all in one http call, etc.


By default the EEPROM in the MCU is erased (to 0xff) when the chip is erased before flash is written to. If you want to prevent this then you will need to program EESAVE in the fuse bits, which is bit 3 in the high fuse byte of the '328.


Yes. Any pin can be used as a digital input/output. However, you cannot use certain communications when using those pins.

The types of communication and their effects on the pins:

SPI: This protocol is used for certain communications with certain breakout boards and shields. For example, the ethernet shield uses SPI to connect. On the Mega(2560), it is pins 50-53.
I2C: This protocol is also for connecting to external items. It is much slower than SPI, but uses only two pins. On the Mega, it uses pins 20/21.
UART/Serial: UART is a communication method that uses two wires and transmits bytes of data. It is often used to connect to things that don't need extreme amounts of data passed, but need a stable two way connection.

On all standard boards, the main UART is on pins 0 and 1. This is usually connected to a UART to USB chip which is sent to the computer. Note: you should still be able to upload sketches if they act as an output and random on/off won't hurt the device.
The Mega(2560) also has UART on pins 14/15, 16/17, and 18/19.


How to display a number using SevSeg library on 4 digit 7 segment LED display

There are two main types of seven segment display:

Common Anode
Common Cathode

The common refers to the fact that one end of the LEDs within a digit are linked, and need to be connected to either Vcc or GND, depending on the type of the display (see below). The other end of each led (one per segment) is used to switch them on, and it is these that go to the Arduino pins, or LED controller.
Common Anode

The common end is connected to the Vcc line. If you wish to light a segment, then the input pin for that segment needs to be pulled LOW.

Source: Four multiplexed 7-segment COMMON ANODE LED
Common Cathode

The common end is connected to the GND line. If you wish to light a segment, then the input pin for that segment needs to be pulled HIGH.

It sounds as if you have the logic inverted, so the wrong segments are lit, when they should be dark, and vice versa.
Either that, or you need to invert the logic in your code, and for example if you are currently pulling a pin LOW to light up a segment, then you need to change your code to pull the pin HIGH.

Image sources:
Electronics-Tutorials
Common Anode/Cathode 7-segment displays


How to switch program in arduino using android app?

Once I made a sketch to run multiple programs. I wrote a setup and loop function for every different "program", (e.g. setup_p1, setup_p2, ... loop_p1, ...) and then wrote a simple main sketch to handle them all.

In my application I choose the program at startup with a 3-dipswitch, but you can easily switch this to allow "on the fly" switching.

I choose to use a callback because it's faster than just checking the mode every time, at least in my case

// callback for loop function
typedef void (*loopfunction)();
loopfunction currentloop;

void setup()
{
  // Set dip-switch pins as input
  pinMode(MODE_PIN2,INPUT_PULLUP);
  pinMode(MODE_PIN1,INPUT_PULLUP);
  pinMode(MODE_PIN0,INPUT_PULLUP);

  // Concatenate the dip-switch values
  byte mode = 7 - ((digitalRead(MODE_PIN2) << 2) | (digitalRead(MODE_PIN1) << 1) | digitalRead(MODE_PIN0));

  // choose the correct mode
  switch(mode)
  {
    case 0: // Shutdown - do nothing
            break;
    case 1: // Program 1
            setup_p1();
            currentloop = loop_p1;
            break;
    case 2: // Program 2
            setup_p2();
            currentloop = loop_p2;
            break;
    ...
  }

  // Not a valid program: halt
  if (!currentloop)
  {
    while(1);
  }
}

void loop()
{
  // Execute the current loop
  currentloop();
}


Don't do delay() calls inside an ISR. In all probability it will hang indefinitely. If you want to play the tone for a second all you need to do in the ISR is set a flag, which you test in the main loop. Turn the buzzer on when the flag changes state. Remember when you did that. When a second is up turn the buzzer off again.

In fact in your case you probably don't need the interrupt at all. Test for the reed switch change in the main loop as well. Don't overcomplicate it.


This is what's happening: it's still between 8 AM and 5 PM on the weekend, so it unlocks it. Since you use an else if, it terminates the if statement and never checks the day between 8 and 5. I'm almost positive that if you checked it another time in the day, it'd be "locked."

Fixed code:

#include <Time.h>
#define doorPin 9
void setup() {
  // put your setup code here, to run once:
  pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
  setTime(10,1,1,6,7,2014);
}

void loop() {
if ((hour()>=8 && hour()<=17) && !(weekday()==1 || weekday()==7)){
  digitalWrite(doorPin, HIGH);
}
else {
  digitalWrite(doorPin, LOW);
}

Note: ! means "not." Thus, the door is locked only if it's not a weekend and it's between 8 and 5.

Additionally, you might want to get a lock that is the other way around: unlocked only with power applied so someone can't unplug the Arduino to get access. EDIT: miscommunication, ignore this part paragraph...


Since double and float represent the same data type (usually), which is preferable?

See avr-gcc

  Deviations from the Standard

  double

  double is only 32 bits wide and implemented in the same way as float

  when writing code for ATMega based boards ...

They are the same, therefore.

(Edited to add)

  When writing code, is it then preferable to using one over the other?

I don't really understand your question. You asked about writing code for the ATMega based boards. Do you really mean, if you are writing code for the Due? The quick answer would be, on the Due, double takes twice the RAM, however it is over twice as precise - around 7.2 decimal digits for float compared to 15.9 for double. (I'm not sure about the speed, probably double would be slower, unless it is implemented in floating-point hardware - however I cannot see any reference to that on the AT91SAM3X8E datasheet).

See: https://en.wikipedia.org/wiki/Floating_point

If you want more precision (however slower and taking more RAM) then you could use double - which won't make any difference on the ATmega based boards, but will on the Due.

As Edgar Bonet said:

  I would use float so that anyone reading my code, who may not know about the non-standard AVR double, knows what precision to expect.

That makes quite a bit of sense.

I warn you though that "preferable" is subjective. It is close to asking "what is best"? To which the reply is: "best for what?"


I2C_anything from Nick Gammon. Value of two senders to be received and printed by receiverslave

Dear Chrisl and Sim Son
Please accept my apologies for not replying earlier, am still recovering form a timbering accident and have limited painless access to my laptop.
thinking in boxes: BOX 1 = Arduino Mega number one regulates the pressure of proportional valves (via I2C conected quaddac MCP4728 to 0-10V) based on the flowvalues of 4 I2C-connected FLowsensors.
BOX 2= Arduino Mega number two does the same with a second set of 4 flowsensors and 4 analog proportional valves.
Splitting this to two arduinos was originally because a) i was unable figure out how to get 2 DACS on the same I2C line and handle the LDAC address fiddling which turned out to be a good approach because the total number of required GPIO pins exceeds the available number of pins of one Mega (many rotary encoders attached, TTL signal delayer for 8 channels, pots to set values, status LEDS.
Both arduinos are supposed to send the values for the flow-setpoints, actual pressure values, actual flow values, other sensor data to a third arduino MEGA =BOX 3 that displays all kind of things on a large TFT. (for what its worth, this third Mega has some inputs from a different set of other I2C sensors that basically provide TTL signal outputs, if event-criteria have been met. the latter TTL are fed back to the first two arduinos to provide decision criteria in if loops)
So, i learn from you that the multimaster approach unlikely to be fun at all, especially given my limited knowledge and loathing /ignorance to handle and send strings. You will at least laugh at me now but i saved quite some time the on day i wrote to you by simply translating all the flow etc values of BOX 1, Box 2-Ardinos (pressures, flowsetpoints and actual flow values into voltages with the help of additional multiplexed DACs, then I pick up the the voltages with I2C-ADCs hooked to the Arduino with the SPI-display (BOX 3) that in turns translates into the true values and prints to the TFT. Any delay and inprecision at the displays side is acceptable so far, analog value fluctuation has been smoothed, the additional hardware is no issue at this stage of the project.
I am sorry that his original issue regarding I2C led me astray to oldfashioned analog data processing
BUT: if you have any hints or pointers to libraries as how two arduinos that act already as I2C Masters can send their data (a bundle of floats) via UART/RXTX, or any other bus to a receiver that handles these as printable variables: more than welcome, i will try to keep abreast of what you suggest.
Best
Daniel


Uno R3 connected via Ethernet shield becomes unreachable after a few minutes

I don't know where my compiler was finding the UDP code in the above sketch, because it's not in EthernetV2_0.h. The problem was fixed by adding the following lines, from the example sketch UDPSendReceiveString written by Michael Margolis and included with the Ethernet_Shield_W5200 library:

#include <EthernetUdpV2_0.h>

#define SDCARD_CS 4

void setup():
    //...//
    pinMode(SDCARD_CS, OUTPUT);
    digitalWrite(SDCARD_CS, HIGH);


Reading the answer from Gerben I realised the core of the issue: The TX/RX LED's on the Leonardo are wired PIN-LED-5V(common anode), whereas on the Olimexino-32U4 they are wired PIN-LED-GND(common cathode). So the two boards will need inverse signals for the same visual output.

Compare:
http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf
https://www.olimex.com/Products/Duino/AVR/OLIMEXINO-32U4/resources/OLIMEXINO-32U4_rev_A3.pdf

The most elegant solution will be to add a new board type (the code below is for IDE 1.0.x):

In your sketchbook create a folder 'hardware' and inside that 'olimexino'. In the olimexino folder create a file boards.txt with this content:

olimexino32u4.name=Olimexino-32U4
olimexino32u4.upload.protocol=avr109
olimexino32u4.upload.maximum_size=28672
olimexino32u4.upload.speed=57600
olimexino32u4.upload.disable_flushing=true
olimexino32u4.bootloader.low_fuses=0xff
olimexino32u4.bootloader.high_fuses=0xd8
olimexino32u4.bootloader.extended_fuses=0xcb
olimexino32u4.bootloader.path=caterina
olimexino32u4.bootloader.file=Caterina-Leonardo.hex
olimexino32u4.bootloader.unlock_bits=0x3F
olimexino32u4.bootloader.lock_bits=0x2F
olimexino32u4.build.mcu=atmega32u4
olimexino32u4.build.f_cpu=16000000L
olimexino32u4.build.vid=0x2341
olimexino32u4.build.pid=0x8036
olimexino32u4.build.core=arduino:arduino
olimexino32u4.build.variant=olimexino32u4

Create another folder 'variants' inside the olimexino folder.
Inside that, create the folder 'olimexino32u4'.
Now copy 'arduino/hardware/arduino/variants/leonardo/pins_arduino.h' to that folder
Open the copy for editing - the path should be 'sketchbook/hardware/olimexino/variants/olimexino32u4/pins_arduino.h'.
Change the section that deals with TXLED and RXLED by swapping the macros that end in 1 with those that end in 0. It should look like this:

#define TX_RX_LED_INIT  DDRD |= (1<<5), DDRB |= (1<<0)
#define TXLED1          PORTD |= (1<<5)
#define TXLED0          PORTD &= ~(1<<5)
#define RXLED1          PORTB |= (1<<0)
#define RXLED0          PORTB &= ~(1<<0)

I don't own the board so I can't test the solution. I hope that it solves your problem - just choose 'Olimexino-32U4' from the Tools->Board menu.


Not showing output when using pins other than 10 and 11 with SoftwareSerial library on Arduino Mega

From https://www.arduino.cc/en/Reference/softwareSerial:

  Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

So you will need to use one of the pins from that list for RX, pin 4 or 5 will not work.


Arduino IDE COM Port error on Windows 10

An easy thing to try but might not help: Use another USB port of your computer and see if the driver is reinstalled.

Otherwise, go to control panel and find the drivers (Device Manager), search for the Ports (COM & LPT) drivers and remove the driver for the Arduino manually, reconnect the Arduino and check if it is installed correctly. Possibly a wrong version of an Arduino driver is installed. If another driver is installed at COM3 (where is my Arduino), remove that driver and try again.


Sounds like you need a pull-down resistor.

If a CMOS input like and Arudino digital input isn't attached to anything it will "float", bouncing between 1 and 0.

Attach a 10k resistor between the input pin and ground (before the switch). That way, if the switch is off/open, the resistor pulls the input to ground.

If the switch is on/closed, it feeds +5V into the pin, overwhelming the resistor.

(Note that you can instead use a pull-up resistor, and then have the switch connect to ground instead of +5 volts. When you do this the input is reversed {HIGH if the switch is not pressed and LOW if the switch is pressed.} There is an internal pull-up resistor on the digital input pins that you can connect by using the setting INPUT_PULLUP instead of INPUT when you configure the pin with the pinMode() function. That way you don't need an extra resistor.)

Also note that in addition to needed a pull-up or pull-down resistor, you may need to debounce your switch. You can do this by writing your code that detects switch presses to ignore changes for 100 ms or so. This avoids the rapid on/off/on/off jitter you often get from switches as their contacts transition from open to closed (or closed to open.)


Red LED not turning off on Adafruit Circuit Playground Classic

This appears to be a bug in the Circuit Playground library. An issue was opened here.

https://github.com/adafruit/Adafruit_CircuitPlayground/issues/40

Edit: This indeed was a bug, it is now fixed in the library version 1.8.4.


How to make data sent by Python (via serial connection) wait for Arduino to finish current task?

If I'm getting things right, your program fails in the above:

  when you send the first message in python, you set state = 0. In
  arduino you enter the serialEvent function and while is triggered. You
  get the first char and send it through Serial.print (but this char
  will be send to python!!!). For the sake of example let's say the
  first char you get from cvs is '2'. At this point let's hold on a
  sec and look what happens in python. State was '0' but as you have
  used in arduino Serial.print(ch); now state will be updated with
  '2'. This will cause no more triggers of the if-else statements in
  python.

  edit:

  By now, and also as a debug, add this lines at your code:

if state == '0': # Wait for Arduino to be ready
    state = ser.read()
    if state != '1':
        print "state: " + state
        state = '0'

  However if csv file contains '1's values this will also cause a
  problem. Do you really need that Serial.print(ch) in arduino?

EDIT The new version since comments
Basically if you are trying to do things before new coordinates, you have to do things in a sequential way. You only ask for info after making all the moves. This is the code I've used to test.
Note: I had to adapt your code because was missing the complete arduino code to test it. So I kinda simulated the motor moving etc with delays. Please adapt to your original code

#include <string.h>

bool coord_complete = false;
byte stepper1_disToGo = 0, stepper2_disToGo = 0;
// debug things
int led = 13;
bool led_state = true, x_complete, y_complete;
char coord_string[256];
int index = 0, x_new = 0, y_new = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  memset(&coord_string, 0, sizeof(coord_string));
}

void loop() {

  serialData(); //ask and process more data

  /*
    // Steps to move from currrent to new point
    target1 = steps(x_current, y_current, x_new, y_new, 1);
    target2 = steps(x_current, y_current, x_new, y_new, 2);

    // Start moving
    stepper1.move(target1);
    stepper2.move(target2);

    // Update current position
    x_current = x_new;
    y_current = y_new;

    // Reset variables
    x_complete = false;
    y_complete = false;
  */
  delay(2000); //replace to simulate actions
  stepper1_disToGo = 10;
  stepper2_disToGo = 10;
  coord_complete = false;

  // replaced to simulate
  /*
    // Stay in while loop until steppermotors is done
    while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
    }
  */
  while ((stepper1_disToGo != 0) || (stepper2_disToGo != 0)) {
    stepper1_disToGo --;
    stepper2_disToGo --;
    digitalWrite(led, led_state); // is moving!!!!
    delay(100);
    led_state = !led_state;
  }
}

/*
   you try to use the serialEvent  but the structure of
   your code and the verifications make it act like sequential.
   If you only want to make things after all steps are done there
   is no need for the serialEvent function
*/
void serialData() {
  /*
     This will never be false because you are stuck in the while

    // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
    if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
    Serial.write('1'); // Tell Python that Arduino is ready for one more line
    }
  */
  //EDIT: wait for info
  while (Serial.available() < 1) {
    Serial.write('1'); /// Tell Python that Arduino is ready for one more line
    delay(500);// ask for info sometimes
  }
  while (Serial.available()) {
    char ch = Serial.read(); // Get new character

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

      // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;                   // Finish coord_string
      x_new = atoi(coord_string);                     // Convert to integer
      x_complete = true;                              // Change x_complete to true
      index = 0;                                      // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

      // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }
    //EDIT: change to AND verification
    // Ends while-loop when true
    coord_complete = x_complete && y_complete;
  }
}

The structure of your loop should be:

ask for data and wait for it
Read data and parse it
Calculate steps needed
move servos till new positions
repeat

this should be your new code more or less if no mistakes were made because can't really test this version (is missing the variables declarations setup, includes etc...)

void loop() {

  serialData(); //ask and process more data
  // Steps to move from currrent to new point
  target1 = steps(x_current, y_current, x_new, y_new, 1);
  target2 = steps(x_current, y_current, x_new, y_new, 2);

  // Start moving
  stepper1.move(target1);
  stepper2.move(target2);

  // Update current position
  x_current = x_new;
  y_current = y_new;

  // Reset variables
  x_complete = false;
  y_complete = false;
  coord_complete = false;

  // Stay in while loop until steppermotors is done
  while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
  }
}

void serialData() {

  //EDIT: wait for info
  while (Serial.available() < 1) {
    Serial.write('1'); /// Tell Python that Arduino is ready for one more line
    delay(500);// ask for info sometimes
  }
  // we got info!!!
  while (Serial.available()) {
    char ch = Serial.read(); // Get new character

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

      // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;                   // Finish coord_string
      x_new = atoi(coord_string);                     // Convert to integer
      x_complete = true;                              // Change x_complete to true
      index = 0;                                      // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

      // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }
    //EDIT: change to AND verification
    // Ends while-loop when true
    coord_complete = x_complete && y_complete;
  }
}


Why does my LCD display random characters?

It could be because "millis()/1000" generates a "number", and not the "string" (or "char"). Try to add ",DEC" in your lcd.print(), something like "millis()/1000,DEC" to convert it to "decimal". Generally, it depends on the library, how they implement this function.

Good luck,

Mike


Unless you share a schematic, it will be very difficult to provide a good answer.

Here are the things that you might be doing wrong:

1) Using a power supply which is not able to provide enough current to the relay.

2) Using a power supply of wrong voltage as required by relay coil. The relay might be needing 12 V and you might be trying to power it up with a 5 V power supply.

3) You might be trying to drive the relay directly with your GPIO pin (without using any external transistor switch).

4) Trying to raise a dead relay. There is a possibility that the relay is damaged. Check it by powering it up directly using a battery or another adequate power supply that you got.


ESP8266-12E and MCP23017 , unable to identify the application

You have an MCP23017 which connects to the device using the I2C protocol, which means you need the  library.  You also need to ensure that SCL and SDA are 'pulled up' using 4.7Kohm resistors between the data lines and the +ve line.
You will then need to send commands to the device to initialise it and set the pins to OUTPUT.  (See http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf).

When running you will need to update the state of this pins by sending messages such as  0x09 0xFF to turn them all on.

It is going to be worth looking for a library that already does all this, but writing your own shouldn't be too hard.  You will be able to use an Arduino library on an ESP8266.

These chips are the easiest ones to use and learn about I2C, so its worth looking at the manual and trying to write your own "library" (Just start by writing a C++ class within your sketch folder.)


Those delays are nonsense. They don't add to the stability of anything. The best you could say is that they stop you spamming your serial port. (However 1 ms is not very long).

Sometimes people throw in a delay because "it seems to work better" without examining the underlying cause. I would speculate that in this case the author may have been using delays to improve receiving serial data, and got the idea into their head that the occasional delay now and then "improves stability".


does eeprom_write_block function of avr.eeprom.h writes a NULL terminated string or we have to manually null terminate it

Since one normally does not know how long a character string is, we need a way to convey this information.  One technique used to avoid confusion is to add a NULL character (which is a zero) to the end of the string.  Another is to explicitly state how long the string is.

In the case of the function eeprom_write_block() talked about here, we see that we are formally passing not only a pointer to the string but also the size of the string.


Arduino to read from RS232 converter to TTL serial module (updated)

You need to disconnect the Arduino`s RX and TX pins from any device before trying to upload a sketch via USB, because the Serial data is directly wired from the USB chip to these pins. It's as if you're trying to flash the thing behind your RS232 adapter.


Output 20x20 Image to Arduino serial monitor

The Arduino IDE's serial monitor is, to put it bluntly, awful.

Switch to a proper ANSI compatible serial terminal emulator (Tera Term, Putty, Minicom, whatever) and use ANSI control sequences to manipulate the screen.

The simplest ones to use are:

Serial.print("\e[2J"); // Clear the screen
Serial.print("\e[1;1H"); // Move the cursor to coordinate (1,1)

Use the first one to clear the screen in setup(), then use the second one at the start of the loop to move to the top-left corner of the screen (1,1 is top left - the coordinates are given as Y;X not X;Y and start from 1 not 0).

Print your 20 lines of 20 characters as either space (nothing) or your chosen "pixel" character.  The spaces overwrite the existing characters to help reduce flicker (clearing the screen every time would be just awful).

The way serial works (sending one character at a time sequentially) there is no such thing as "All at once". The above is the best you can get without writing your own program to interpret incoming serial data representing an image frame and displaying it.


What is an easy way to power a 3.3v BMP-180 barometer board from a 5v Arduino Nano?

Here is the solution I settled on:  a small part that will step 5 volts down to 3.3 volts.  The price is right, but it will be shipped by the slow boat so will take a month or so to receive.

5Pcs 5V to 3.3V DC-DC Step-Down Power Supply Buck Module AMS1117 LDO 800MA

http://www.ebay.com/itm/5Pcs-5V-to-3-3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-LDO-800MA-/261983164332

It has 3 pins - Vin, Vout, GND.    Easy to hook up.

Upvote to everybody for the discussion.


project not working when switching to battery power

You may find that, with a high load on batteries, it's depleting the battery quickly; batteries often recover after a while, which may be confusing things further. Try using a multimeter to measure the voltage on the battery, when your program is running.

The Arduino (actually, the chip that runs the Arduino) has brown-out detection - if the voltage drops below a certain level, the Arduino will shut down; if the power comes back up, the Arduino will start up again - but reset. The chip has settings for 1.8v, 2.7v, and 4.3v brownout detection (or none at all!); something I read on the interweb (if you can trust that) said the default was 4.3v. It may be worth flashing an led on startup, so you can tell when the chip is reset.

Also, if you are powering the Arduino through the voltage regulator (using the power socket on the Arduino), then you need about 6-7 volt in just to get 5 volt at the Arduino - this causes further power loss. If using 4 AA batteries through the voltage regulator, you will get 6 volts (probably a little more when the batteries are fresh) going into the regulator - barely or not quite enough! - and the voltage on the Arduino is likely to be below the 5v it needs. Any load (in one of my projects, two large 7-segment displays) can cause the voltage to drop enough to trigger a reset. If you are using the voltage regulator, check the voltage between the 5V and GND pins.


ESP8266 malloc/calloc-related crashes ("segfaults")

You wrote:

// funkiest malloc in the world

Funky, indeed. ;-) I kind of like its twisted beauty, but not everyone
does. Some may urge you to typedef that function type.

allClockFaces[4] = &fullDayBinaryCF;

Are you sure DESIGN_MENU_SIZE is strictly larger than 4? Maybe an
assert() would be good to use here.

ClockFaceSelectMenu* cfMenu = (ClockFaceSelectMenu*) malloc(...);
cfMenu = new ClockFaceSelectMenu(...);

You are assigning a value to cfMenu twice in a row, which means the
value assigned first is lost. This is a memory leak. You do not need
malloc() here, as new takes care of the memory allocation prior to
initializing the object. This error is repeated several times in this
function.

allMenus[3] = tzMenu;

allMenus has length 3: valid indices range from 0 to 2. This is an
out-of-bounds array access, and the likely cause of the errors you see.


Why can't my .cpp file have a class of the same name?

#define XYZ

class XYZ { };

The first line tells the "C preprocessor" (called before C and C++ compilers) to replace XYZ with nothing everywhere it happens, hence after preprocessing, and before compiling, that code becomes:

#define XYZ

class  { };

This is where C++ compiler complains. It has nothing to do with your file name.

Among C and C++ programmers, it is commonly admitted that header files should be protected by macros named after the file name including the extension:

#ifndef XYZ_H
#define XYZ_H

If you use this practice, you won't have this problem anymore.


You need to set the ports to output first, before you can use them.

To do that you use the DDRx (Data Direction) registers.  Your code should look like:

//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
    // Set the pins all to output
    DDRA = 0xFF;
    DDRC = 0xFF;
    DDRD = 0xFF;

    PORTA =  B0000000; //29--->22
    PORTC =  B0000000; //37--->30
    PORTD =  B0000000; //45--->38
}

void loop(){
    PORTA =  B1000100;
    PORTC =  B0101000;
    PORTD =  B0000010;
    delay(1000);

    PORTA =  B1010000;
    PORTC =  B0001010;
    PORTD =  B0100000;
    delay(1000);

    PORTA =  B0010100;
    PORTC =  B0100010;
    PORTD =  B0001000;
    delay(1000);
}

You can read more about direct port manipulation here.


The teensy series from pjrc.com allows USB MIDI natively (full USB speed!).  It works well and does not require any firmware tomfoolery.  It can also do HID keyboard/mouse/joystick natively as well.

There's the 2.0, which is 32u4, and the 2.0++ which has more pins and memory.  If you want to step off the Atmel reservation the teensy 3.0 and 3.1 have more speed and memory; in a couple of weeks they are coming out with a Teensy LC which is a 3 with less bells and whistles for cheaper.


It's quite simple: You don't.

Instead you use your initial ISR to configure and enable one of the ATMega's Timer peripherals. Set that to the length of your required delay - then the ISR exists.

When the chosen time has passed the timer interrupt triggers, and you use that interrupt to turn on your output.


How to use a 4-pin ultrasonic sensor as a 3-pin ping sensor?

The four pin Echo))) module is basically the same as three pin ones, except for triggering is done by another pin. So you don't have to care about setting pin to the output mode and switching it back to the input mode after the trigger pulse. You can read about it for example here.

const int8_t pingPin = A0;
const int8_t trigPin = A1;

void setup()
{
  pinMode(pingPin, INPUT);
  pinMode(trigPin, OUTPUT);
}

void loop()
{
  // pulse on trigger pin:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // 10us is minimum trigger pulse duration
  digitalWrite(trigPin, LOW);

  // measure HIGH pulse duration:
  long duration = pulseIn(pingPin, HIGH);

  // and rest of the code:
  long   inches = microsecondsToInches(duration);
  long       cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}


Problem with powering ublox NEO-6M GPS module

The module may very well be dead now, due to giving it 5V.

But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought.

A window means that at least 50% of the sky is blocked by the building. The module might not be able to get a signal from enough satellites for a cold start.
A voltage divider only works if there is constant current. As you've noted, you just created an unstable power supply.
The datasheet says 27 s but that is probably with a clear view of the sky.
Next to the 5V pin on the Uno is a 3.3V pin. How about using that?
Visually, no. But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not.


Has pt.h library been removed from arduino?

pt.h has never, and will never, be part of the Arduino core distribution.  It is a completely separate third party library that you have to install yourself.

I think the library you want is this one.


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

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


First, you have to understand what “hex” means. Basically, you are
representing binary data as text, where each byte is represented as
two characters. For example, the number 42 is represented as either “2A”
or “2a”. In C and C++, you can write this number as 0x2a, but I assume
your serial stream sends the raw hex data, without the “0x” prefix.
Thus, on the serial stream you may receive the character “2” (character
code 0x32 = 50 in decimal) followed, some time later, by “a” (charcode
0x61 = 97).

What you need is a conversion routine that takes these characters and
reconstructs the binary data out of them. Here is one such routine I
use. You have to provide it with an input string in and an output
array out large enough to store the resulting binary data. The
function will return the number of bytes filled in *size:

/*
 * Convert an hex string to binary. Spaces are allowed between bytes.
 * The output array is supposed to be large enough.
 * On return, *size is the size of the byte array.
 */
static void hex2bin(uint8_t *out, const char *in, size_t *size)
{
    size_t sz = 0;
    while (*in) {
        while (*in == ' ') in++;  // skip spaces
        if (!*in) break;
        uint8_t c = *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
        in++;
        c <<= 4;
        if (!*in) break;
        c |= *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
        in++;
        *out++ = c;
        sz++;
    }
    *size = sz;
}

As a mere convenience, the function above accepts spaces within the
string, but only between bytes. Notice however that it does not attempt
to do any error checking. You may want to improve it in this respect.

Next, you have to devise a way to frame your messages on the serial
line. Serial does not provide any framing per se: it only transmits byte
one by one. When dealing with text, a common scheme is to send a
carriage return (\r) to indicate the end of a message. With this
convention, you sketch has to buffer the bytes it receives until it
sees a carriage return. Then it can process the whole message as a
whole. This approach is nicely explained in the blog post Reading
Serial on the
Arduino,
by Majenko, a regular contributor to this site.

Here is an example that reads an hex string, converts it to binary, and
then sends it back as hex again:

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

void loop()
{
    static char buffer[1024];
    static size_t length = 0;

    if (Serial.available()) {
        char c = Serial.read();

        // On carriage return, process the received data.
        if (c == '\r') {
            Serial.println();  // echo

            // Properly terminate the string.
            buffer[length] = '\0';

            // Convert the hex data to a byte array.
            size_t byte_count = length/2;
            uint8_t data[byte_count];
            hex2bin(data, buffer, &byte_count);

            // Echo back the byte array in hex.
            for (size_t i = 0; i < byte_count; i++) {
                Serial.print(data[i], HEX);
                Serial.print(" ");
            }
            Serial.println();

            // Reset the buffer for next line.
            length = 0;
        }

        // Otherwise buffer the incoming byte.
        else if (length < sizeof buffer - 1) {
            Serial.write(c);  // echo
            buffer[length++] = c;
        }
    }
}

Notice the lines with the comment “echo”: they are meant to help you see
in the terminal what you are typing. You can remove them if you do not
what the Arduino to echo your typing. I tested it by sending

AA bb06 000000 0101 03 03

and it replied

AA BB 6 0 0 0 1 1 3 3


On my page about the ADC converter I attempted to record a 4 kHz sine wave on the ATmega328P with the following code:

const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

The code (rather inefficiently) sends the results in ASCII, like this:

378
710
899
992
966
827
609
367
159
38
35
147
350
593
817
965
1001
917
733
494
259
88
21
76
239
471
711
905
1001
977
839
620
376
164
39

This gave reasonable results:

Now the Leonardo is, of course, a different processor. However it is similar. The ADC on it should be capable of similar performance.

I should point out that this code records first, then sends the data. This is so the recording can keep up. A normal ADC conversion (if you don't change the ADC prescaler) takes 104 µs. To send 10 bits via serial at 115200 baud rate would take 173.6 µs because it would require two bytes per sample (unless you somehow compress each reading). If you could put up with 8-bit resolution (per sample) then you halve that, and can probably just stream the data out fast enough.


Of your three functions (DAC, screen and MIDI) only one (MIDI) actually uses UART.

The other two devices are SPI devices which, while it is a serial protocol isn't UART (serial is a concept not a protocol).

Connect the DAC and screen to the SPI port (you can share SCK, MOSI and MISO, but select different CS pins) and you have the UART pins (0/1) available for MIDI use - as long as you don't want to use the USB connection which is linked directly to those pins.


Reducing Clock Speed increases sketch size?

Does your code have delays in it? If you changed the clock speed, then the compiled assembly for the delays may require more NOP instructions or something similar to achieve the same real-time delay. As a result, the size of the compiled sketch could increase.


As Majenko wrote: the Arduino Yún = Leonardo + Yún shield. You get into a lot of trouble with the Arduino Uno, and the Yún shield has already enough troubles on its own.

Maybe the Arduino Mega 2560 can be used when both the hardware and software is changed to use another hardware serial port for the Yún shield. If you start with the Yún shield, then use the Leonardo. Don't even try the Arduino Uno.

It is possible to upload a sketch via Ethernet or WiFi, but that often fails. Therefor you need the usb-serial connection to the computer to upload a sketch.

Even when you use a Arduino Leonardo, the communication between the Yún shield and the Arduino board (the 'Bridge') can cause troubles. In OpenWRT a Python script is used to read the serial data from the 'Bridge', which causes a lot of CPU usage.

The Yún shield is not fully compatible with the Arduino Yún. I think a few GPIO pins are different and maybe some other things. That means you are stuck to the firmware of the Yún shield, which can have issues and is not fully compatible with the Arduino Yún firmware.

When installing software in OpenWRT, the rootfs is filled quickly. You can type df or df -h to see the disk usage. I have read about ways to add a SD memory card or a USB flash drive to the rootfs. I have not tried that because I want OpenWRT to run even without a SD memory or USB drive.

An SD memory or USB drive can be used to store a website on it, or scripts, or music files, and so on.

When you need more memory, you might want to try the Raspberry Pi. The Raspberry Pi Zero W is very cheap and has WiFi.


3-instruction remote machine coding Arduino Atmel chip over a serial line from a tethered (host) PC

The AVR CPU cannot execute instructions from RAM. It's not a question of what the compiler can do or should be able to do, the physical chip itself cannot do it. There is simply no physical pathway between the RAM and the instruction decoder in the CPU.
Instructions can only be executed directly from Flash memory. That is how the chip works. You can only execute code that you send over serial if you first erase a page (or more) of Flash memory then burn the incoming code into that page. You can then call the start of that page's address and your code will execute.
But there is another caveat there: only code running in the bootloader flash area is allowed to modify the flash memory. That means your code can't do it, only the bootloader. That doesn't mean that the bootloader has to be running, but the code that you execute has to reside there.
There is an alternative version of the Optiboot bootloader that can provide flash writing facilities to a user program, but I have no experience using it so can't assist with that.


Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.”

Your transmitter and receiver pins need to be crossed, rx->tx and tx->rx. As a mnemonic, the two ends of the antenna point to the board edge with the receiver pin and it is that pin that needs the voltage divider. While you're at it, it would be a good idea to tie the RST pin high, as well as the CH_PD. I use one 10K pullup for both.

Recent versions of these boards are shipped with their baud rates set to 115200. Since you're using a hardware UART on the Mega board, you can send/receive to it at that rate.

Note to readers using a software UART (SoftwareSerial): First thing, change the board's baud rate to 9600 and communicate with it at that rate. You can use SoftwareSerial to make the change as it sends at 115200 reasonably reliably, but its receive function can't keep up at that rate).

You can confirm your connections and baud rate with:
EspSerial.println("AT");
You should receive `OK' in reply.


Using only Rx pin to receive data from HC 05 and attiny85 (Arduino IDE)

I suggest you get rid of SoftwareSerial and use instead this Simple
ATtiny USI UART. This is a driver
for a receive-only UART that uses the USI port of the ATtiny85. It is
superior to a software-only UART as it makes good use of the hardware,
leaving more time for the CPU to do more useful things (or sleep and
save battery). Also, unlike SoftwareSerial, it does not need to block
interrupts for long periods, which is a good thing.


Get ESP32 Chip ID into a string variable (Arduino/C++ newbie here)

You can combine all your work into one single line with the snprintf. You aren't limited to just one variable, and you can add plain text:

char ssid[23];

snprintf(ssid, 23, "MCUDEVICE-%04X%08X", chip, (uint32_t)chipid);


There's a couple of things I would try.

First: Don't use the native Arduino TX/RX pins, they should be left alone to talk to the computer. Use SoftwareSerial instead in start a separate serial connection.

Second: Check that Arduino TX pin (that you declared in softwareSerial) is connected to the BC127 RX and vice versa. Unlike just about every other connection in electronics, serial connections need to have their pins reversed so that TX talks to RX. It's an easy mistake to make and one I've made when not paying attention to what I was doing.

Third: Flow control.

If the BC127 sends data when the Arduino isn't listening the data could be lost, to prevent this the BC127 won't send until the Arduino signals it is ready through flow control.
See the BC127 datasheet page 8, pins 40 and 43. Trying tying UART_CTS to 3V3 and UART_RTS to Ground. That should cause the BC127 to be in a constant 'send' state.

Lastly I'd hook up a couple of LEDs to pins 37 and 38. They should give you some sort of status indication that could be useful in debugging future problems.


Can I fix it?

If your power supply still works, there's a decent chance you can repair the board by replacing its microcontroller which is conveniently socketed.


How to split a string into substring Arduino

Import the string.h library by adding #include <string.h> on top of your sketch, in order to use the strtok() function.
Checkout the usage example of strtok() here: http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok


Arduino LED lighting up when signal is reading low on multimeter

You left pin 3 floating. The multimeter will lower the voltage, resulting the the led lighting. Try enabling the pull-up resistor in pin 3 by adding pinMode(3, INPUT_PULLUP).

PS you might want to add a resistor in series with that led, or it will burn out and/or damage pin 3 on the arduino.


Using external reset to trigger radio receipt

No gotchas I can think of, except for the fact that the ATtiny's memory
will be re-initialized every time you reset it. But I assume you are
aware of that.

Note that, if you want some data to be preserved across a reset, it is
possible using either the on-chip EEPROM or the .noinit
section of the RAM.