using multiple hc-05 with one arduino mega please anyone help me build my project, i want to connect multiple smart phones to arduino mega using blutooth module hc-05 , I am working on real life home automation project and i don't have idea that can i use 4 Bluetooth modules with arduino mega . Requirement is max 4 smart phone connect to system , please anyone knowing about arduino please help ,i will be grateful . if u have any other suggestions tell me .

HC-05 modules use Serial (UART) for communication with the Arduino. Thus you need 4 Serial interfaces for 4 HC-05 modules. The Arduino Mega has 4 hardware Serial interfaces, so just connect once HC-05 to each Serial interface. Then handle each module in your code the same just with a different Serial interface. If you already know, how to use one HC-05, then it should be rather easy to implement the same with all 4 modules.


External (pin change) interrupt and power consumption I want to write a lipoly powered arduino device that can be launched from sleep mode by pressing a certain key that is connected to ground. Usually, when no in sleep mode I enable the internal pull-up resistor for a definite level. But when in sleep mode, I assume this would drain to much power and hence I want to avoid it. Is it sufficient to just wait for a pin-change interrupt on the same port pin without the internal or an additional external pull-up resistor?

You must not leave CMOS inputs floating. This will increase power consumption, and as a worst result may damage the device. Use an external pull-up if you feel that the internal pull-up passes too much current.


seperate ATmega 2560 - turn on a single LED - troubleshooting I have got my own PCB with "some stuff" on it and first I want to make it run a simple "turn on LED".

My setup:

Atmega 2560
LED connected to PE4 (D2 in Arduino language) => PE4 - LED - 1K resistor - 5V
ceramic resonator (CSTCE16M0V53-R0 16MHZ) connected to XTAL1 + XTAL2 with 1MOhm resistor inbetween
all VINs are pulled to GND with capacitors

Upload is working through ICSP (MISO, MOSI, SCK, RESET, 5V, GND) with an USBasp

Here is my Arduino sketch, which I upload through the Arduino software:

void setup() {
  pinMode(2, OUTPUT);
}

void loop() {
  digitalWrite(2, LOW);
}

I checked the fuses on the atmega as well:

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (H:FD, E:D8, L:FF)

avrdude uploads successfully: (output truncated!)

avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.01s
avrdude: Device signature = 0x1e9801
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: writing flash (1518 bytes):
Writing | ################################################## | 100% 5.47s
avrdude: 1518 bytes of flash written
avrdude: reading on-chip flash data:
Reading | ################################################## | 100% 3.45s
avrdude: verifying ...
avrdude: 1518 bytes of flash verified

avrdude done.  Thank you.

Problem: the LED doesn't work. It is OFF all the time.

Any ideas why it is not working?

Cheers
Hendrik

You are saying that the LED lights if you write LOW to it.

  I need to pull the output pin to LOW to make the LED work

That's exactly what you expect.

Since the other end of the LED is wired to +5 V, then you need to drive the pin low to have a voltage difference over the LED, and for it to light.

  I double checked the Atmega and it is a ATmega2560V, which is rated for 8Mhz. Any chance to fix this with the existing PCB? Change the Fuses to use the internal clock?

Yes, I suggest you do that.

Look at Engbedded Atmel AVR® Fuse Calculator to see what to set them to. I suggest the internal 8 MHz oscillator.


Are pins 0 and 1 (Rx and Tx) parallel with the USB jack? Can I connect another USB jack th 0 and 1 and use it to upload sketches? I have a compact weatherproof enclosure and the onboard USB jack of my Mega is close to the edge. I didn't want to add a bulky weatherproof USB jack, so I'd like to just leave a female USB pigtail loose inside the enclosure.

The only thing is, I want to avoid the extra assembly step of soldering leads directly to the lugs on the board. I'd like to make a shield instead, with screw lug headers to attach all my wires to. That way a lot of my connections can be solderless and the assembly tech can just plug in the shield.

Can I connect the four wires of a USB cable to the header pins? I suspect I'd use Vin, GND, pin 0 and pin 1, but I'm not 100% sure. Thanks for your advice, gentlemen.

No. For many reasons. No. USB is not TTL. You need an adapter to connect rx/tx pins of arduino to USB. And the on-board adapter has the DTR line connected to reset the Atmega before writing a program into it. Without it, you would need to push the reset button in the right moment.


Reading and Writing to a JSON File on the Desktop from Arduino? I'm fairly new to Arduino. I'm working on a project where I'm making HTTP requests using a python code and this lets me read and write to a JSON file on my desktop. I have an Arduino with sensors that records values and I want to take those recorded values and update them to the JSON file on my desktop in real-time. I looked online and many suggested using some Arduino library, but it was only for reading. I'm still confused about reading and writing to the JSON file on my desktop. I appreciate any help to guide me in the right direction. Thank you.

The Arduino cannot access files on a desktop computer.
However you can write software on your computer (you already use Python, so why not use that?) to accept information over Serial, process it, and store it in any way you like (including JSON), or return data from the computer to the Arduino if needed.


I have built a battery level indicator and have tested with a 12V battery Would it harm my arduino board if I connect a 48V battery? I am a newbie and have followed a tutorial to build a battery level indicator as below

Please suggest any changes I'll need to make to make the circuit useful with a 48V battery as the above circuit is tested with a 12V one.
Thank You.

You have a voltage divider there, which would give (if the pre-set pot was set to the maximum):

Vout = (Vin * R2) / (R1 + R2)
Vout = (12 * 10000) / (100000 + 10000)
Vout = 1.09

Thus a 12V battery would present 1.09V at the analog input.

This same wiring would seem to be in range for a 48V battery:

Vout = (48 * 10000) / (100000 + 10000)
Vout = 4.36

Since the analog input can handle up to 5V, then that should be OK. However I would test the voltage divider output first with a multimeter to make sure it doesn't exceed 5V - before connecting it to the Arduino.

You would probably need to change the code to test for different ranges of input voltages, other than what is used for the 12V battery.


Arduino sound equalizer I'm trying to build a led equalizer using arduino and I want to light up with the frequencies.

And I need a little help on how I should do it cause Im a beginner.

Should I use pulsein() or analogin pin to measure the freqeuencies?

The input will be an audio cable.

Use a MSGEQ7. This IC is a "Seven Band Graphic Equalizer".

Here is its datasheet:

https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf

This method is more efficient, accurate and easier then pulsein() or analogRead(). The IC is fairly cheap and there are many libraries for it.

https://github.com/NicoHood/MSGEQ7

Here is a nice project that I found and that uses that IC. It can be a good souce of inspiration for both your code and your electronics.

https://www.youtube.com/watch?v=InrQvtUuS2w


LED Programme where it delays the amount written in the Serial Monitor I have written a simple code to delay the blinking of LED 13, the delay time is set by us.I have incurred a problem when I enter a 2 digit value in the serial monitor.There is some problem with the ASCII. Is there a way to solve this problem without using Serial.parseInt().

void setup()
{
  Serial.begin(9600);
  Serial.println("Programming is starting");
  pinMode(13,OUTPUT);
}

void loop()
{
  if(Serial.available())
  {
    int val=Serial.read();
    int val1=val-'0';
    Serial.println(val1);
    digitalWrite(13,HIGH);
    delay(val1*1000);
    digitalWrite(13,LOW);
  }
}

Here you have.

No error checking. Anything not digit produce zero as output.

void setup()
{
    Serial.begin(9600);
    Serial.println("Programming is starting");
    pinMode(13,OUTPUT);
}

void loop()
{
    static int value = 0;

    while(Serial.available() > 0) {
        int c = Serial.read();

        if(isDigit(c)) {
            value = value * 10 + (c - '0');
        } else {
            Serial.println(value);
            digitalWrite(13,HIGH);
            delay(value*1000);
            digitalWrite(13,LOW);
            value = 0;
        }
    }

It convert chars to values as they are being readed, one by one. There are no size limit for the input string, other that final value must fit in an int

You write a value in the Serial Monitor and end it with return, space bar or whatever non digit key you want.


Controlling a 5m LED strip with a Nano or Uno I'm wanting to control a 12V LED strip (5m, 60 LEDs per meter) with a Nano or Uno. I know from Adafruit that I'll need some power transistors but I'm not sure that I have the right type. I have 6 transistors labelled 30N06L, and I'm hoping they're equivalent to the ones used. Are mine ok to use, or do I need to buy others?

You have a lot of LEDs that you need to power so lets run through the calculations. Assuming that they are RGB LED strips, ie 3 LEDs per physical LED:

5 x 60 x 3 = 900 LEDs

Assuming each has a current draw of 20mA, that is (900 x 20mA) 18A of total current if all are on at the same time at full brightness.

Since each colour will be controlled by its own FET, each FET will be required to drive 6A at full brightness.

The FET that you have is a Fairchild FQP30N06L 60V LOGIC N-Channel MOSFET that can drive up to 32A. Of course, that would need a large heatsink at that current.

If you plan to have any of the colours on at full brightness for extended periods I would recommend putting a heat sink on the tab to help dissipate the heat.

The Arduino Uno/Nano uses a 328P microcontroller at 5V which, according to the datasheet, is suitable to drive the FET.

These FETs should do the job.


How to make XBee module interrupt/wake arduino What I am trying to do is, to have arduino in low power mode and waking up only when a packet is received and is available to be read from the buffer.

A scenario : Zigbee XBee module is not receiving anything, arduino is asleep. Once this particular module receives any data from any other module, it makes the arduino wake up and process this packet.

I've looked almost everywhere possible about this, and people say they do not have a 100% working solution.

Does the XBee module produce a particular output on a specific pin when it receives data? If so, can I connect that pin to the interrupt enabled pin on arduino and with that interrupt arduino or wake it up?
do I need arduino mega for that or is the uno a good enough option?

The pin number 9 and 13 on the Xbee are DTR/RTS used for hardware handshaking. You can connect it to the interrupt pins on the Arduino and program the arduino to wake when the pulse changes. Enable the DTR/RTS feature from X-CTU and it should work. Check this for more information.


How to get code to respond to a certain time from the DS3231 RTC? I am trying to make a program that runs when it gets to five in the afternoon, so 17:00:00.

I am using this DS3231 library, but I can't figure out a way to get it to send "Woooopp" to the serial monitor at the specified time.

On the DS3231, the pin labeled SCL is connected to A5 on the Arduino and the pin labeled SDA is connected to A4 on the Arduino.

SCL -> A5
SDA -> A4

My code:

#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc (SDA, SCL);

void setup() {
  // Setup Serial connection
  Serial.begin(115200);
  // Uncomment the next line if you are using an Arduino Leonardo
  //while (!Serial) {}

  // Initialize the rtc object
  rtc.begin();

  // The following lines can be uncommented to set the date and time
  // rtc.setDOW(SATURDAY);     // Set Day-of-Week to SUNDAY
  // rtc.setTime(19, 48, 50);     // Set the time to 12:00:00 (24hr format)
  // rtc.setDate(3, 6, 2017);   // Set the date to January 1st, 2014
}

void loop() {
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Wait one second before repeating :)

  if (rtc.getTimeStr() == "19:58:12") {
    Serial.println("Woooopp");
  }
  delay (1000);
}

No errors are thrown, however, the code simply does not work.

Any help would be greatly appreciated!

How to get code to respond to a certain time from the DS3231 RTC?

the easiest is to set up the alarm in rtc.

alternatively, keep reading the rtc until the desired time has passed. not terribly efficient.


facing issue with while loop I'm trying to develop one code in which I'm facing issue with while loop. Once I enter any newString it enter in while loop it count till 10 times, when (n>10)  then it is coming out from the while loop.
Facing issues in this part

while (n < 10)
  {
    while (!ret) {
      if ((time + 15) < millis()) {
        ret = dmd.stepMarquee(-1,0);
        time = millis();
      }
    }
     ret = false;
     n++;
    }

I just want when I enter any newString when loop is running it break while loop and start display newString.

Please help me out with this. Thanks for your help, greatly appreciated.

Here is my full code:

#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include "SystemFont5x7.h"
#include "Arial_black_16.h"

//Fire up the DMD library as dmd
#define DISPLAYS_ACROSS 2
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

String inputString = "";
boolean stringComplete = false;
String commandString = "";

void ScanDMD()
{
  dmd.scanDisplayBySPI();
}

void setup()
{
   Serial.begin(9600);
   Serial.println("Arduino Start");
   Timer1.initialize( 5000 );
   Timer1.attachInterrupt( ScanDMD );
   dmd.clearScreen( true );
}

void loop() {

if(stringComplete)
{
  stringComplete = false;
  getCommand();

  if(commandString.equals("STAR"))
  {
   dmd.clearScreen( true );
  }

  else if(commandString.equals("PRSC"))
  {
    String text = getTextToPrint();
    printText(text);
  }
  inputString = "";
}

}

void getCommand()
{
  if(inputString.length()>0)
  {
     commandString = inputString.substring(1,5);
  }
}

String getTextToPrint()
{
  String value = inputString.substring(5,(inputString.length())-2);
  return value;
}

void printText(String text)
{
  char newString[256];
  int sLength = text.length();
  text.toCharArray( newString, sLength+1 );
  dmd.selectFont(System5x7);
  dmd.drawMarquee( newString , sLength , (32*DISPLAYS_ACROSS )-1 ,1);
  unsigned long time;
  boolean ret = false;
  time = millis();
  int n;
  n= 0;
  while (n < 10)
  {
    while (!ret) {
      if ((time + 15) < millis()) {
        ret = dmd.stepMarquee(-1,0);
        time = millis();
      }
    }
     ret = false;
     n++;
    }
}

void serialEvent() {
  while (Serial.available()) {            // get the new byte:
    char inChar = (char)Serial.read();    // add it to the inputString:
    inputString += inChar;                // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

Forget using serialEvent(). It is one of the more stupid things that Arduino implemented.  It is nothing more than a function that gets called (wrapped in a check to Serial.available()) once per iteration of the main loop() function.

It is not really an "event" function at all.

To have anything happen inside your while loop you have to manually implement that thing within your while loop.  Nothing outside of the while loop (with the exception of interrupts) can affect the operation of the while loop.


Run code via NRF24L01+ command "dynamically"? I'm trying to make a home automation setup but I'm having a bit of trouble.

I want to be able to send commands of varying sizes to my arduino, separated by "|" and after receiving it completely it runs code corresponding to the command.

Example:

input "RCP=10001|CMD=D|VAL=120"
would result in an array like:

String cmd[][] = {{"RCP", "10001"}, {"CMD", "D"}, {"VAL", "120"}}

with the amount of 'variables' being... well, variable.

The code would continue checking if the RCP (recipient) ID corresponds with the ID of the current client and then run code based on the following variables.
But I don't think that's important info for the code which separated the string.

This string would be sent through an NRF24L01+ (That code already works)

What you are asking is very tricky at best. Your average Arduino doesn't have enough memory to start storing arrays of Strings.

Instead you will need to "distil" the information as it comes in and store the distilled information.

If the possible keys are all known beforehand then you can assign a number to each possible key - say RCP is 1, CMD is 2, VAL is 3, etc.  If the values are all numeric or can be represented by a number, then convert those to the corresponding number and store those.

Also the Arduino is not good at working with dynamic memory allocations - again because of lack of memory.  If you can decide on a reasonable maximum number of messages to store then you can pre-allocate the memory for them.

For instance it may be good to define a structure which is the content of a message:

struct message {
    uint8_t key;
    uint16_t val;
};

Then make an array of that structure - one slice per possible command, say 10 of them:

struct message messageQueue[10];

That would take a total of 30 bytes in memory - each entry being 3 bytes (1 for the key, two for the value).  Now you can set the keys and values to the correct data as it arrives.

Depending on how you want to deal with the messages as they come in - add them to the end of an existing queue, or always starting the queue from empty every time a new message arrives - you might want to implement a circular buffer.  This is basically how the Serial port on the Arduino works - in involves having two pointers to locations in the array - one where you are writing to, and one where you are reading from. As you write to the array the writing pointer moves along - if it reaches the end it starts from the beginning again.  As you read from the array the reading pointer moves along too.  If the two pointers are together then the array is empty. If the writing pointer would end up where the reading pointer is, the array is full.  Take a look in the Arduino source code (HardwareSerial.cpp) to see how it's implemented.

As for parsing the string as it comes in - if you have it as a single String already then it's a case of looking through it for the | characters and splitting out each portion in turn, then doing the same with each portion looking for the =. Then you can interpret what is in the key/value pairs and decide what to store in the array.


digitalRead not reading input pin of ESP8266-01 I am trying to use a on-off switch with the ESP8266 to change whether GPI02 is HIGH or LOW. I am using GPIO3 as input. My circuit looks like this:

The red area to the right is a relay, I wasn't sure how to make it work in fritzing but I am sure that it is wired correctly, it just has a signal, +, and -, pin. The more important stuff is happening with the ESP8266. First, here is the code:

/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  This example illustrate the cloud part of aREST that makes the board accessible from anywhere
  See the README file for more details.

  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "ew1zard";

// WiFi parameters
const char* ssid = "MaisonBlanche";
const char* password = "7932gLBw";

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Set input / output pin
  pinMode(3, INPUT);
  pinMode(2, OUTPUT);
  //pinMode(2, OUTPUT);
  //digitalWrite(3, 0);

  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id(device_id);
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);

  int read3 = digitalRead(3);
  Serial.println(read3 + " input");
  digitalWrite(2, read3);

}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.println("request from interwebs");
  rest.handle_callback(client, topic, payload, length);

}

The output of the Serial.println is always input (there is no HIGH or LOW or 1 or 0, or whatever it should be, before the input. I have verified that the switch is working. In the on position it is sending 3.3v to GPIO3 (I have measured it with my multimeter) and still the input never changes. In the off position it sends 0v and the ESP8266 just acts as if there is nothing to read it seems. Since I am using this with aREST and you can set the mode of pins through that, I thought maybe I had to set the pinMode with the aREST request cloud.arest.io/xxxxx/mode/3/i and it verifies with a JSON response that the pin is being set to input, but still no reading. Do I not have the ESP8266 wired correctly for this? Maybe I need some pull-ups/pull downs or I can't use the pins in the configuration I am using them? One other thing, when I set the input pin with aREST, it turns on the relay (sending something through GPIO2 for some reason). If I don't set the input with aREST the relay stays off.

UPDATE
I tried with this code to rule out that it might be aREST:

void setup() {
  // put your setup code here, to run once:
  pinMode(3, INPUT);
  pinMode(2, OUTPUT);

  // Start Serial
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  int read3 = digitalRead(3);
  Serial.print(read3);
  Serial.println(" input");
  digitalWrite(2, read3);
}

It always outputs 0 input, the ESP8266 seems to be ignoring that input pin.

UPDATE
I am now trying with GPIO0 as input. I have the switch wired to ground, and it leads to GPIO0. When I turn it on, GPIO0 reads 1 (on), then I use the switch and it turns the relay off correctly, then I try and turn it on again, and nothing happens, GPIO0 continues to be read at 0. So I can't use the switch past the initial off.

The expression read3 + " input" performs pointer arithmetic, i.e. you either add 0 or 1 to the start adress of " input", so you get either " input" or "input". Does the leading space disappear when pressing the button?

To correct your code you can print the number separately:

Serial.print(read3);
Serial.println(" input");

You should get rid of the rest and pub-sub code. You can add this later after having solved the problem with the button.

Also note that GPIO03 uses the same pin as RX. The docs state the following:

Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX).

So it should work after disabling Serial and after providing a pull down resistor. The resistor is needed to prevent having a floating input.


Arduino Cross Correlation? How can I write lightweight cross correlation code for arduino? I couldnt find any solution. The measurement system contains an ultrasonic sensor and a servo  that turns from 45 to 135 degree and measures distance from 4-300 cm. Than i collect data in an array which contains distances with respect to angle. System makes several measurement like this and program finds cross correlation between new and old arrays.

http://www.instructables.com/id/How-To-Make-an-Obstacle-Avoiding-Arduino-Robot/

Given the time scale of the measurements, performance is not an issue.
And since you are not computing in real-time, as the samples are being
measured, you can apply the definition of cross-correlation as is, and
compute it in a double loop. The only difficulty is figuring out that
cross-correlation may not be the proper tool for the job... and finding
the right one! My assumption is that you want to estimate a rotation
angle between the two measurements.

The mathematical definition of cross-correlation assumes infinite
arrays. In practice, cross-correlation is often used to locate a short
pattern inside a long signal. In this case, the computation is done only
for shifts where the pattern completely overlaps the signal. Then the
length of the result is

length(result) = length(signal) − length(pattern) + 1

In your case, since your pattern is a previously measured signal, this
would give a single-sample result, which is useless.

You could instead compute the integral for all shifts where there is
any overlap between the pattern and the signal. This is equivalent to
zero-padding the signal. This has the drawback of biasing the result: if
your signal and pattern are both featureless (positive constants), you
will find a very nice peak at zero shift!

You can remove this bias by subtracting the average from both the signal
and the pattern, and correlating (signal − avg(signal)) with
(pattern − avg(pattern)). This still carries a bias for “big”
features. Imagine for example that, after removing the averages, you
have

pattern = [  0,   0, −20, +20,   0,   0];
signal  = [−50, +50,   0,   0, −20, +20];

You would expect your correlator to find a good match between the
[−20, +20] of the pattern and the [−20, +20] of the signal. The
correlation is, however, much better with the [−50, +50] of the signal.
You may try to alleviate this by computing a normalized
cross-correlation instead, but you will at best make both matches
equally good.

My suggestion is that you completely forget about correlations and
instead think in terms of “goodness of fit”. Correlations are good for
finding scaled and shifted copies of a pattern inside a signal. You are
looking for shifted only copies, with no scaling. Your question should
be: if you shift the pattern by some amount, how well does it fit the
signal? What amount of shift gives the better fit? The canonical answer
to all “goodness of fit” questions is to minimize the RMS difference
between the two: you compute the sum

S = Σ(signal − shifted(pattern))²

Then the RMS difference is

RMS(difference) = √(S/N)

where N is the number of samples involved in the sum. The most likely
shift is the one that minimizes this error. In practice, you do not need
the square root, you just minimize

RMS(difference)² = Σ(signal − shifted(pattern))² / N

You can implement this formula as-is, it's completely straightforward.
Just beware that N depends on the shift, as it's the length of the
overlap. And avoid going to very small overlaps (i.e. large shifts).

Now, if you expand the square inside the sum, you may find that, after
all, this is not so far from a cross-correlation... And BTW, all this
has nothing to do with Arduino.


Arduino Pi-3 Ubuntu MATE not compiling When I try to upload a script to my Genuino Uno from the Linux ARM distro on genuino.cc/downloads it spits out this during compiling.

avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

Has anyone got any ideas?

Thanks,
Caleb

After following the advice left by Majenko, I went to https://www.arduino.cc/en/Guide/Linux and followed the instuctions at the bottom of the page:

If you get an error Error opening serial port ... you need to set serial port permission.

Open Terminal and type:

ls -l /dev/ttyACM*

you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

Now we just need to add our user to the group:

sudo usermod -a -G dialout <username>

where  is your linux user name. You will need to log out and log in again for this change to take effect.


Force compiler to execute instructions sequentially? Is there a way to force the Arduino compiler to compile individual commands sequentially?  Looking at the disassembly, lines of the assembly code for different C/Arduino commands are mixed.  I was thinking something like a dmb or dsb command in ARM assembly.  I realize it's done the way it is for timing optimization, but I would like to see if changing it fixes some other timing issues I'm having.  I'm working on an Arduino Zero.  Thanks!

You can use the optimize function attribute to change the compiler optimization level for an individual function. That's the closest you'll get.

  optimize

  The optimize attribute is used to specify that a function is to be compiled with different optimization options than specified on the command line. Arguments can either be numbers or strings. Numbers are assumed to be an optimization level. Strings that begin with O are assumed to be an optimization option, while other options are assumed to be used with a -f prefix. You can also use the #pragma GCC optimize pragma to set the optimization options that affect more than one function. See Function Specific Option Pragmas, for details about the #pragma GCC optimize pragma.

  This attribute should be used for debugging purposes only. It is not suitable in production code.

E.g.,:

void __attribute__((optimize("O0"))) myFunction() {
    // ...
}


Arduino Pro Micro, get data out of Tx pin? I have a Sparkfun Arduino Pro Micro with an ATmega32u4 on it and a Roving Networks RN32 Bluetooth Module

Theoretically, I should be able to solder the Rx of the Bluetooth to the Tx on the arduino and vice versa and I should get serial communication over the Bluetooth.

Of course, I do not. However, as a first question: How do I get my Arduino to transmit data over the Tx pin?

I uploaded this to the Arduino with no hiccups:

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

void loop(){
  Serial.print("HelloWurld");
}

However, when I plug up my o-scope, I see no signal over the Tx line. Nada. I see data coming over the USB into the COM port on my computer, but nothing over the Tx pin.

How do I get the Arduino to put out serial data on the Tx pin?

You appear to have a "pro micro" style board in which the USB communication is directly sourced from the main ATmega32u4 processor, rather than generated as serial data and then forwarded to a distinct USB-serial converter as on traditional Arduinos.   Your question could have been resolved much more quickly if you had clearly stated the type of board you were using in words, rather than only as a product link (so I edited that into your question).

According to the documentation for the official Arduino Pro Micro:

  Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data using the ATmega32U4 hardware serial capability. Note that on the Micro, the Serial class refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class.

Therefore to generate output on the hardware UART you will need to change all occurrences of Serial to Serial1

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

void loop(){
    Serial1.print("HelloWurld");
}

The transmit data will be sourced from ATmega32u4 pin 21 which is "D1" (digital pin 1) on the headers.  If you wish to probe it, that would be the best place to do so.

If you wish to transmit data out of a different pin which is not connectied to the ATmega32u4's UART (as your example with digital pin 5 hints you might) you must instead use SoftwareSerial or similar implementation to bit-bang the serial data out of a general purpose I/O pin.

For example (inspired by this example):

SoftwareSerial mySerial(4, 5); // RX, TX

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

void loop(){
    mySerial.print("HelloWurld");
}


How to program arduino for ethernet with only usb cable I have arduino UNO r3 ATMEGA 328P board and this kind of a cable. But I want to make and test a program that need to get the data through ethernet port. Can I do only with them. I want to know whether they are enough to that (there are any converter or virtual devices) or should I buy anything.

You can do the programming of the Arduino through the USB cable, but in order to test and operate the program, you'll need an Ethernet shield and a cable to connect that to the LAN.


ESP8266 returns whatever is sent through Arduino serial I am a newbie and working on a kind of WiFi-controlled vehicle (car or maybe hovercraft later). My ESP8266 repeats the commands I send. For example, AT gives AT, AT+GWR gives AT+GWR, dabdabik gives dabdabik, etc.

I am using an Arduino Uno to send commands, as I don't have FTDI related stuff (USB to Serial Converter). I use AA cells for power supply (1.5v*2=3v). I don't even have 3.3 volt direct supply. I am using the Arduino IDE Serial Monitor. I connected the Arduino's TX to the ESP8266's RX via a voltage divider (1.66K Ohm(TX) and 1.66K Ohm (GND)->3.29 Ohm(RX)).

My connections are:

ESP8266----------------Arduino Uno
TX---Voltage divider---RX(d0)
RX---------------------TX(d1)
GND--------------------GND
VCC-------**3V**
CH_PD-----**3V**

Sometimes it gives garbage otherwise it just repeats (weird). Garbage ONLY changes if baud rate is changed.

I flashed it (it seems) with the AT 9.5.2 firmware. Flashing works rarely ONLY with TX to TX connected directly without a voltage divider.

I tried as much as I could after searching the web and ESP8266 forum but still couldn't solve problem.

Please help. I am a student in a small town (Manipal) in Southern India so no good stores nearby and I don't want to buy FTDI or anything online. I am a bit new to electronics, but I am a C++ programmer and student.

UPDATE: I noticed after some resets that it gives full garbage to longer commands most of the time, whereas two-letter commands give partial garbage. For example AT gives IT,TT,OT,etc.

There is no coding.
I am sending the commands directly via Arduino hardware serial pins (rx,tx) and a bare minimum program.

I noticed when testing my ESP8266 using the Arduino IDE serial console that ending with a CR repeated what was sent, a NL executed the command and combination of the two yielded a combination of the two behaviours. This could have just been the firmware on mine (it seemed to be non-standard), but it is possible that the behaviour is similar on yours. If you are using CR & NL, it would explain repetition. However, I can't explain commands not executing, or executing abnormally.


How can I get my LCD display to display Chinese and Japanese characters? I'm making a project that requires me to display Chinese and Japanese characters on an LCD. However, the 16x2 LCD display I have does not seem to support displaying Chinese and Japanese characters.
If I do something like lcd.print("おはよう世界"); or lcd.print("简体中文测试");, it seems to display just a bunch of jumbled random characters (which I am assuming have their character values add up to the values of the characters in the code).
How can I get my LCD to display Chinese and Japanese characters?
Or, if there's no way to do it without buying a new one that supports it, where can I buy one?

Displaying Kanji or Chinese characters is way beyond the ability of an LCD that displays 5 pixel by 7 pixel characters.
To understand the limitations, take a piece of graph paper and draw out a set of 5x7 rectangles. See if you can define ANY recognizable Japanese or Chinese characters on your graph paper.
Maybe a couple of characters? (Then again, maybe not.)
You need a display with a lot more resolution, like an OLED graphics display. You are also struggling against a microcontroller that doesn't have support for Unicode. It's just not up to the job. You'd be much better off with a Raspberry Pi and a screen like a smart-phone color LCD screen. Install Linux and you can have native support for Unicode.
As others have pointed out, hiragana or katakana would be more practical, and there are some low-res LCDs that support those characters.


How to program ATTiny85 running 3.3V I have a working project built around ATTiny85 on a breadboard running at 5V. Now I want to move this prototype on a PCB where it will be powered from batteries. All components used are capable of running 3.3V so I want to run the ATTiny85 at 3.3V as well.

I don't have a programmer so I use ArduinoISP to program the ATTiny. If I change the fuses on Tiny to run it at 3.3V can I still use the 5V Arduino to program the tiny?

Since the ATTiny can easily run at 5V I don't see any problem with programming it at 5V levels and then run it at 3.3V. Is that correct?

Since the ATTiny can easily run at 5V I don't see any problem with programming it at 5V levels and then run it at 3.3V. Is that correct?

Yes. But if there are any components on the board that can't run at 5V then you must provide some way of protecting them from the excessive voltage.

  If I change the fuses on Tiny to run it at 3.3V can I still use the 5V Arduino to program the tiny?

There are no fuses required to change the actual operating voltage of the device. There is the BOD threshold, but you can still operate the device at a higher voltage without issue regardless.


avrdude.conf: programmer type must be written as "id_type"? I'm trying to compile & run using ino.

At the ino upload step I get the following error:

avrdude: error at /usr/share/arduino/hardware/tools/avrdude.conf:332: programmer type must be written as "id_type"

Relevant section of avrdude.conf:

programmer
  id    = "wiring";
  desc  = "Wiring";
  type  = wiring;   # line 332
;

I've seen various posts around the internet that suggest I just delete the config & refresh it, but I'd like to find the correct syntax and actually understand & fix the issue.

After looking at the source repo it looks like quotes are now required:

  type  = "wiring";


NODEMCU 1.0 HX711 Load cell reading weird text Hi Guys! i have a problem with the reading with my NODEMCU where i tried this code on an arduino UNO it is working perfectly fine but until i tried to switch it to NODEMCU 1.0 which have a wifi function that i need, the reading turn out to have this type of error, i've tried looking for solution online and tried every single of them but apparently none of it help. The image is the error i have faced and the connection i have made from the nodemcu to hx711 is VCC --> Vin or 3.3v, GND --> GND, DT --> D2, SCK --> D3.
Here's the code that i found online to use:

#include <HX711.h>

// Scale Settings
const int SCALE_DOUT_PIN = D2;
const int SCALE_SCK_PIN = D3;

HX711 scale(SCALE_DOUT_PIN, SCALE_SCK_PIN);

void setup() {
  Serial.begin(115200);
  scale.set_scale(-47740);// <- set here calibration factor!!!
  scale.tare();
}

void loop() {
  float weight = scale.get_units(1);
  Serial.println(String(weight, 3));
}

Thanks in advance!!

Try D1 instead of D3. D3 is io 0, a boot configuration pin with pull-up on board.


Eclipse C++ Ide for Arduino 2.0 and eeprom.h (no such file or directory) I am using a Pro Mini and the Arduino Eclipse plugin. I have a project that is close to 1,000 lines of code and I am using things such as analogRead() and the u8g display library. Now I am at the point where I want to save data to EEPROM but I can't, because it says "eeprom.h (no such file or directory)". I have tried including this library in both my main file (where the setup and loop functions are) and also in my own .h files, which are in the same folder as the main file. Any thoughts on this?

I'm sorry but it's quite difficult to understand what you are asking. Are you saying you are trying to write some code to write to an EEPROM and you can't find eeprom.h?

1,000 lines isn't a big enough program to cause issues unless there is a problem with your IDE. This file should be included from you main file. If you were using the Arduino IDE then there is a feature to include the library and it adds the #include statement for you.

I don't know what operating system you are using, you didn't say but have you searched for the file? Does it exist? Have you got the correct case for the filename (doesn't matter on Windows)? I think it is called EEPROM.h, maybe changing the name in the include statement will help.

What can't find the file, Eclipse or the compiler? If it's your IDE it shouldn't matter.

Have you got an EEPROM library and can you build and run the examples?

I don't know if this version of Eclipse and the plugin is recent or not, it's possible that the EEPROM library is not supported on this version. You would need to research that. When you encounter problems with third-party tools, it is usually best to revert to the Arduino IDE and check that the tool is functioning correctly.


Connecting hardware to the Arduino I'm using an Arduino Due with various sensors. At the moment, I'm using the majority of the pins along the width (the double width pins). I want to make the setup more permanent, however I can't seem to find any ribbon cables with 36-conductors. What do you use for long term connections on the Due, especially if you occasionally need to unplug all the connections? Would a 40-pin ribbon cable work as they're easy to come by.

Thanks

I have used 40 pin cables for this purpose, specifically, IDE cables (beware: on high speed, "80 conductor" cables, but still with 40 pin connectors, some pins are permanently connected, to indicate to to the controller that this is a high speed cable!). The connectors are cheap, the cables are free if you ask around (probably less so now). In my case, I connected two extra-large 7-segment displays, and it worked great. More pins than you rarely hurts. In my case, it was especially useful since I needed some pins at the top, and some pins at the bottom of the display; my ide cable had three connectors (motherboard & two drives); I used the top row on one ide connector to the top of of my displays, and the bottom row of pins on the other connector to the bottom of the displays.


servers , free domains with ESP Lets Say That I Have a  routine like:

I have written PHP codes for the free domain that will:

Wait for request like url/control?ToDo="someMethod",parm=Something (posting some password for security)
and will change the database values for ToDo and parms as the request sayed
Wait for request like url/veiw (posting some password for security) and will send the values of sensors that is stored in the database
Wait for request like url/esp?Doin="someMethod",sens1=Something,sens2= ..... and will change the database values for doin and sensors as the request said
Wait for request like url/check and will send the values of ToDo and parms that is stored in the database

The problem in the code of ESP or node that they need IP to connect
the IP that I know is free domain provider's not for my link

I guess I'm missing some knowledge in servers (in english too but it's off the topic XD)  and IP things

Any one can help with a well documented method or API?

Edit:

There Were 2 main problems -:

1- I Need to know more about HTTP requests , How they look like and what should be in Headers

2- After I have build a good ones and Tried the problem was in my connection with free domain server I've checked to find out that the server is down so I moved To a reliable Server And , It worked .

I guess that's it for now ,
Thanks too you All

You do not need the IP address of the server. You connect with the name of the server and DNS will resolve it to IP address. See the WiFiClient example of the ESP8266WiFi library


Use SD Card while Pin 11 is being used for PWM On Arduino Uno Rev3, I just ran the speaker_pcm demo that used TIMER1 and TIMER2 to generate a PWM wave. However, this means that the Pins 3, 9, 10 and 11 can not be used anymore; according to the documentation:

Takes over Timer 1 (16-bit) for the 8000 Hz timer. This breaks PWM
(analogWrite()) for Arduino pins 9 and 10. Takes Timer 2 (8-bit)
for the pulse width modulation, breaking PWM for pins 11 & 3.

I wanted to change the program such that the WAV data was read from a SD card. However, this is what documentation for SD.h library says:

The communication between the microcontroller and the SD card uses SPI,
which takes place on digital pins 11, 12, and 13 (on most Arduino boards)

This means both the SD.h and speaker_pcm want to use pin 11, and the requirement to use these pins is dictated by the hardware. I am guessing that this clash will create problems.

Is there any way I can make this work? Can I switch between SD card reading and Audio playing somehow (essentially multiplexing in software)? Or will this collision of pin usage not be a problem?

The program you link to does not take over pins 3, 9, 10 and 11, it
takes over Timer 1 and Timer 2, which are used to provide PWM capability
on those pins. This means you cannot do analogWrite() on those pins
anymore, but you still can use them for other purposes, including SPI
access to an SD card.

Note, however, this line of code:

int speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

This of course will conflict the SPI port using pin 11 as MOSI. You can
fix this conflict simply by setting speakerPin to 3 instead of 11.


Error on Arduino Code (unknown type name 'LiquidCrystal') I am using Arduino IDE 1.6.8 and I am trying to compile the following code Wheatstone Bridge. I have currently a really weird error:

unknown type name 'LiquidCrystal'

This error seems to come from the header file:

// Include the Wheatstone library
#include <WheatstoneBridge.h>

// Include the LCD library
#include <LiquidCrystal.h>

// Declare external global lcd
extern LiquidCrystal lcd; <<<Error

I have already installed the LiquidCrystal library but I don't know if this trouble is due to the compiler (and the IDE) or something is wrong. The compiler seems to find the right libraries...

Using "extern" when instantiating a class is unusual.  We can not tell what your intentions are because this is only part of your code.  However it would be my guess that this code:

// Declare external global lcd
extern LiquidCrystal lcd;

Should actually be written like this:

// Declare external global lcd
LiquidCrystal lcd((12, 11, 5, 4, 3, 2);

This is making a BIG assumption that you are using an LCD similar to the one used in the HelloWorld example and you have connected it using the same pins!  Comments from the HelloWorld example to help you out:

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

Background:

Arduino sketches are written mostly in C while the libraries take advantage of C++.  As such the libraries can use a C++ feature called "overloading".  This is where you can have several different functions with different parameters all with the same name. The advantage is that you can call upon slightly different functions (or in this case different classes) simply by altering what is passed.  The LiquidCrystal class has defined all these possibilities:

  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);

But in none are there no parameters.  That is why the compiler could not find the class in your code.  You needed to match one of the above class types.


Breaking a switch case from an ISR I'm struggling with something. My CPU sits in a switch case state machine like this:

switch(expression) {

   case constant-expression_1  :
      statement(s);
      break; /* optional */

   case constant-expression_2  :
      statement(s);
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

I have an interrupt that occurs on a button press. In the interrupt, I change the switch expression to the case I want to go next, like this:

void ISR(void){
   expression = constant-expression_2;
}

After the interrupt has been handled, I want the CPU to return directly to the case being switched to, and to not continue where it left off.

Does anyone have any good ideas on how to implement this, if it's possible? I'd prefer to not have to wait for the code to finish what was happening in the previous case before going to the one being switched to.

Thanks in advance!

Most of the time this isn't a problem, because code normally runs pretty fast. The problem, most of the time, is the use of delays. What I did was use my own delay function that checks if the expression has changed, and if so, immediately returns.

Below is my code. I had to modify it a bit, so it might not work out of the box, but will give you the idea as to how.

volatile byte expression;
volatile boolean expressionChanged = false;

switch(expression) {

   case constant-expression_1  :
      statement(s);
      myDelay(1000);
      statement(s);
      break; /* optional */

   case constant-expression_2  :
      statement(s);
      myDelay(500);
      statement(s);
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

void myDelay(int ms)
{
    uint32_t start = micros();
    while (ms > 0 && !expressionChanged)
    {
        //yield();not implemented in arduino
        if ( (micros() - start) >= 1000)
        {
            ms--;
            start += 1000;
        }
    }
}

void ISR(void){
   expression = constant-expression_2;
   expressionChanged = true;
}


Read from serial monitor and put it in a array of byte I'm a new here and this is my first question.
I would like to read from serial monitor and stock the information in a array of bytes. then I want to print this array in serial monitor.
This is the code that I tried:

byte A[6];

void setup()
{
}

void loop() {
  A[6] = Serial.read();
  Serial.write (A);
}

If you want to print it only, I would suggest not to store it. But if you want to do some calculations, you might store it.

The problem you make is you always store the value in the 6th element of the array A, however A only has elements A[0] to A[5], so A[6] is beyond the storage space, and results in crashes (sometimes) or at least unexpected behavior.

To fix it you have to store the value in the correct element of A, and for that you need an index variable. Since you can only store 6 values, after the 6th, start with the 0 and process it.

Like:

byte arr[6];
index arrIndex;

void setup()
{
   arrIndex = 0;
}

void loop() {
  // Read serial.
  arr[arrIndex] = Serial.read();

  // Increase counter
  arrIndex++;

  // If the maximum is read, print values and reset it.
  if (arrIndex == 6) {
     // Print the elements.
     for (index = 0; index < 6; index++)
     {
        Serial.write(A[index]);
     }

     // Restart counter.
     arrIndex = 0;
  }
}

An improvement: instead of 6 everywhere, use a define:

#define MAX_ELEMENTS 6


How to avoid Multiple definition of 'Blynk' error? By including

 #include <BlynkSimpleEsp8266.h>

Blynk library (https://github.com/blynkkk/blynk-library) from more than 1 module/cpp file, "Multiple definition of `Blynk’" error is thrown at compile time. The header file contains following:

static WiFiClient _blynkWifiClient;
static BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);

How can I get the Blynk declarations into a second or third module, without multiple definitions error? Editing the header/library file/s is not an option!

By the question in How to create global variables/includes/functions for use in multiple source files it is still not clear what a working solution is...

The Blynk "simple" header files are not ready to be included into multiple cpp files. They are meant to be included only in the main ino file. The reason is that the variable allocations are in headers file, which is bad practice for  C and C++. The h files should contain only declarations. The right way would have

extern BlynkWifi Blynk;

and the lines which are now in the h file should go in a cpp file. Then every cpp file that includes the .h will know about the variables but the variables would be allocated only once.

The fix is to change the library or to copy the BlynkSimpleEsp8266.h include to your project as for example MyBlynk.h and change the Blynk variable in MyBlynk.h to extern and add a MyBlynk.cpp file with variables allocation

#include "MyBlynk.h"

WiFiClient _blynkWifiClient;
BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);


Interfacing a CCTV camera (AV output) with Arduino Uno I have to use a camera to take picture in my major project. I want to use this camera, which has AV output. Please tell me how to interface this camera with my Arduino Uno and use the data from camera and send it to my PC using a Wi-fi Module?

P.S. Please do not suggest me to use wireless camera because firstly they are expensive and secondly I require a board in my project anyway.

Unfortunately, I have to tell you that a UNO isn't enough powerful to work with any type of camera: it hasn't got enough ram and processing power to elaborate your camera's data. (see atmega328P's specs)

I'm not sure you can work with that camera, unless it is digital and has integrated RAM to keep the frames.

A good project which I suggest you to see is arducam.


Lines not pulsed fast enough (?)) Should this code pulse the PB3 and PB4 pins (MOSI and MISO of an Arduino Uno) at 2ms interval ?

#include <avr/io.h>

int main(void)
{

//  for (byte i = 0; i < 32; i++)
//    pinMode(i, INPUT);

  DDRB |= (1 << PB4);
  DDRB |= (1 << PB3);
//  pinMode(PB4, OUTPUT);
  while (1)
  {
    PORTB &= ~(1 << PB4);
    PORTB &= ~(1 << PB3);
  //  digitalWrite(PB4, LOW);
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//    delayMicroseconds(10000);
    delay(1);
    PORTB |= (1 << PB4);
    PORTB |= (1 << PB3);
  //  digitalWrite(PB4, LOW);
//    delayMicroseconds(10000);
    delay(1);

  }
}

If used for SPI MOSI can do 1 MHz just fine - so my logic analyzer says. MISO would not behave when used by SPI. MISO works in other non-SPI scenario: I am able to use the Arduino for in-system programming other AVR boards.

But the code above pulses neither MISO nor MOSI, as pointed out by the same logic analyzer in the same setup. Should it?

update

There has been some issue with the board. Changed it and all works fine now, regardless of using int main() alone or also calling init() as per @Majenko 's answer

The code content works fine while compiled as an Arduino program - that is, using the proper setup() and loop() structure:

void setup() {
    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
}

void loop() {
}

However the same code will not work when using it in main(). This is simply because delay() will never work. Normally main() calls init() which then configures TIMER0 to generate the millis() and micros() count used for the delay() functions.

So either use setup() and loop() instead of main(), or make your program call init() before anything else:

int main() {

    init();

    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
    return 0;
}


Do we need to burn bootloader in new Atmega328p before uploading the arduino code I have an arduino code which is working fine. Now I am planning to make a PCB out of it. But I do not want to use the complete Arduino board. I just want to use the Atmega328p microcontroller. So my plan is to connect the USBasp programmer to the new Atmega328p and upload the code. So before this code, do I need to upload the bootloader or uploading the code first will run fine.

Tools > Burn Bootloader in the Arduino IDE does two things:

Set fuses according to the settings in boards.txt for the Tools > Board selection
Install the bootloader.

The latter is pointless since when you do an Upload Using Programmer the bootloader will be overwritten but the former is very important to do the first time you use a new chip(or anytime you want to change the fuses) to be sure that the correct fuses are set, which likely will be different from the default settings of the chip when you get it. Upload Using Programmer does not set fuses, the only way to do this via the Arduino IDE is Tools > Burn Bootloader.

So yes, you should Burn Bootloader.


Set pins to LOW over time I've written a simple sketch that adds threshold to an PIR sensor. If the PIR sensor sends 3 HIGH ex. HIGH...LOW...HIGH...LOW...HIGH (The LOW == no movement) it will trigger and alarm.

I want to reset the counter of HIGHs if there's no movement detected. The problem is the loop will get delayed if I put it inline. My code: (Don't mind my code, I'm pretty newbie)

int calibrationTime = 30;
int pirPin = 5;
int ledPin = 6;
int sensorState;
int stateCount = 0; //How much movement is detected
int stateThreshold = 3; //THRESHOLD
bool isSensorHigh;

void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  digitalWrite(pirPin, LOW);
  Serial.print("calibrating sensor ");
  for (calibrationTime; calibrationTime > 0; calibrationTime--) {
    Serial.print(calibrationTime);
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}
void loop() {
  sensorState = digitalRead(pirPin);
  //Serial.println(sensorState);
  if (sensorState == 1) {
    isSensorHigh = true;
  }
  if (sensorState == 0 && isSensorHigh == true) {
    isSensorHigh = false;
    stateCount++;
  }
  //Set pins 2,3,4 here to LOW if there's no movement detected over time
  if (stateThreshold == 3) {
    switch (stateCount) {
      case 1:
        digitalWrite(2, HIGH);
        break;
      case 2:
        digitalWrite(3, HIGH);
        break;
      case 3:
        digitalWrite(4, HIGH);
        break;
    }
  }
  if (stateCount == stateThreshold) {
    blinkLeds();
    delay(3000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(ledPin, LOW);
    stateCount = 0;
  }
  Serial.println(stateCount);
  delay(150);
}

void blinkLeds() {
  for (int x = 4; x > 0; x--) {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    delay(1000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    delay(1000);
  }
}

Use millis() instead on delay.
Ref: https://www.arduino.cc/en/reference/millis


Using timer0 on Arduino Uno I am trying to find a simple timer0 interrupt example, but none of those work. Neither this code which I tried to run:

boolean toggle0 =0;

void setup() {
pinMode(8, OUTPUT);
  cli();

  // Set timer1 interrupt at 1 Hz
  TCCR1A = 0; // Set entire TCCR1A register to 0
  TCCR1B = 0; // Same for TCCR1B
  TCNT1  = 0; // Initialize counter value to 0

  // Set compare match register for 1 Hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)

  // Turn on CTC mode
  TCCR1B |= (1 << WGM12);

  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);

  // Enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  sei();
}

ISR(TIMER0_COMPA_vect){  // Change the 0 to 1 for timer1 and 2 for timer2
  if (toggle0){
    digitalWrite(8,HIGH);
    toggle0 = 0;
  }
  else{
    digitalWrite(8,LOW);
    toggle0 = 1;
  }
}

void loop() {

}

What am I doing wrong?

The main problem is you are using the wrong interrupt handler. You are setting up Timer1, but the interrupt handler is for Timer0:

boolean toggle0 = 0;

void setup() {
pinMode(8, OUTPUT);
  cli();
//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  sei();
}

ISR(TIMER1_COMPA_vect){  //change the 0 to 1 for timer1 and 2 for timer2
  toggle0 = !toggle0;
  digitalWrite(8, toggle0);
}

void loop() {

}


How can I burn the bootloader onto atmega328 (not atmega328p)? Hi I bought some atmega328 chips (not to be confused with atmega328p). They are very similar but the atmega328p chips are just more power efficient, so I've read. Anyways, my goal is to burn the arduino bootloader onto these chips so that I can make some breadboard arduinos. I used the arduino ISP sketch and hooked up everything like so ->

I was following instructions from the following link ->
https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
However, when I press the Burn Bootloader button under Tools, it keeps telling me that it can't verify that my chip is an atmega328p. Well it is not atmega328p but everywhere online says it does not matter since they are the same architecture. The error also tells me that I can override by typing -F, but it doesn't tell me where to input this. I'm pretty sure that may fix the issue, but I am not sure where I'm supposed to put the -F.
Also I saw another post that was similar to this one but the answer said that the problem is the atmega328 chip itself. Is it even possible to add the bootloader to these chips??? Other sources said it is, but I can't seem to do it.

How can I burn the bootloader onto ATmega328 (not ATmega328P)?

As Juarj commented, For a variety of standalone AVR microcontrollers you can add new "cores" to the Arduino IDE using it's board manager.
This provides the Arduino IDE with information about your specific chip and this means the IDE can instruct the avrdude program appropriately and select a bootloader image that was written to support your specific chip
The Minicore documentation says it supports all variants of ATmega328
Other well-known examples of cores for bare AVR microcontroller chips  include ATtinycore which supports a wide range of ATtiny microcontroller chips like the popular ATtiny85.


Red LED not turning off on Adafruit Circuit Playground Classic When using the traditional Blink example program, the light blinks as expected. Even when writing from scratch digitalWriteing pin 13 to high and low repeatedly works fine. The problem is when I try to use CircuitPlayground.redLED(false). That has no effect, and the Circuit Playground specific Hello_Blink example doesn't work at all. The LED is just constantly on no matter what I do.

I've looked through the source code for the CircuitPlayground library and it's also using pin 13, and doing essentially the same thing as the traditional blink program.

Not sure what else could be causing this.

This is the Blink sketch that's working:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

And this is the Hello_Blink sketch that is not working (LED remains on permanently):

#include <Adafruit_CircuitPlayground.h>

void setup() {
  CircuitPlayground.begin();
}

void loop() {
  CircuitPlayground.redLED(HIGH);
  delay(500);
  CircuitPlayground.redLED(LOW);
  delay(500);
}

Changing HIGH and LOW to true and false does nothing.

I also have noticed two other strange things. The speaker does an audible click when the board resets when using the Hello_Blink sketch (or any other sketch that uses the CircuitPlayground library), as if pin #5 is being held high as well. Also, I added these two lines

pinMode(6, OUTPUT);
digitalWrite(6, HIGH);

to the setup() of both programs and then probed #6 with a multimeter. Pin #6 is not connected to anything. The traditional blink program allows the pin to go high as expected. The CircuitPlayground sketch, however, the pin stays low.

I am using this library with a atmega32u4.

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.


Re-use smartphone/tablets parts like a camera For learning and hacking purposes, I plan to study and use parts from smartphones and tablets like Galaxy or iPhone. They are really efficient and pretty cheap...

Did anybody do this before? If yes, can anybody tell me what kind of connector is this one on the galaxy camera, Galaxy Tab S 10.5 Front Facing Camera (Wi-Fi), and whether it can be found for attaching it to an Arduino project?

Edit: Someone else asked a similar question here, How to reuse quality camera from old / broken phone.

The connector on the flex circuit from that camera was made by Hirose (it has an HRS logo on it), and might be in the BM10, BM14, or BM20 series.  You can measure the pin spacing, stacking height, etc. to check which series it's in.  For example, the Hirose BM14 series of FPC to board connectors has pins at 0.4 mm Pitch and 0.8 stacking height.

Mouser.com carries a 24-pin BM14 connector that might mate or match with the pictured connector.  For other photos of Hirose FPC connectors, see google images for hirose fpc.

While you probably can find a matching connector (via careful measurement and perhaps some trial and error) and build an interface, it may be difficult to use the camera once it's hooked up.  Most Arduino models have too little RAM to support image processing.  A Yun might do it, a Tre, or some other micro entirely, eg Beagle or Raspberry.


Why does the potentiometer act as an on/off switch in my program? I'm using an HC-SRO4 Ultrasonic Sensor and a D10K Potentiometer. So, I was just messing around with the potentiometer in the program and then tried to change the brightness of the LED which turns on if a certain condition is met, but the potentiometer acts like an ON/OFF switch instead. I'd like to know why this happens and how can I change the LED's brightness normally in this situation.

long duration;
int distance;
int trigPin = 9;
int echoPin = 10;
int buzzer = 11;
int LED = 3;
boolean detected = false;
#define pot 0
int val = 0;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pinMode(buzzer,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
val  = analogRead(pot);
val  = map(val, 0, 1023, 0, 255);
Serial.println  (distance);

if(distance < 50 && distance != 0){ // distance != 0  because sometimes the distance's first value is sometimes 0 which ruins the purpose of
 // the program
  analogWrite(LED, val);
  alarm();
  detected = true;
}
else if(detected){
  digitalWrite(LED,LOW);
  alarm();
}
}

void alarm(){
  tone(buzzer, 450);
  delay(100);
  tone(buzzer, 1000);
  delay(100);
  }

The answer is very simple. You use pin 12 for LED. Pin 12 can't do analogWrite(). This pin doesn't support PWM on Arduino UNO (Atmega 328)

Pin 3 is not OK either. Use of tone() function disables PWM on pin 3. From reference: "Use of the tone() function will interfere with PWM output on pins 3 and 11".


Can external power supply above current limit lead to errors/shutdown arduino? I have an Arduino Due that is connected both over native USB to PC and a 12v power supply in the Jack.
Mounted on the Arduino I have a custom PCB that drives 3 motor drivers. The Motor drivers are powered via the arduinos VIN Pin with 12v.

As Ive read elsewhere the arduino automatically chooses the 12v powersupply in this case. My question is: If the 3 motor drivers exceed the 1amp that the powersupply can supply, will the arduino encounter errors/shutdown or automatically switch back to USB for power supply?

If so, is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Also, how much current can I safely drive through the VIN Pin?

Thanks!

If the incoming voltage drops below 6.6V the MOSFET will activate for the USB power and that will become available. But it's not perfect.

The MOSFET is always "partially" active - that is, the "body diode" is always available, so if the 5V rail drops below the USB voltage minus the forward voltage of that body diode the USB power will take over regardless of what else is happening. That 5V rail then feeds the 3.3V regulator, and
since the ARM chip on the Due is a 3.3V chip, even a dip of a volt or so on the 5V rail should have no effect on the MCU.

So theoretically the chip should keep running fine all the time regardless of what happens with the power.

  Is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Not really, no.  You can remove the 12V from the jack though and just power from USB. Connect the 12V to your motor drivers, and link its ground to the Arduino ground. The motors will use the 12V supply, and the Arduino the 5V supply.

  Also, how much current can I safely drive through the VIN Pin?

The diode inline with the barrel jack is rated at a maximum sustained current of 1A. Any more than that and you risk blowing that diode.


LCD display under power saving mode To make LCD display, Pro Mini and ATMega2560 to run on one set of battery for months, appreciate idea and comment.

Which LCD to use?

Which LCD chip controller chip (hide inside the LCD) has better power saving mode?

Which library with functions of power saving and also can put out VERY beautiful per-programmed display, like multiple fonts, different fonts size, some graphics like circle, rectangles, color fills, gradual-color-changing background with text and graphic at 'foreground' (as in PC power point style)?

Under context of

Small Mono chrome 2 lines text display
3 inches mono chrome graphic 128 x 64 or similar
3 inches color graphic, 320 x240 or similar

Many thanks in advance

Use an eInk/ePaper style display, which uses no power while the display is not changing.  These come in monochrome greyscale, and have excellent readability.

This solves only part of your problem as you still need to power the CPU.


Change From One State Machine To Another I have a project where I need to state from leds turning on and off to another one that will have all the leds turned on and send data and I was wondering how should I do that, this the code I have:

#include <CapacitiveSensor.h>

CapacitiveSensor cs_11_10 = CapacitiveSensor(11,10);

int state_s1 = 0;
int state_s2 = 0;
int state_s3 = 0;
int state_s4 = 0;
int state_prev_s1 =0;
int pin_s1 = 12;
int val_s1 = 0;

const unsigned int ledPins[]={2,3,4,5,6,7,8,9};
const unsigned int lenledPins=9;

unsigned long t_s1 = 0;
unsigned long t_0_s1 = 0;
unsigned long t_s3 = 0;
unsigned long t_0_s3 = 0;
unsigned long t_0_s4 = 0;
unsigned long t_s4 = 0;
unsigned long t_s2_4 = 0;
unsigned long tiempo = 250;

unsigned long bounce_delay_s1 = 5;

long total = 0;

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

  for(int i=0; i<(9); i++)
  {
    pinMode(ledPins[i], OUTPUT);
  }

  cs_11_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
  Serial.begin(9600);

}

void loop()
{

  MBoton();          //MAQUINA DE ESTADO

 MaquinaGeneral();

  if(state_s2 == 1)
  {
    led();
  }

  if(state_s1 != state_prev_s1)
  {
    Serial.print("state =");
    Serial.println(state_s3);
  }

  if(state_s4 == 6)
  {
    for(int i=0; i<lenledPins; i++)
    {
      digitalWrite(ledPins[i],HIGH);
    }
  }

  Serial.print("");

}

void MaquinaGeneral()
{
  switch(state_s2)
  {
    case 0:
    if(state_s1 == 4)
    {
      state_s2 = 1;
    }
    break;

    case 1:

    break;
  }
}

void MBoton()
{
  state_prev_s1 = state_s1;
  switch(state_s1)
  {
    case 0:         //RESET
    state_s1 = 1;
    break;

    case 1:        //START
    val_s1 = digitalRead(pin_s1);
    if(val_s1 == LOW)
     {
      state_s1 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s1 = millis();
    state_s1 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= bounce_delay_s1)
    {
      state_s1 = 5;
    }
    break;

    case 5:         //ARMED
    val_s1 = digitalRead(pin_s1);
    if(val_s1 == HIGH)
     {
      state_s1 = 4;
     }
    break;

    case 4:       //TRIGGERED
    state_s1 = 0;
    break;

  }
}

void led()
{

  switch(state_s3)
  {
    case 0:         //OFF
    for(int i=0; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],LOW);
    }
    for(int i=1; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],HIGH);
    }

    t_0_s3 = millis();
    state_s3 = 1;
    break;

    case 1:         //WAIT
    t_s3 = millis();
    if(t_s3 - t_0_s3 >= tiempo)
    {
      state_s3 = 2;
    }
    break;

    case 2:         // ON
     for(int i=0; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],HIGH);
    }

     for(int i=1; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],LOW);
    }

    t_0_s3 = millis();
    state_s3 = 3;
    break;

    case 3:         //WAIT
    t_s3 = millis();
    if(t_s3 - t_0_s3 >= tiempo)
    {
     state_s3 = 0;
    }
    break;

  }

  }

void Capacitor()
 {

  switch(state_s4)
  {

    case 0:         //RESET
    state_s4 = 1;
    break;

    case 1:        //START
    total = cs_11_10.capacitiveSensor(10);
    if(total >= 1000)
     {
      state_s4 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s4 = millis();
    state_s4 = 3;
    break;

    case 3:         //WAIT
    total = cs_11_10.capacitiveSensor(10);
    if(total < 1000)
     {
      state_s4 = 0;
     }

    t_s4 = millis();

    if(t_s4 - t_0_s4 >= 2000)
    {
      state_s4 = 5;
    }

    break;

    case 5:         //ARMED & WAIT
    t_s2_4 = millis();
    total = cs_11_10.capacitiveSensor(10);
    if(total < 1000)
     {
      state_s4 = 4;
     }

     if(t_s2_4-t_s4 >= 1000)
     {
      state_s4= 6;
     }
    break;

    case 4:       //TRIGGERED
    state_s4 = 0;
    break;

    case 6:     // ARMED 2
    Serial.println("Entro al estado 6");
    total = cs_11_10.capacitiveSensor(10);
    break;

}
}

If you think you need two finite state machines, where only one of them
is running at any given time, then it is trivial to combine them
together: draw them side by side, and add the required transitions
between them. The set of states of the combined FSM will be the union of
the states of the initial FSMs. For example, if you have:

FSM 1 states: STATE_A, STATE_B, STATE_C
FSM 2 stages: STATE_D, STATE_E
global states: FSM_1_RUNNING, FSM_2_RUNNING

Then the combined FSM will have the states STATE_A, STATE_B,
STATE_C, STATE_D and STATE_E, and all the transitions of both
initial FSMs.


Is it possible to power this 12V Wind Speed Sensor with a 5V battery? I have a battery pack used to charge mobile phones. It's capacity is 13,000mAh and it has two output ports. Both are 5V but one is 1A and the other 2.1A
It also has an Input port of 5V 1A. (To which I will connect a solar panel).

I want to be able to power this Adafruit Feather M0 as well as this Wind Speed Sensor Wind Speed Sensor Voltage Type(0-5V) SKU:SEN0170. Is it possible and if it is how?

If you have a circuit diagram for your 13,000mAh 5V battery, check whether there are internal connections at higher than 5V.  Because 5V is not a common battery voltage, there probably are cells in a higher-voltage series connection, being converted to 5V output via a step-down (buck) circuit.
An item like a “5V DC to 9V DC Converter DC-DC Isolated Power Supply Module” as in picture below [from ebay seller bidcenter] might do the job.  Also available are less-expensive not-potted adjustable boost regulators.


How to connect DRV-8835 to arduino I try to connect arduino with motor using DRV-8835. The problem I have - simply nothing happens. I used tutorial from http://www.instructables.com/id/The-SnapMobile-Start-Your-Physical-Computing-Engin/step6/Building-the-Prototype-Wiring-Up-the-Arduino-the-D/

Code for arduino:

void setup() {
    pinMode(7, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(8, OUTPUT);
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(7, HIGH);
  analogWrite(5, 255);
}

Maybe someone has scheme how to connect wires to motor. Now I'm not sure if I made a mistake or motor driver is broken.

Try this code:

void setup() {
    pinMode(8, OUTPUT);//MODE
    pinMode(5, OUTPUT);//AENBL
    pinMode(7, OUTPUT);//APHASE
}

void loop() {
  pinMode(7, HIGH);//APHASE
  pinMode(8, HIGH);//MODE
  pinMode(5, HIGH);//AENBL
  delay(200);
  pinMode(5, LOW);//AENBL
}

Here is a description of the breakout board, this shows a requirement of PWM on AENBL for speed control. Try different  delays.


Arduino MKR1000 as Access Point I want to turn my Arduino MKR1000 into an Access Point. My code is the following:

#include <SPI.h>
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

WiFiServer server(80);
char ssid[] = "MKR1000";
int status = WL_IDLE_STATUS;

void setup() {
  delay(1000);
  Serial.begin(9600);
  Serial.print("Creating access point named: ");
  Serial.println(ssid);
  if (WiFi.beginAP(ssid) != WL_CONNECTED) {
    Serial.println("Creating access point failed");
    while (true);
  }
  server.begin();
  printStatus();
}

void loop() {

}

void printStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  Serial.print("To connect, join the network and open a browser to http://");
  Serial.println(ip);
}

After uploading this, in the serial monitor I get this:

Creating access point named: MKR1000
Creating access point failed

I'm new to this so I really don't know what's the problem. I hope someone knows what's going on.Thank you in advance.

I found this reference for Wifi.beginAP() in the Wifi101 library, which I hope is the correct one - apologies if it's not.

It says that beginAP() returns either WL_AP_LISTENING or WL_CONNECT_FAILED, so checking for WL_CONNECTED is not sensible.

Try this:

if (WiFi.beginAP(ssid) != WL_AP_LISTENING) {
  Serial.println("Creating access point failed");
  while (true);
}


How does the motor shield determines how much voltage to supply to a motor? Can i connect 6v DC motor and 12v DC motor, or 6v DC and 12V stepper to adafruit motor shield v1, and an external 12v power supply?
also, how does it determine how much voltage needs to be supplied to a motor? is it done by code, when we set the speed of the motor, or the frequency?

do i have to take care of how much voltage i am supplying to the motor shield?

Can i connect 6v DC motor and 12v DC motor to adafruit motor shield v1, and an external 12v power supply?

No.

  how does it determine how much voltage needs to be supplied to a motor?

It doesn't. It supplies whatever voltage you supply through the power input.

You must match the power supply to the motor. The motor shield is merely a switch that turns the power on and off in the right way to change the speed and direction of the motor.


Make something happen on a continous input just once and for a specific amount of time My project is very complicated, but here is a visual synthesis

The input actually comes from a kinect, that detects a person position through Processing, which I connected via Serial to Arduino.
Whenever my trigger is activated, a character is sent to arduino.
What I need to make everything work properly is, upon the said input, some lines of code have to be executed once and for a specific amount of time. And upon repeated input, these lines must not be executed until the input changes.

A semplified version would be: I press a button, led turns on for one second and then turns off (even if i'm still pressing it). led doesn't turn on again until i stop pressing and press again. Obviously in my project the input is the character received via serial and the output is the motor to turn on for some time, and then turn off.

I wanted to make the serial thing specific because i think it makes the thing a little bit trickier than the led example.

you want something along the lines:

bool continuing;
#define trigger 't'
void loop(){
  if( Serial.avaiable()) {
    char c;
    c=Serial.read();
    if (continuing) {
       if (c==trigger) { //do nothing, ignore it
       } else {
       continuing=False; }
   } else {
     continuing=True;
     motors.start();
     the_time=milis();
   }
 };
 if (the_time+timespan>milis()) {motors.stop();};
}


Sending PUBX commands to GPS Board (Ublox NEO-6M) through SoftwareSerial I am having trouble parsing NMEA sentences coming from a GY-NEO6MV2 board (https://www.cytron.io/p-gps-neo6mv2), using the TinyGPS (https://github.com/mikalhart/TinyGPS) library. The GPS board itself is connected to an Arduino Pro Mini 3v3 8MHz (ATmega328)

First of all, to start debugging I want to disable all NMEA sentences other than GGA and RMC (which are the only ones I need for this project)

According to the manual, this can be done by sending PUBX commands through the SoftwareSerial (no need for binary UBX)

I am doing this in the following way

#include <SoftwareSerial.h>
#include <TinyGPS.h>

// GPS SoftwareSerial
// Shares pins with (MISO 12/ MOSI 11) used for SPI

#define GPS_RX_PIN 12
#define GPS_TX_PIN 11

TinyGPS gps;
SoftwareSerial GPSSerial(GPS_RX_PIN, GPS_TX_PIN);

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

      GPSSerial.print("$PUBX,40,GLL,0,0,0,0*5C\r\n");
      GPSSerial.print("$PUBX,40,ZDA,0,0,0,0*44\r\n");
      GPSSerial.print("$PUBX,40,VTG,0,0,0,0*5E\r\n");
      GPSSerial.print("$PUBX,40,GSV,0,0,0,0*59\r\n");
      GPSSerial.print("$PUBX,40,GSA,0,0,0,0*4E\r\n");
}

void loop()
{
// ...
}

However, the GPS board will not respond to these commands and keep sending all the NMEA sentences.

FWIW, this is the original code I'm building my project on - https://github.com/billygr/arduino-aprs-tracker/blob/master/arduino-aprs-tracker.ino

Any thoughts would be appreciated...

I've tried your code sending those PUBX commands to a ublox module and they work successfully for me.

There are a lot of fakes about on the internet using AT6558 chips repackaged as ublox. Check the GPTXT messages that are output when the GPS module is powered up to see if its really a ublox module or a fake one like this:

$GPTXT,01,01,02,MA=CASIC*27
$GPTXT,01,01,02,HW=ATGM332D,0080113573899*18
$GPTXT,01,01,02,IC=AT6558-5N-31-0C500000,J7M911C-B2-008827*50
$GPTXT,01,01,02,SW=URANUS4,V4.3.0.5*18


Use an Arduino to "intercept" transparently serial communication to Grbl? I need to have an Arduino "spying" on communications between the PC and another Arduino with GRBL. The goal is to intercept a couple of GCode commands and act on them instead of Grbl.

My first step is to attempt to be as transparent as possible, but so far, I am not getting from Grbl the clear answer I expect. For example, I get Grbl 1.1d [?2???B???u5 instead of Grbl 1.1d ['$' for help]

Here is my code so far.

#include <SoftwareSerial.h>

int PortOneTX = 10;
int PortOneRX = 11;

const String USB = "USB";
const String GRBL = "GRBL";

char endOfLine = '\n';

SoftwareSerial portOne(PortOneRX, PortOneTX);

String grblBytes = "";
String USBBytes = "";

void setup()
{
    Serial.begin(115200);
    while (!Serial)
    {
        ; // Do nothing, just wait till we are connected through USB
    }
    portOne.begin(115200);
    portOne.write("\r\n");
    delay(2);       ;
}

String stringtoWrite = "";

void loop()
{
    if (portOne.available() > 0)//while (portOne.available())
    {
        stringtoWrite = portOne.readStringUntil(endOfLine);
        for (int i = 0; i < stringtoWrite.length(); i++)
        {
            Serial.write(stringtoWrite[i]);
        }
        Serial.write(endOfLine);

    }
    if (Serial.available() > 0)//while (Serial.available())
    {
        stringtoWrite = Serial.readStringUntil(endOfLine);
        for (int i = 0; i < stringtoWrite.length(); i++)
        {
            portOne.write(stringtoWrite[i]);
        }
        portOne.write(endOfLine);

    }
}

I feel that I should be using events instead of if (serial.available) in the loop, but I am not sure how to go about it. I thought it would be easy!

Anyway, as I want Grbl-Panel to work totally transparently, I need this first step to be Ok before doing anything else.

Thanks for your help.

I finally solved my problem by buying an Arduino Due! It was a problem of speed, not of code. The Uno is just not powerfull enough to read an write to Software Serial at 115200 Bauds, or even 9600, which I tried.

The Due has absolutly no problem. I made a small code test to intercept "words" coming form "USB" To "GRBL", and it works just as expected, while GCODE is send (using Grbl-Panel on the PC) through the Due (USB) to the Uno (Grbl).

It's the very first time I solve what I thought to be a code problem by an hardware solution.

BTW, in case anyone wonder, yes, I am using a level shifter between the 2.


Rename device name (ch340 usb to serial) Mac OS Can't upload sketches to Arduino Nano clone with USB to serial chip ch340.

After installing drivers and plugging in, device has the name cu/tty.wch ch341 USB=>RS232 fa130 (with spaces), but Arduino can't recognize the full name (only tty.wch).

Is it possible to rename device in Mac OS or change device identifier?

UPDATE: ch340 new driver http://www.wch.cn/downloads.php?name=pro&proid=178

I am Antonis from codebender and we recently released drivers for the Mac.

If you want to overcome this problem, without disabling your computer's security settings, maybe I can help you with this! Codebender just released their Mac drivers package, which includes a new driver that supports the CH340G chip, on Yosemite and all other versions of OS X for Mac.

This will help you to install these drivers securely, and
all you have to do is to download and install them.

You can find more information about the drivers in the codebender blog.


Why would uninitialized SD-card module without card disable CAN-Bus shield? (I am able to successfully initialize CAN-Bus shield and SD-card module w/ card in it.)

Now I have removed all code related to the SD-card module, yet I left the module (without the card in it) physically connected. This results in the CAN-Bus shield initialization failing.
When I insert the card into the SD-card module the CAN-Bus shield initializes successfully. (I am still not doing SD-card module initialization.)

Of course, I can just disconnect the SD-card module or leave the card in it... But I am trying to understand this black magic.

I have connected the SD-card module CS to pin 8, the CAN-Bus shield clone CS is connected to pin 10. I tried to set the SD-card module CS pin to OUTPUT and to HIGH. That had no effect.

the CAN-Bus shield + schematics: http://www.elecfreaks.com/estore/can-bus-shield.html [Resource -> Schematics]
the SD-card module: https://ebay.com/itm/161366316226?_trksid=p2057872.m2749.l2649

Without seeing schematics this is purely supposition:

My guess is that the SD shield contains bi-directional level shifting. The MISO pin, which connects the DO pin of the SD card to the MCU, will have a 3.3V -> 5V level translator on it.  This, with no SD card inserted, will be floating (flapping around in the breeze) causing the output of the level translator to randomly produce digital signals on the MISO pin. These signals interfere with the MISO signals from your CAN shield.

How best to cure the problem very much depends on what level shifting is in the circuit and how it is controlled and wired. For that we will need to see schematics of both the CAN and SD card shields.


Reading quadrature encoder I am using an encoder motor for one of my projects and i was reading encoder values manually through Arduino. It was working fine when i turned it slowly, but whenever i would rotate it at some higher speed, data input to the arduino would stop. I am using the encoder at 4 x.

Can somebody help me with some code to read the data from encoder faster.

    int pulses, A_SIG=0, B_SIG=1;

void setup(){
  attachInterrupt(0, A_RISE, RISING);
  attachInterrupt(1, B_RISE, RISING);
  Serial.begin(115200);
}//setup

void loop(){

}

void A_RISE(){
 detachInterrupt(0);
 A_SIG=1;

 if(B_SIG==0)
  pulses++;//moving forward
 if(B_SIG==1)
  pulses--;//moving reverse
 Serial.println(pulses);
 attachInterrupt(0, A_FALL, FALLING);
}

void A_FALL(){
  detachInterrupt(0);
 A_SIG=0;

 if(B_SIG==1)
    pulses++;//moving forward
 if(B_SIG==0)
     pulses--;//moving reverse
 Serial.println(pulses);
 attachInterrupt(0, A_RISE, RISING);
}

void B_RISE(){
  detachInterrupt(1);
  B_SIG=1;

  if(A_SIG==1)
     pulses++;//moving forward
  if(A_SIG==0)
      pulses--;//moving reverse
  Serial.println(pulses);
  attachInterrupt(1, B_FALL, FALLING);
}

 void B_FALL(){
    detachInterrupt(1);
    B_SIG=0;

    if(A_SIG==0)
       pulses++;//moving forward
    if(A_SIG==1)
       pulses--;//moving reverse
    Serial.println(pulses);
    attachInterrupt(1, B_RISE, RISING);
}

volatile long rawTacho[2];      // interrupt 0 & 1 tachometers

ISR(MotorISR1)
{
    int b = digitalReadFast(8);
    if (digitalReadFast(2))
        b ? rawTacho[0]-- : rawTacho[0]++;
    else
        b ? rawTacho[0]++ : rawTacho[0]--;
}

ISR(MotorISR2)
{
    int b = digitalReadFast(9);
    if (digitalReadFast(3))
        b ? rawTacho[1]-- : rawTacho[1]++;
    else
       b ? rawTacho[1]++ : rawTacho[1]--;
}

void setup()
{
    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    pinMode(8, INPUT_PULLUP);
    pinMode(9, INPUT_PULLUP);

   attachInterrupt(PCINT0, MotorISR1, CHANGE);  // pin 2
   attachInterrupt(PCINT1, MotorISR2, CHANGE); // pin 3
}

something similar to that - it was extracted from bigger code so you will have read it and understand it as opposed to copy paste.

Update note: This is not complete in a pure form - the cpu doesnt tell you what pin had an interrupt - thus some underlying Arduino code figures that out for me, but it is fairly efficient, and I used it as is. Also if it is not obvious, this is reading encoders from 2 motors. 1 interrupt is assigned to each motor, the second phase of each is on a non-interrupt pin. Never lost a reading to my knowledge.

The problem with your code is probably the print in the interrupt as pointed out in a comment.


A waterproof Chlorine Sensor Does anyone know where I can find a Chlorine Sensor to use with the Arduino? It would need to be water proof. I've googled, but I couldn't find anything.

EDIT
Requirements: relatively inexpensive (under $100us), works with Arduino, waterproof and used to detect chlorine in water.

Your best bet would probably be to interface with a colorimeter.  There is a tutorial for an open source colorimeter here:

http://www.appropedia.org/Open-source_colorimeter

IORodeo also sells a shield:

http://www.iorodeo.com/colorimeter

Vernier sells a colorimeter that may be suitable for your project & Sparkfun sells a shield to interface with Vernier sensors.

If a colorimeter doesn't work you would have to use an electrode, which is pretty expensive and has a shelf life.


How to display information from a web API on an LCD (2x16) in real time? How can I display information from a web API on an LCD (2x16)?

This is an example of the data returned by the API for train times.

The information that I want to display on the LCD is time information (2 min, 5 min, etc., ...)

Your API presents the information in a format called JSON, JavaScript Object Notation. It is a human readable way of passing around data structures. Web APIs often make use of it.

Benoît Baluchon has a library, Arduino JSON for manipulating JSON in embedded systems. You can download it from GitHub. The documentation is here. Assuming that the problem you need to solve is getting the information out of JSON and into a form that you can display, this looks like a good place to start.

Using Arduino JSON, the code to get the first time would look something like this:

char* getSchedule();

StaticJsonBuffer<200> jsonBuffer;

JsonObject& root = jsonBuffer.parseObject(getSchedule());

char* next = root["response"]["schedules"][0]["message"];

Note: this is from a quick search on "arduino json" followed by quickly reading the code. I doubt if it is exactly right, but hopefully it is enough to get started.


How do I use two PulseIn() functions simultaneously in Arduino? I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?

You can't. pulseIn() is a blocking function that waits for a pulse to arrive before returning.

Instead you will either have to use interrupts or (where available) Input Capture peripherals.

However, using multiple ultrasonic sensors at the same may not make sense. Unless you take great care with your physical design you will get interference between the two.  Echoes from one bouncing around will trigger the other.  For this reason it is normal to not trigger both at once, but to use them sequentially, in which case pulseIn() is still perfectly fine to use.


Fluctuating readings of LM35 temperature sensor (+- 5°C) with Arduino UNO I am trying to read a LM35 temperature sensor with Arduino UNO which I got as a gift.
The issue is the fact, that my readings of sensor are, well, suspicious at least - they jump with each reading some 5 °C up or down.

I had used several posts how to wire  the thing to Arduino board and for and program the reading (1, 2, 3) and produced the code posted below. The sensor reading fluctuates really a lot - it jumps by some 3 to 7 °C after  each reading regardless of reading frequency (tested with reading each 0.5 s, 1.0 s or 2.5 s). (Unfortunately I do not own a multi-meter to check actual values.) To mitigate the issue I implemented an averager, but underlying problem stays. Expected values are something like 23 or 24 °C as measured by digital weather station and bimetallic thermometer respectively.

Have you met this before ? Do you have any ideas what might be source of this ? I am beginner to electronics as well as to Arduino, trying to learn and mainly understand it.

The complete code:

#include <WString.h>

//Stores read analog values
int readLM35;
const int sensorAnalogPin = 0;
const float voltsToTemperature = 1.1 / 1023 * 100; // (1.1V supply / 10bit resolution) * (10 mV/°C = 1 V / 100 °C)
//Stores the temperature in °C
float temp;
//Averager
float temps[8];
byte position = 0;
float averageTemp;

void setup() {
    Serial.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);

    //For setting internal analog reference voltage to 1.1V
    analogReference(INTERNAL);
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    digitalWrite(LED_BUILTIN, LOW);

    //Measure temperature
    readLM35 = analogRead(sensorAnalogPin);
    temp = readLM35  * voltsToTemperature;

    //Save it
    temps[position] = temp;
    if (position == 7) {
        position = 0;
    } else {
        position++;
    }

    //Get average
    averageTemp = 0;
    for (byte i = 0; i < 8; i++) {
        averageTemp += temps[i] / 8;
    }

    //Write
    Serial.println(String(readLM35) + " => " + String(temp, 1) + " deg. C, avg. " + String(averageTemp, 1));
    delay(2500);
}

Example of output (note the first numbers - actual reading):

211 => 22.7 deg. C, avg. 22.5
186 => 20.0 deg. C, avg. 21.9
234 => 25.2 deg. C, avg. 22.7
173 => 18.6 deg. C, avg. 21.9
237 => 25.5 deg. C, avg. 22.6
185 => 19.9 deg. C, avg. 21.9
231 => 24.8 deg. C, avg. 22.4
193 => 20.8 deg. C, avg. 22.2
223 => 24.0 deg. C, avg. 22.3
206 => 22.2 deg. C, avg. 22.6
197 => 21.2 deg. C, avg. 22.1
225 => 24.2 deg. C, avg. 22.8
183 => 19.7 deg. C, avg. 22.1
240 => 25.8 deg. C, avg. 22.8

The cause is the low sinking capabilities of LM35 output. This makes the output sensitive to EMI. Yes, the output output impedance is stated as 0.5 ohms but only for sourcing current. The sinking current is limited to 1uA which is easily achieved by the environment noise.

You need to add a low impedance load between LM35 output and ground, can be 200 ohm as the data sheet recommends for heavy capacitive loads but I wouldn't go that far, might be 1k or 2k to avoid self heating errors.

No software only solution can solve this error.