How to improve the sampling rate of Arduino due ADC? I am now working on a project, which needs a cheap analog acquisition device with a sampling rate of no less than 5MHz. Before, I only used Arduino, and rarely operated the registers on Arduino. I hope to use Arduino due to complete it. I spent a lot of time researching and querying solutions, but it didn't succeed. I hope someone can help me.

I haven't used the Due, but I understand its ADC is rated for 1 MHz sampling.  If that's its absolute limit then you can't expect 5 MHz.  However, judging by the Unos which I have used, you may be able to push things by limiting the number of bits.  This gives a speed boost two ways, by shortening the time the ADC uses to acquire the data, and if you limit to 8 bits you have half as many bytes to move into memory.
Do not try to use more than one channel, since then you have multiplexer delays as well.
Also, you may want to skip interrupts and just sample in a tight loop. Using this loop trick doubles the useful ADC rate of the Uno, from 50 kHz to over 100 kHz. (You'll need to figure out the actual sample rate by reading the timer before and after the loop, then divide by the loop size and take the reciprocal.)


Using Li-Poly battery to run UNO + Adafruit data logger I want to power Arduino UNO+Adafruit data logger (https://www.adafruit.com/product/1141) with a 3.7V 2000mAh Li-Poly battery. I am providing an excitation voltage of 3V, through one of the digital pins and a potential divider arrangement, to a sensor which is providing output signal in analog (voltage) form. I am using ADC to read that voltage. My question is, since the battery voltage is going to drop during its operation, would the voltage output from the digital pin, and thus the potential divider, also drop? Could this voltage drop also affect the reference for the ADC?

You can't run the Arduino UNO directly from 3.7V.

You can use a boost regulator to step up to 5V and feed that into the 5V pin - in which case your question becomes null and void, since you are running at 5V, not 3.7V.

Or you can perform some hardware and/or fuse modifications and run the board directly from 3.7V into the 5V pin:

You will have to change the surface mount resonator to an 8MHz one instead of the normal 16MHz, or
Switch the clock to use the internal RC oscillator by reprogramming the fuses.

Either way you will then have to also modify the board configuration in the IDE to run at the new clock speed.

So given all that the simplest thing to do is to invest in a 5V boost regulator. Personally I'd suggest the LiPower Shield from Sparkfun. It also has a "fuel gauge" chip to monitor the batter charge.

Either that or scrap the Uno and invest in a development board that is designed to run from a Li-Poly / Li-Ion / LiFePO4 battery.


What's the difference between setting a variable outside a function and setting a variable inside a function? I'm programming C++ for arduino and today I have seen an example like this

void loop() {
    byte variable = 0; // << This variable is the question.
    //more stuff here
}

Is the same as this?:

byte variable = 0;

void loop() {
    //stuff here
}

If the answer is "no", my question is "why?".

Thanks for your time!

The difference is not only about where you set the variable, but about where you defined it as well.

Defined outside the function, it will have global scope and lifetime, meaning it is visible everywhere and it exists for the entire duration of the program.  If you then place an initializer inside the function, whatever value it had just before function-entry will be replaced by the initializer value.

If you define it inside the function (and without a "static" specifier) it only exists while that function is executing, and is only visible to code inside the function. Because it only comes into existence when the function is entered, you must initialize it within the function, somehow.

If you define it inside the function, but with a static specifier,

static byte variable = 0;

then it will exist for the entire execution of the program but will only be visible to code within the function. In addition, an initializer on its definition (as opposed to other assignments to the variable) will only be executed once, just before the program begins executing, and will not be executed within function.

Using local and static (as opposed to global) variables is considered good program-variable hygiene because it hides those variables (to a greater or lesser degree) from code that needn't and shouldn't be able see or alter them.


connection of led with dht and code combination Hi again? I saw my last question did not come out well, so let me rephrase it.
Ideally, my project is composed of 3 sensors: 2 dht-22 sensors and an mq-7 sensor.
For the dht22 sensors, I am using data pin connections 9 and 10 PWM on the Arduino mega 2560 board with their respective 10 kilo-ohm resistors, with 5v supply and ground connections.
The issue is that I want to set limits for both temperature and humidity for both sensors to be:  (16

#include "DHT.h"

#define DHT1PIN 9     // what pin we're connected to
#define DHT2PIN 10

#define DHT1TYPE DHT22
#define DHT2TYPE DHT22

// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht1(DHT1PIN, DHT1TYPE);
DHT dht2(DHT2PIN, DHT2TYPE);

void setup() {
  Serial.begin(115200);
  Serial.println("DHTxx test!");

  dht1.begin();
  dht2.begin();
}

void loop() {
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h1 = dht1.readHumidity();
  float t1 = dht1.readTemperature();
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();

  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (isnan(t1) || isnan(h1)) {
    Serial.println("Failed to read from DHT #1");
  } else {
    Serial.print("Humidity 1: ");
    Serial.print(h1);
    Serial.print(" %\t");
    Serial.print("Temperature 1: ");
    Serial.print(t1);
    Serial.println(" *C");
  }
  if (isnan(t2) || isnan(h2)) {
    Serial.println("Failed to read from DHT #2");
  } else {
    Serial.print("Humidity 2: ");
    Serial.print(h2);
    Serial.print(" %\t");
    Serial.print("Temperature 2: ");
    Serial.print(t2);
    Serial.println(" *C");
  }
  Serial.println();
}

Ps: LEDs used are 10mm.
For the MQ-7 sensor, this is it's code.

/* MQ-7 Carbon Monoxide Sensor Circuit with Arduino */

 const int AOUTpin=0;//the AOUT pin of the CO sensor goes into analog pin A0 of the arduino
 const int DOUTpin=8;//the DOUT pin of the CO sensor goes into digital pin D8 of the arduino
 const int ledPin=13;//the anode of the LED connects to digital pin D13 of the arduino

 int limit;
 int value;

 void setup() {
 Serial.begin(115200);//sets the baud rate
 pinMode(DOUTpin, INPUT);//sets the pin as an input to the arduino
 pinMode(ledPin, OUTPUT);//sets the pin as an output of the arduino
 }

 void loop()
 {
 value= analogRead(AOUTpin);//reads the analaog value from the CO sensor's AOUT pin
 limit= digitalRead(DOUTpin);//reads the digital value from the CO sensor's DOUT pin
 Serial.print("CO value: ");
 Serial.println(value);//prints the CO value
 Serial.print("Limit: ");
 Serial.print(limit);//prints the limit reached as either LOW or HIGH (above or underneath)
 delay(100);
 if (limit == HIGH){
 digitalWrite(ledPin, HIGH);//if limit has been reached, LED turns on as status indicator
 }
 else{
 digitalWrite(ledPin, LOW);//if threshold not reached, LED remains off
 }
 }

I am yet to buy a relay circuit to be able to connect it with the circuit using a , but for now I would appreciate it the scenarios highlighted for the sensors could be addressed and also, how the two codes could be combined to be one single code.
If there is any question, feel free to ask.
The project is for silo monitoring and control.

Only thing that gives people problems when combining two simple sketches are "delay" commands. There is just one "delay" so it's perfect.

Create new sketch
Paste everything that's not in a method from the two sketches.
Combine setup methods together by pasting first one and second one below.
Remove duplicated commands like Serial.begin(115200); from the method
Combine loop methods together by pasting first one and second one below.
Move code in loop to make the code visually pleasing (it's called the "smell" of code)

This should not be a big problem with those two particular sketches.
Please ask more precise questions as soon as you will have problems.


What does “LSB per degree per second” mean? I'm currently working with a digital output gyroscope. Its sensitivity is given as 120 least-significant bit per degree per second.

While every single component of that unit is easy to understand I don't quite get what it means altogether.

Can you explain it to me?

Let us say we have a number, "4025". The "most significant digit" of the number is the 4 in the thousands position, since it tells us the most about the magnitude of the number ("in the four thousands"). Consequently, the "least significant digit" is the 5 in the units position, since it tells us almost nothing about the magnitude of the number. "Most/least significant bit" is the same, except it applies to binary numbers (which the MCU cares about, of course; we can still use any radix we like to talk about them). So the device's output count can change by up to 120 per degree per second.


Can SPI and serial.begin be used at the same time? I have two modules where I want to control them through a single Arduino UNO.

I guess Serial.begin(9600) uses serial port and UART. But Im not sure about SPI.

Can I use SPI library hence the SPI communication together with serial communication(serial.begin) at the same time to communicate with two different modules?

Yes. UART and SPI are completely different things.  One uses pins 0/1, the other uses pins 11/12/13, and they use separate hardware and control registers inside the chip.


Attiny45 wake by Software Serial I would like to wake Attiny45 from sleep by Serial communication. RX is connected to pin 7 (D2). When I try to use PCINT0_vect routine, I get an error "multiple definition of `__vector_2'" so it looks like Software Serial already uses "ISR (PCINT0_vect)" and pin change interrupt.

So my question is, will incomming communication wake Attiny from sleep?

Is there a possibility to change CLKPR when Attiny starts receiving? For example I set clock divider to 256 for the majority of time and when it starts receiving it changes back to 1.

I was thinking of something like this:

void loop() {
 if (SWSerial.available()>0) {
   noInterrupts ();
   CLKPR = bit (CLKPCE);
   CLKPR = clock_div_1;
   interrupts ();
 }
//other code here
}

I don't mind loosing some bytes, but I need to low Idle current as much as possible.
Thank you.

Question #1: Can a change on pin 7 wake from sleep?
Yes. The lowest power mode for this chip is Power-down, and you can wake from this state with a pin change interrupt. Assuming that the soft-serial code you are using already enables interrupts on the pin for its own purposes, then you should just be able to sleep and the part will wake on the next pin generated interrupt.
Depending on what compiler/libraries you are using, something like this...
include <avr/sleep.h>

...

set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu();
//We will only reach this line after an interrupt has occured

...should work. Note that an interrupt when waking from sleep takes longer than when already running, so you'll need to check your soft serial library to see if it will possibly garble the first bit received- it will depend on how they do their timing.
If you really want the lowest power possible, you could write your own soft serial code that drops the processor to idle in between serial bit transitions. Depending on how much time you will be spending actually receiving data this could drop overall power consumption dramatically.
For low baud rates, I could imagine writing serial receive code that woke on an interrupt from the start bit, and used the timer running at a very low clock speed to wake up in the middle of each data bit and very quickly sample and shift the bit in before going idle again. Done right, this could dramatically drop the power used while receiving.
Question #2: Is there a possibility to change CLKPR when Attiny starts receiving?
Yes. You can change the prescaler any time, but note that...

The clock is not running at all during power-down mode, so there is no reason to scale back before going to sleep - it will just mean that it takes you longer to wake up when a change happens.

Sometimes scaling back the clock can actually use more power, especially when sleeping is envolved. A processor running 1/2 as fast uses more than 1/2 as much power, so it is often more power efficient to wake up at full speed, do what you have to do as fast as possible, and then get back to sleep.

The best option for you will depend on factors like how often will you be receiving data compared to waiting for data, and how much work you wan to put into getting optimal power usage. This chip can be extremely power efficient, but it can take work to take advantage of it.


Device Security - EEPROM data I'm writing code for Arduino that I plan to distribute. But I worry about piracy (the .HEX can extracted from the board and reuploaded to another).

With that in mind, I am storing data to the EEPROM.

Since I am storing data to the EEPROM, can the data be extracted in some way?

Nothing is 100% secure. For example, EEPROM and flash can be read using techniques like Scanning Probe Microscopy & Scanning Electron Microscope, even if the security bit is set. IMO, the goal to safely securing your data is to make it extremely hard. You should take a look at the ATAES132a from MicroChip.

  The first device in the AES family, the ATAES132A, is a high-speed, high-security, 32K Serial EEPROM that enables authentication and confidential nonvolatile data storage

It also boast a tamper resistant hardware

  The ATAES132A device contains physical security features to prevent an attacker from determining the
  internal secrets. ATAES132A includes tamper detectors for voltage, temperature, frequency, and light, as
  well as an active metal shield over the circuitry, internal memory encryption, and other various features.
  The ATAES132A physical design and cryptographic protocol are designed to prevent or significantly
  complicate most algorithmic, timing, and side-channel attacks.


Arduino Mega 2560 from .org- which IDE works? My personal choice is to purchase from the .cc (or adafruit) for new boards. YMMV.  Craigslist locally of course has generic and .org boards now and then.

If I get a .org board on craigslist, will I need to use their fork of the IDE for the board to be recognized by the IDE?

My feeling is "yes" but I wanted to confirm.

A board there just now is Arduino mega 2560 from the .org.  Would I have to use their flavor of the IDE?

Thank you for your thoughts- photo of the board I am considering is attached.

Arduino.org and arduino.cc have come to a agreement.
As such all incompatibilities that exist (I don't think they exist for this mega board) will be solved with next version of the Arduino IDE as if it is a board of their own.


Powering potientiometer/button with a digital pin When I read articles/tutorials about the Arduino Uno, the potentiometer and button always get power from the 5 V pin instead of from digital pins.

May I know whether the two components above can be powered by digital pins?

What is the situation that the components must only get power from 5 V pin instead of digital pins?

You can likely use an I/O pin as an output to "power" fairly high-impedance devices such as pullup resistors for buttons, or even potentiometers of moderate to high total resistance.
A reason you might wish to do so would to be able to stop the device from draining power while the entire system is in a low-power sleep mode, or to otherwise disable it beyond merely ignoring its input.
However, it's worth noting that powering an analog device such as a potentiometer from an I/O pin is likely to inject noise and full scale voltage uncertainty into the signal so derived, as the output voltage under load may be neither the same as the supply rail, not "quiet".
And, of course, you must not attempt to use an I/O pin to power lower-impedance (aka more "power hungry") loads via an output pin.  Generally, active devices should not be powered in this way - especially ones such as radio transmitters, other microcontrollers or complex logic functions, ultrasonic transmitters, and definitely not motors, relays, or solenoids.


How to send int array with ESP8266 http post request? I'm reading RFID cards' UID with an ESP8266 and trying to send that information to my web server hosted on a Raspberry Pi. I'm currently storing the UID in an int array, but the http.POST(); function takes a string input. I tried adding each UID digit together, but that doesn't work either.
How would you go about sending the uid in the request?
My code:
    /*
    Created by TheCircuit
*/

#define SS_PIN 4  //D2
#define RST_PIN 5 //D1

#include <SPI.h>
#include <MFRC522.h>

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

const char* ssid = "****";
const char* password = "****";
const char* serverName = "****";
int RELAY = 2; //D6

int UIDs[1][4] = {
  {83, 111, 39, 47}
};

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

void setup()
{
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522

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

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

boolean compareUIDs(int a[4], int b[4]) {
  for (int i = 0; i < 4; i++) {
    if (a[i] != b[i]) return false;
  }

  return true;
}

void loop()
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

  // mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

  int UID[4];
  for (int i = 0; i < 4; i++) {
    UID[i] = mfrc522.uid.uidByte[i];
  }

  Serial.print(UID[0]);
  Serial.print(" ");
  Serial.print(UID[1]);
  Serial.print(" ");
  Serial.print(UID[2]);
  Serial.print(" ");
  Serial.print(UID[3]);
  Serial.println();

  for (int i = 0; i < sizeof(UIDs); i++) {
    boolean success = compareUIDs(UIDs[i], UID);
    if (success) {
      Serial.println("ACCESS GRANTED");
      digitalWrite(RELAY, LOW);

      if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;

        // Your Domain name with URL path or IP address with path
        http.begin(serverName);

        // Specify content-type header
        http.addHeader("Content-Type", "application/json");

        int httpResponseCode = http.POST("UID GOES HERE");

        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);

        // Free resources
        http.end();
      }

      delay(2000);
      digitalWrite(RELAY, HIGH);
      return;
    }
  }
}

You could use the (awesome) ArduinoJSON library, but likely overkill for this app. I found it more useful to parse JSON than to construct it.
You could simply print to a buffer and the POST that:
char payload[MAX_PAYLOAD];
sprintf(payload, "{\"uid1\":%d,\"uid2\":%d,\"uid3\":%d,\"uid4\":%d}", UID[0], UID[1], UID[2], UID[3]);

http.POST(payload);

You would #define MAX_PAYLOAD with a value that will be sufficient to hold all the information.
Notice that sprintf allows you to use any formatting options you want (e.g. hexadecimal, etc).
If you wanted to send it as an array:
sprintf(payload, "{\"uid\":[%d,%d,%d,%d]}", UID[0], UID[1], UID[2], UID[3]);


Hard-resetting an arduino I need to hard reset (or seriously breathe life into) a stuck Arduino clone (Sunfounder UNO) which doesn't get recognized by Windows (error 43) after installing the wrong sketch. I am using the latest Arduino toolset and, before today, the setup was functional.

The problem is probably that I am writing to the serial in the setup() section like this:

void setup() {
  pinMode(a0, OUTPUT);
  pinMode(a1, OUTPUT);
  pinMode(a2, OUTPUT);
  pinMode(b1, OUTPUT);
  pinMode(m0, OUTPUT);
  pinMode(m1, OUTPUT);
  pinMode(m2, OUTPUT);
  pinMode(OK, OUTPUT);
  pinMode(KO, OUTPUT);

  pinMode(carry, INPUT);
  pinMode(result, INPUT);
  delay(1000);

  Serial.begin(9600);
  Serial.write("Arduino Tester v. 0.1\n");
}

Arduino seems to be running the code. The problem is that Windows doesn't recognize it and doesn't set up a COM port for it.

So: i'd like to nuke it and restart from scratch.

How is this done?

The word "clone" immediately rings alarm bells.

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

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

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

As I say that is unlikely.

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


3.5" TFT LCD Display is not working with Arduino Mega 2560 R3 Even I can't do similarly with my 2.4" TFT LCD in here still: 2.4" TFT LCD Shield isn't working on Arduino Mega

Now, I have bought 3.5" TFT LCD display for my Arduino Mega 2560 R3 to try whether I could run the screen or not, and it is not working now! I am so depressed and angry for these two's misbehaviors. I have already checked website and a lot of Arduino IDE code examples and libraries such as UTFT.h, UTouch.h, UTFT_MEGA, UTFT_CTE, TFTLCD. I tried these and I can not run my 3.5" screen. Where am I faulty? There is something below the screen shield: www.mcufriend.com and 3.5" TFTLCD for Arduino 2560. Are there any basic code or have anyone tried to run Mcufriend's displays correctly?

http://www.henningkarlsen.com/electronics/library.php?id=51

Download hennings new UTFT library.

in myGLCD define R61581 as this is the driver chip for 3.5 display.

Regards!


Mapping string values I have a bunch of thermometers (between 1 and 128). The thermometers have an internal OneWire ID such as "28edce1e500e5" and it is not readable by humans.

Normally I would make an associative array like this:

map["28edce1e500e5"] = "Temp1";
map["28ffd33b9116420"] = "Temp2";

Serial.print(map[printAddress(allDevices[i])]);
Serial.print(" : ");
Serial.print(sensors.getTempC(allDevices[i]));

But it looks like the only hashmap library for Arduino is no longer supported and appears to be quite expensive.

The solution does not have to involve associative array.

The values are populated from a JSON file, loaded from an SD card.

I'm looking for a solutiuon to the problem, not a way to implement an associative array. (Unless that's the best way to solve the problem)

Make a struct containing the name and id.

struct device{char[MAX_ID_LENGTH] id; char[MAX_NAME_LENGTH] name; }

Then store the those pairs in an array which you can have sorted by one field or the other. That way you can binary search on that field.


Picking the time a led on an arduino should turn on, via android I have created an app which is connencted to my arduino via bluetoth. The user of the app can turn on and off a led which is connented to the arduino. But I want to take it a step further... I want the user to be able to give the time and the date when the light should turn on and additionally the time that sould pass until the led turns off again. Is it significantly harder? I have thought of using an already existing alarm app but I am pretty stuck, so could anyone give me some suggestions?

Make the Bluetooth message send how many seconds it is until the light should be on, and how many seconds it should stay on.

Then the arduino code can just handle everything with millis(). You know the millis() you were asked to start, add the delay, and wait for that time.

Delays less than 50 days (wrap around of millis ())  take no effort to handle it you embrace the overflow.

Handling delays greater than 50 days can be achieved by watching for millis() overflows and counting them. You could also make your own timer based counter.

If you care about recovery after power loss / reset you could use an RTC module. Depending on its complexity, it could interrupt you or you poll it to check for a date you saved to Arduino eeprom.  You would have to consider what the system should do it the alarm would have happened during the power loss...


Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock Burning question:

So, I'm trying to burn the Arduino Leo bootloader onto a ATmega32U4 that's on 3.3V and the internal 8MHz clock.  Do I have to modify and rebuild the bootloader to set the fuses correctly, and can this be done with AVR Studio?

All of the references on doing this are dated.  The folder structure for the Arduino IDE has changed. I've done it in the past with 5V 16MHz 32U4s using an Arduino as ISP, but never with the AVRISP mkII on the Arduino IDE.

On the good side, I do have it up and running with Atmel Studio.

Thanks!

If you have an appropriate crystal attached then you can do this in the Arduino IDE. Select your board and programmer in the IDE menu, connect the programmer to the board, and choose Burn Bootloader from the menu. This will both burn the prebuilt bootloader image and set the fuses in a single operation.

Note that you cannot use USB on the '32U4 if you are running off either a ceramic resonator or the internal oscillator, and so you should not attempt to use the Leonardo bootloader in either case.


Detect current in car handbrake circuit Using Arduino, how can I detect that the switch is on? I have access to the wire within the red rectangle only. That's because the switch is closely connected to the car body (ground). When the handbrake is up, the switch is pushed by a coil to touch car body and close the circuit. And when the handbrake is down, the switch go away from the car body and the circuit is open.

If you truly only have access to the red rectangle content, and not the Ground or +12V supply, you could use an opto-isolator, assuming you can use enough of the wire in the red rectangle to be able to form a voltage divider to get at least 1-2 mA through the input side of the opto.


Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding I have a Arduino Nano (Sainsmart) that I'm trying to upload a sketch to. Under the Arduino IDE, the device selected was Arduino Nano w/ ATmega328.

However uploading the sketch gives me the error

avrdude: stk500_recv(): programmer is not responding

I tried both USB ports (/dev/tty.usbserial & /dev/cu.usbserial) but the same error persist. The Arduino is connected to a Macbook Air via the USB cable, and the PWR LED indicator light on the Arduino is turned on and the L indicator LED blinks. There was no problem uploading to a Arduino Uno.

Retried after installing the latest FTDI drivers (MAC OSX, x64, v2.2.18, FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg) from http://www.ftdichip.com/Drivers/VCP.htm. However that did not help.

What could have gone wrong?

Know this is old but I ran onto it during my search for Nano(V3)'s not uploading so thought might help someone else.  Problem is the bootloader - Arduino IDE BUT I Found an easy solution (right under my nose).

I realized that my nano's had been uploading just fine then I had finally updated the Arduino AVR Boards from 1.6.20 to 1.6.21.  I didn't think there was any problems because it still showed my Nano and ATmega328 etc in the board manager after the change.

But the new boards manager has a new ATmega328 processor choice for the Nano. I changed processor: In the Arduino IDE select TOOLS > PROCESSOR > pulldown menu from ATmega328P to  "ATmega328P (Old Bootloader)".

Since then, I have uploaded many programs to several different Nano's V3 (Prolofic interace Chipset) without issue.


What else is consuming Data Segment reported by avr-size? I am facing a low memory available problem in arduino. I am compiling a big sketch for arduino mega 2560.
Analysing a .elf file, the avr-size tool gives:
text    data     bss     dec     hex filename
68524   4392    2560   75476   126d4 C:\Users\LEAN...

And the avr-nm (avr-nm doc) shows only variables with t, T, b, d and B. The following is how the command is executed (the output is being saved in a file called test.txt).
   avr-nm -a -td -C -l --size-sort -r x.elf >> test.txt

Then, I perform a sum to confirm the avr-size result using this Python script:
f = open("test.txt", "r")
lines = f.readlines()
f.close()

su = 0
dsum = 0
bsum = 0
tsum = 0
gsum = 0
for line in lines:
    #print(line, end="")
    s = line.split()
    try:
        val = int(s[0])
        su = su + val
        if(s[1].lower() == 'b'):
            bsum = bsum + val
        if(s[1].lower() == 'd'):
            print(line)
            dsum = dsum + val
        if(s[1].lower() == 't'):
            tsum = tsum + val
        if(s[1].lower() == 'g'):
            gsum = gsum + val
    except:
        print("ERR: ",s[0])
print("\n\nSIZE: ", su)
print("SIZE d/D: ", dsum)
print("SIZE b/B: ", bsum)
print("SIZE t/T: ", tsum)
print("SIZE g/G: ", gsum)

and the sum result of each var type is:
SIZE:  71015
SIZE d/D:  135
SIZE b/B:  2560
SIZE t/T:  68320
SIZE g/G:  0

The question: Here d/D sums is 135 bytes. So, why the data segment reported by avr-size is 4392 bytes? how to find out what is occupying this space?
Best Regards.
EDIT
It must be a Joke!
I have a lot of like this in the code:
Serial.print("QTDE REG: ");

Just changing for this:
Serial.print(F("QTDE REG: "));

I have reduced by 10 the .data size!
So, in this way Serial.print("QTDE REG: "); "QTDE REG: " is stored as a global variable?? I thought the compiler would save locally.
EDIT 2
I have an advance running avr-objdump -s -j .data x.elf as suggested by Edgar below. Now I see that all my string literals are in data! For example:
void myFunction(){
    ...
    sprintf(buf, "{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},", (int)settings.treg);
    ...
}

avr-objdump -s -j .data x.elf shows:
 800660 2c007b22 6e616d65 223a2249 6e746572  ,.{"name":"Inter
 800670 76616c6f 20646520 52656769 7374726f  valo de Registro
 800680 73222c22 76616c75 65223a22 2564222c  s","value":"%d",
 800690 2022756e 6974223a 2243227d 2c007b22   "unit":"C"},.{"

EDIT 3
As commented, all string literals are saved in the (SRAM). So, the problem is, I have a lot of strings literals spread across different functions. How to save this amount of SRAM? Note that using F() for sprintf gives compilation error.
Is there any way to put the literal in stack (release memory when function returns) and not in the global area? Is F() the only solution?
============ SOLUTION ============
For now, I have found this solution: use sprintf_P with PSTR(...) in the same way of F(...):
sprintf_P(buf, PSTR("{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},"), (int)settings.treg);

I will test more...
Thanks for all clarification!
Best Regards!

Most of the missing data section is probably made of string literals.
When you write something like
Serial.println("Hello, World!");

the string "Hello, World!" is implemented by the compiler as an
anonymous array of characters, and the address of this array is
provided to the println() method. Since the array is anonymous, it
doesn't show up in the output of avr-nm. You can check that this is
the case by looking at the actual contents of the section:
avr-objdump -s -j .data x.elf

And you can avoid this by wrapping the strings in the F() macro:
Serial.println(F("Hello, World!"));

This has the effect of keeping the string in flash, and passing the
flash address to the println() method. Note that this is actually a
different, overloaded method, that knows how to retrieve the character
data from flash.

Edit: Adding some clarifications.
All this complexity about flash vs. RAM storage comes from the fact that
the AVR uses a Harvard architecture, where RAM and flash are
in different address spaces, accessed through different memory buses
using different machine instructions. Unlike C, the C++
language has no notion of address spaces, and the compiler simply
assumes that any pointer to function holds a flash address, whereas any
pointer to data holds a RAM address.
Per the rules of the language, a string literal has the type
const char *, and a function that should be able to accept a string
literal should take a const char * parameter. Since these are pointers
to data, when you dereference them the compiler emits the machine
instructions that are appropriate for reading RAM. This is why the
compiler puts all string literals in the .data section of the flash: at
program startup, the C runtime copies them to the .data section of the
RAM, making them accessible to those machine instructions.
The current solution to avoid this useless copy involves a bunch of
preprocessor macros like F(), PSTR(), PROGMEM,
pgm_read_byte()... that expand to compiler extensions or inline
assembly. These allow you to pass around the flash addresses of string
literals disguised as regular data pointers. These pointers should never
be dereferenced with the regular operators of the language (* and
[]), but only through the pgm_read_*() macros. And they should only
be given to functions that do expect these kind of pointers, like
sprintf_P() or Print::println(const __FlashStringHelper *), which is
the println() that gets invoked when using the F() macro.

Is there any way to put the literal in stack

Yes, there is, but it has to be done explicitly:
PROGMEM const char greeting[] = "Hello, World!";

void say_hello() {
    char stack_copy[strlen_P(greeting)+1];
    strcpy_P(stack_copy, greeting);
    Serial.println(stack_copy);
}

As you have already noticed, it is preferable to not put the strings in
RAM at all, and instead use functions like sprintf_P that expect
flash-based strings. However, if you need to use a library function that
expects a RAM-based string, you can use this trick to avoid permanently
committing it to RAM.


What is more power efficient: GPRS or SMS for a GSM sim Arduino application? I have a GSM shield for my arduino and am wondering the most efficient way to receive and send data to the cloud.

The specific project I am looking to accomplish is starting my car from a web browser (or custom built ionic mobile app) that will send data to my GSM shielded arduino and the arduino then "press the button" of an already installed remote car starter (which is all probably in the car's trunk).

What is more power efficient, sending and receiving a SMS (text message) or sending and receiving data via GPRS?

What is best when considering strategies like sleep, or deep sleep cycles?

Looking at it logically SMS is probably the most power efficient method.

The thinking is this:

With SMS:

The shield sits there connected to the mobile network doing nothing much
An SMS is sent by you which travels through the mobile network
The SMS is sent from the mobile network to your GSM shield which then wakes up and does things with it
The shield sits there connected to the mobile network doing nothing much

With GPRS:

The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service and sees a request is available
The shield downloads the request
The shield acts on the request
The shield goes back to querying the on-line service
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
... etc ad nausium ...

As you can see with SMS the onus is on the mobile network to send the data to the shield, whereas with GPRS the onus is on the shield to keep querying an on-line service to see if there is any requests to handle. There is no way of you sending data to the shield directly (indeed, most GPRS services include at least one layer of NAT gatewaying). So your shield has to be active all the time and constantly looking at something online - not only power hungry, but potentially financially expensive too.


analogWrite is not working - while trying to control DC motor speed I'm trying to control the speed of DC Motor using

Arduino R3
NPN Transistor (2N2222A331)
10k potentiometer
2M ohm resistor
Diode

I'm not using L298N and I'm also not using L293D.

DC motor is running, but the speed of DC motor doesn't seem to change with changes in potentiometer.
Circuit seems to be alright as DC motor is running.

The code is as follows

int potPin = A0;
int motorPin = 9;
int potValue = 0;
int motorValue = 0;

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

void loop()
{
 potValue = analogRead(potPin);
 motorValue = map(potValue, 0, 1023, 0, 255);
 analogWrite(motorPin, motorValue);
 delay(2);
 Serial.print("potentiometer = " );
 Serial.print(potValue);
 Serial.print("t motor = ");
 Serial.println(motorValue);
}

Whenever I tweak the Potentiometer, I can see the relative changes from Arduino  "Serial Monitor" (both Potentiometer values and Motor values), but the speed doesnt seem to change physically.

Things that I tried

tried different combinations of resistors(100,1k,10k,1M,2M ohm) so as to vary voltage that goes to DC Motor
tried to check with different Output pins like 3,5,9

Nothing works, DC motor speed isn't changing.

this leads me - to believe that, my analogwrite isn't working.
please help me understand as to what i'm i doing wrong?

The Circuit is as follows

Well, 2M resistor to the base? If the motor is running with that, the transistor must be broken (shorted). Just try to check if the motor is running with disconnected base.

You can also check PWM output by connecting LED with resistor (no, not 2M ohms, just about 330 ohms). For the transistor 1k should be sufficient maybe little less (depends on motor current and h21e amplification coeficient).

Also there are some versions 2N2222 with emitter and collector swapped. And reversed transistor has much lower current amplification coeficient.

And I hope you are using external power supply, USB is not a good idea. Starting power is usually way too much for the overcurrent protections.

Anyways, this works for me:

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

void loop() {
  analogWrite(9, map(analogRead(A0), 0, 1023, 0, 255));
  delay(100);
}

2N2222A + 1k + PC FAN + 12V Fan Power supply.

Connections: E -> Gnd, C -> FAN-, FAN+ -> 12V, 12V GND -> Arduino GND, Pin 9 -> 1k -> B

On the Arduino side 47k trimmer and the USB


how to send input values from host computer to arduino how to send input values from host computer to arduino,such that speficing the number of rotations for a stepper motor etc

The easiest method is to use the serial communication. Use the sample code at http://arduino.cc/en/Tutorial/SwitchCase2, upload that to an Arduino, start the serial monitor (Ctrl+Shift+M), make sure the baud rate is the same as set in the code (9600 in this case), then write the commands and send them to the Arduino.

Edit
Since the serial characters are usually read one by one you need a character that will signal the end of the string. This is usually a newline \n, but can be any character you choose (and can be sent to Arduino).

Sample code (processString would be your function to do something with the string):

char buf[64];
byte cnt = 0;
void loop()
{
    while (Serial.available()>0) {
        byte c = Serial.read();
        // Check for terminator character or the size of buffer
        if (c == '\n' || cnt >= 63) {
            // Add the terminating 0
            buf[cnt] = 0;
            // Process the full string
            processString(buf);
            // Prepare to read the next string
            cnt = 0;
        } else {
            // Not terminator - add to string
            buf[cnt++] = c;
        }
    }
}


Microcontroller controlled power supply Can anyone assist me to make a power supply whose output voltage will be controlled by an Arduino, with the latest voltage setting automatically saved in non volatile memory?

I am in an OJT (On the Job Training Scheme). I was given a task to make a Arduino controlled voltage variable power supply whose outputs can be switched between several preset values using pushbutton control.   It's like switching between two different outputs when a designated button is being pushed.

Here is what I have done so far. I made an LM317 based power supply with the output voltage controlled by a potentiometer. I followed this youtube tutorial. It works well but I was ask to upgrade it.

Instead of using a potentiometer to adjust the voltage, I wish to use switching buttons to choose between two or more preset voltage levels. Each switch buttons have their corresponding voltages.

This link may also be relevant.
Code is given below the circuit diagram.
ARDUINO AS A POWER SOURCE ALTERNATOR

If you want to output preset voltage levels in distinct steps, rather than an 'analogue' range from X volts to Y volts, then the answer is in the datasheet for the LM317:

Connect each of the INPUTS through a 1k base resistor to your Arduino pins. Selecting different values for all the resistors will of course allow you to vary Vout by turning each transistor on or off, by themselves or together. You can use any standard transistor: 2N3904, 2N2222, BC548, etc., but I might elect to use a (low power) MOSFET like a BSS138 instead (and omit the base resistor). Of course you can use add more resistor/transistor lines if you want more output options. I recommend using R2 so that Vout is always limited, otherwise - if Vin is quite high - you may damage whatever Vout is powering due to some runaway voltages.

Calculating resitor values is your mathmatical challenge. If you really apply some brainpower you can change Vout in linear steps with minimal Arduino pin usage:

'Input' states            Vout
  A  B  C  D            (/volts)
  0  0  0  0              5.00  [Vmax set by R2]
  0  0  0  1              4.75
  0  0  1  0              4.50
  0  0  1  1              4.25
  0  1  0  0              4.00
   ...  ...                ..
  1  1  1  0              1.75
  1  1  1  1              1.50

This shows that with N Arduino pins you can have (N^2)-1 levels. Using R2 gives your final level whne all INPUTs are off.

If you want to be able to drop Vout down to 1.25V, add transistor/MOSFET that connects R1/ADJ straight to ground. Turning this on will drop Vout to 1.25V, irrespective of the state of the other INPUTS.


Sketch Upload to LinkIt ONE Timeout I've just bought a new LinkIt ONE IoT prototyping board, and I'm having trouble getting started with it.

I'm working on a mac. I've installed the LinkIt ONE SDK onto my Arduino IDE as specified in the instructions here: http://labs.mediatek.com/fileMedia/download/5fed7907-b2ba-4000-bcb2-016a332a49fd

When I go to upload my first sketch to my board, the sketch compiles and goes through uploading, but before it uploads, it stops uploading and the Arduino IDE perpetually tells me "Uploading...". When I look at the console below, it's telling me this:

[txd] AT

[txd] AT

[medrv]: Time out call back

[error] time out
[medrv]: Kill timer, event is AT_TIMEOUT

I've read some forums about an issue similar to this on the MediaTek website, but they don't help with the issue on the Mac. The ability to use LinkIt ONE on a Mac is new only this month, so I believe if we come up with a fix for this issue, it will help lots of people in the future who have this similar problem.

Disclaimer: I do not have access to one of these devices to test this on.
Section 3.4.1 of LinkIt's developer's guide (which you linked to) seems to indicate that it is necessary to install COM port drivers on OS X before you can communicate with the board. The [txd] report is communication from your computer to the board, so it seems like you are never establishing a connection. The suggestions in the developer's guide are as follows:

If you are using a LinkIt ONE development board on Mac OS X 10.10, then a USB driver is required to enable connectivity with and firmware updates on the LinkIt ONE development board. The OS X 10.10 built-in generic CDC ACM USB driver is not compatible with three ports available on the LinkIt ONE development board. The steps to install a custom driver to enable the BROM port for Firmware Updater are as follows:

Extract the content of the zip file available in LinkIt ONE SDK software’s Driver folder (see 2.3.2, “Installing LinkIt ONE SDK”) named MacOS_USB_COM_Driver_BM_xxx.xx.x.zip.

Run the installation package (BMCDCACM_Driver_v115.05.0.mpkg) and click Next to install it.

Wait until driver installation has finished, then restart your Mac.

BROM USB driver installation is now complete and you have access to the MTK USB Serial ports.


Uno doesn’t get enough power from 5v barrel connector. Why? I’m using a 5v 20a power supply run through a barrel connector into an Arduino Uno to control an LED strip. When only the barrel is connected, the green light on the Uno comes on but the yellow light lights dimly for a few milliseconds then goes dark. The light strip doesn’t light at all. When a USB is also connected, the board lights up fully (green and yellow LED) and the LED strip runs through its routine.
I’m making this as Christmas lights on a tree outside so I want it to run on the stand alone power supply. Why doesn’t the barrel work on 5v?

Voltage Drop
Well, if you put 5V into your barrel jack, your UNO's onboard 5V regulator is going to drop that down to 3.5V or so.  You must have more than 5V into the regulator to get 5V out of it.  This is referred to as the regulator's "drop out" voltage.
The specs for an UNO say to power it from at least 7V for that reason.
As an experiment you can power it this way without your lights attached and measure the "5V" header to GND to see this happening.
Power Dissipation
Linear regulators like that found on the UNO are not efficient. They waste energy as heat in proportion to the current through it and voltage dropped by it.
If you provide it with 7V at the regulator and your project draws 0.5 amps from the regulator, you will try to generate 0.5A * (7V - 5V), that is 1 Watt of heat.  Your regulator can probably dissipate half that with how it's mounted on the UNO and normal ambient air temperature.
Note this situation gets worse if you put 12V (for example) into the barrel jack, as you'd be dropping 7V across the regulator.
Many linear regulators have thermal overload protection built into them.  They'll stop producing as much voltage at the output as they heat up to try to survive the event.  And that's likely what you're seeing if you're trying to power your christmas lights from the regulator.
If you want to see this yourself might try very briefly tapping the regulator with your finger; it may be blazing hot.  You might just dampen your finger and hold it near the regulator's surface to feel the heat coming off of it.
You will more than likely need to route power around the Arduino board to your lights to prevent this.


Arduino GSM Shield NET and STATUS led turn off after a few seconds #include <GSM.h>

// PIN Number
#define PINNUMBER ""

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

// Save data variables
String IMEI = "";

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

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);

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

  // connection state
  boolean notConnected = true;

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

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

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

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

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

Results:
When I run the program, I can see the "GSM networks scanner" message appear on my serial monitor, but it does not display anything else after that. Also, the NET and STATUS LEDs turn off after some few seconds when the program starts running. I already made the minor adjustments necessary for the Arduino Mega, and the power supply is temporarily from the USB port of my laptop connected to the Arduino Mega. I am using a SIM card that has been activated.

I think my program stops at this stage:

  // connection state
  boolean notConnected = true;

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

P.S. when I run the program without inserting a SIM card, the NET and STATUS LEDs keep on working (NET is blinking, while STATUS remains ON)

I tried this program as well https://www.arduino.cc/en/Guide/ArduinoGSMShield#toc9
and it has the same problem (i.e. stops at the same stage as the previous program)

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

This is the code that worked out with me:

#include <GSM.h>

#define PINNUMBER ""

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

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

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

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

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

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

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

void sendSMS(){

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

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

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


Request for member is Non-class type Im getting this error:

iotHook.ino: In function 'void setup()':
iotHook:13: error: request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'
request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'

When I try to lunch my begin function of my class:

class Esp8266 {

  public:
    Esp8266();
    void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom);
    ...
  private:

    HardwareSerial *wifiCom;
    HardwareSerial *debugCom;
    ...

}

Esp8266::Esp8266() {
}

void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) {
  this->wifiCom = wifiCom;
  this->debugCom = debugCom;

  this->debugCom->begin(115200);
  while (!this->debugCom) {
  ;
  }
}

EDIT 1:
Updated image with new code

Why is not picking up the begin function?

Your current problem is that the USB Serial interface of the Leonardo isn't a hardware serial device, it's a CDC/ACM device, and the class for that isn't HardwareSerial, it's Serial_.

So you can't pass it to a function that expects a HardwareSerial.

What you should be using, instead, is the Stream class.  That will allow you to pass any object that is based on the Stream class, such as HardwareSerial, Serial_, Client, etc.  Many different things, including serial and networking protocols, use Stream as their base class.

It does have the down side, though, that you have to initialize the Stream objects in your sketch (that is, do the Serial.begin(...) and Serial1.begin(...) in your sketch not your class) because the Stream class doesn't have the concept of a baud rate, and so no begin(baud) function.

This is what I mean:

class Esp8266 {

public:
    Esp8266();
    void begin(Stream &wifiCom, Stream &debugCom);
private:

    Stream *_wifiCom;
    Stream *_debugCom;

};

Esp8266::Esp8266() {
}

void Esp8266::begin(Stream &wifiCom, Stream &debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;

    while (!_debugCom) {
        ;
    }
}

Esp8266 esp;

void setup() {
    Serial.begin(115200);
    Serial1.begin(115200);
    esp.begin(Serial, Serial1);
}  // end of setup

void loop() {
}  // end of

Note, as well, my use of pass-by-reference (Stream &whatever) so you don't have to pass a pointer in your begin function.  Also notice the use of unique variable names in the class (I always prefix my member variables with _) so you don't have to keep putting this-> in everywhere.

To be able to move the .begin() function inside your class you will have to use both HardwareSerial and Serial_ object types within your class.  There's two ways this may be done.

First is dynamic casting:

void Esp8266::begin(Stream &wifiCom, Stream *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;

    HardwareSerial *hard;
    Serial_ *cdc;

    if (hard = dynamic_cast<HardwareSerial*>(_wifiCom)) {
        hard->begin(115200);
    } else if (cdc = dynamic_cast<Serial_*>(_wifiCom)) {
        cdc->begin(115200);
    }

    if (hard = dynamic_cast<HardwareSerial*>(_debugCom)) {
        hard->begin(115200);
    } else if (cdc = dynamic_cast<Serial_*>(_debugCom)) {
        cdc->begin(115200);
    }

}

I haven't tested this, and I don't know if the Arduino's cut-down C++ library is even capable of it, but it's worth a try.

The other method is to overload the .begin() function of your class with multiple versions that take different parameters:

void Esp8266::begin(Serial_ &wifiCom, HardwareSerial *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;
    wifiCom.begin(115200);
    debugCom.begin(115200);
}

void Esp8266::begin(HardwareSerial &wifiCom, HardwareSerial *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;
    wifiCom.begin(115200);
    debugCom.begin(115200);
}

void Esp8266::begin(HardwareSerial &wifiCom, Serial_ *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;
    wifiCom.begin(115200);
    debugCom.begin(115200);
}

You're still storing them internally as Stream objects in all cases, but within the begin() function itself you also have them available as their child classes.  It does mean you have duplicate code copied between the different versions of begin().  You could modularize it a little more though by moving the duplicated code into functions which would only need to be duplicated twice, not three times - one to act on a single Serial_ object and one to act on a single HardwareSerial object:

void Esp8266::initSerial(Serial_ *ser) {
    ser->begin(115200);
}

void Esp8266::initSerial(HardwareSerial *ser) {
    ser->begin(115200);
}

void Esp8266::begin(Serial_ &wifiCom, HardwareSerial *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;
    initSerial(&wifiCom);
    initSerial(&debugCom);
}
... etc x3 ...


Why does the serial monitor needs to be repeated a command? I am experimenting with the serial monitor in an Arduino Uno. My project consists in a simple LED turning on and off at will with the commands "ON" and "OFF" respectively.

To achieve this, I use an HC-06 Bluetooth module, but because of the nature of the test I decided to disconnect it and 'debug' my project using the serial monitor as an equivalent.

The circuit has the following connection table:

LED +: Pin 12 on my Arduino.
LED -: GND on my Arduino.

...as you can see, I have tried to simplify as much as I can the circuit, as I wanted to make sure I didn't have wire problems.

Here's the code:

char command;
String string;
#define led 12

void LEDOn()
    {
          digitalWrite(led, HIGH);
    }

void LEDOff()
    {
      digitalWrite(led, LOW);
    }

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

void loop()
{
     if (Serial.available() > 0)
           {string = "";}

     while(Serial.available() > 0)
    {
           command = ((byte)Serial.read());

           if(command == ':')
           {
                  break;
           }

           else
           {
                  string += command;
           }

           delay(1);
    }

    if(string == "LO")
    {
           LEDOn();
     }

   if(string == "LF")
    {
           LEDOff();
    }

The problem comes when I type the commands. Normally, an LED in the board will react (I think it's the RX one), but the LED in pin 12 will not react at all. After testing ten times with each command alternatively, I calculated the serial needs an average of 6 command repetitions in order to react. Exactly the same happens when the HC-06 is connected.

Is there a reason for this?

It worked fine for me, if I typed the entire command, "LO:" or LF:" (without the quotes of course). However, if I typed and sent one character at a time, it failed. The problem is quite likely the code:

   if (Serial.available() > 0)
         {string = "";}

If you send all of the characters at once, the while( Serial.available() ) loop will get the whole line and match it. But if there is any pause between characters, what does that if statement do? (Hint: loop() executes way faster than you can type!)

I was using the serial terminal built into the Eclipse IDE. Different terminal software might behave differently when you type a string and send it. Remember, any gaps between characters, and that first if statement gets time to do its dirty work.


Ubuntu class string has no member remove I am running some code that works fine on my windows system using the .remove method.  On Ubuntu 16.04 I get the following errror:

error: ‘class String’ has no member named ‘remove’

To see if it was installation, I uninstalled arduino with

sudo apt-get purge arduino arduino-core

then

sudo apt-get update
sudo apt-get upgrade

sudo apt-get install arduino arduino-core

and the issue remains.  I have seen some people say opening arduino through the terminal (from this), although that does not fix it.

Arduino version
2:1.0.5+dfsg2-4

Any help is appreciated.

The remove method was added to the String class in 1.0.6.

Installing Arduino IDE from the Ubuntu repository gets you a really old package (1.0.5).

You should download and install the newest version from the official Arduino page.


Debugger with Breakpoint and Variable read/set capability Is there any free/open or commercial/paid Arduino IDE Sketch Debugger (not Atmel chip factory standard tool set) with Breakpoint and Variable read/set capability?

I read about VM on web. Is there any similar product?

There is something quite close to what you are asking.
You need either the (more expensive) ICEMKII (iirc) or the (cheaper) AVRDragon.
Then it's possible to use it with gdb.

In practice the AVR supports only one breakpoint, so what happens is that the binary in flash will be dynamically patched.
This will slightly reduce the life of the AVR, but I think it's fairly acceptable. One can always use Arduino UNO with the original DIP package for AVR, mounted on a socket. Then it's sufficient to replace the burnt microcontroller and keep the rest (but it's hundreds of thousands of programming cycles before the AVR fails).


Using an Arduino board to program an AVR I think the arduino board is awesome.
Though I'm not interested in the library and IDE at all...
Is there a way, to use an AVR 328p, as you normally would, on an arduino board?

I like how arduino's can be programmed through serial, can get powered through serial and I often use serial as a debugging option. Making my own board (with ICSP programmer) would not be able to do this (withouth bootloader).

The Question

Do I have to use all the stuff from arduino?

Can I use my own compiler for an arduino board? (GNU-GCC / AVR)
Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)
Can I still program through serial then? (Does the bootloader care which compiler I used? Does Eclipse/AVR studio have the options to program through serial?)
Other stuff I should take in mind. (Annoying things like AVR studio not having a COM port window, though that's an easy fix.)

Edit: We've programmed an AVR 328P (GNU-GCC / Eclipse / ICSP) in school, so I know it takes quite some work to get the compiler set up, working with Eclipse. You don't have to completely describe the proces :) Just to avoid someone spending hours on an answer that's easily found on the internet.
(On my search for this subject I could only find people doing the other way around, getting an 328p chip to work with arduino)

Do I have to use all the stuff from arduino?

A = No!

Can I use my own compiler for an arduino board? (GNU-GCC / AVR)
Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)
Can I still program through serial then? (Does the bootloader care which

Of Course! I use Eclipse IDE and I programming boards with Arduino bootloader directly in C/C++ using avr-gcc and avrdude.
Configuring Eclipse
First, let's download a plug-in for integrating AVR GCC and Avrdude + Eclipse IDE
To install the plug-in, point to the menu "Help> Install new software":

We will set a new location to download the plugin. Click the "Add ..." and type: AVR - Eclipse and the URL: http://avr-eclipse.sourceforge.net/updatesite

Now select the plugin that appeared in the list and click "Next":

Next, next, "I Acept the terms...", restart...
Now we install the plug-in, we will set it up. Point to the menu "Window> Preferences." Click in "AVRDUDE". The following screen:

On the next screen "AVR DUDE" let's set our recorder. Click "Add" to "Programmer configuration". Search for "Arduino".

Or, if you prefer, you can program making use of avr libraries in own Arduino IDE. Try to upload the following code into an Arduino board! While a blink costs almost 1,056 bytes of memory using an Arduino Uno, the following code uses only 164 bytes and does the same thing :)
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clr_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define tst_bit(Y,bit_x) (Y&(1<<bit_x))
#define cpl_bit(Y,bit_x) (Y^=(1<<bit_x))

#define LED PB5

int main( ){
    DDRB = 0xFF;

    while(1){
        cpl_bit(PORTB,LED);
        _delay_ms(200);
    }
}

If you use Linux, you can take a sudo cat/dev/ttyACM0 to detect what lies serial and echo "string" >> /dev/ttyACM0 to send data.


ArduinoJSON define as extern My sketch contains 2 .h files. one defines
on 1st .h file:
#define JSON_SIZE_IOT 400
#define JSON_SIZE_SKETCH 300
StaticJsonDocument<JSON_SIZE_IOT> paramJSON;
StaticJsonDocument<JSON_SIZE_SKETCH> sketchJSON;

and other need to define paramJSON and sketchJSON as extern
on 2nd .h file:
extern JsonDocument paramJSON;
extern JsonDocument paramJSON;

but I get this error:
error: conflicting declaration 'ArduinoJson6172_91::StaticJsonDocument<400u> paramJSON'
 StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

....
: previous declaration as 'ArduinoJson6172_91::JsonDocument paramJSON'
 extern JsonDocument paramJSON;

For an extern the whole definition has to match the "master" definition.
So if you have:
StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

then you extern has to be:
extern StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

Of course you have to make sure your JSON_SIZE_IOT is the same for both - so it's best if that comes from a common source.
This is known as explicit instantiation declaration and you can read more about it in the Class template C++ reference.


Querying streaming sensor data on the Arduino board I am new to Arduino and this forum, so please forgive me if I am asking something really trivial and stupid.

I have an Arduino board which collects sensor readings from an MPU6050 sensor (acceleration+gyroscope). The next step for me would be to process these data directly on the board. I want to somehow store N last sensor values and then query this set (collection, vector, array, whatever you call it) to fetch certain values. This set will be constantly updated with new values, whereas older values will be pushed out, so that only the most up-to-date values are stored in the set. For example, I want to know if the acceleration exceeded 10 m/s in the last minute.

In the literature this kind of set with most recent values is sometimes called window - this approach allows limiting an unbounded sequence of constantly generated tuples to a bounded bag and then apply traditional SQL-like query operators. For example, Oracle has come with CQL - an engine and a query language for handling streaming data.

Before I start implementing this, I am wondering if there is a similar (and, of course, much simpler) library for Arduino? If not, which data structure should I use to implement such functionality?

Also, my intention is to query not just individual values, but certain patterns and sequences - e.g., I want to know if the acceleration first decreased and then increased again (something similar to the WHERE condition of an SQL query). Does it look realistic to implement with Arduino?

It sounds like you are after my Average library:

https://github.com/MajenkoLibraries/Average

It allows you to store a rolling set of data where you get to "push" values into it and the oldest one drops off the end. (It's implemented internally using a circular buffer).

You can then do various forms of analysis on the data - get the mean average, the mode average, calculate the standard deviation, find the maximum and minimum values of the set, and even access individual entries within the set.

It's a fully templated library, so you can use it with any numerical data type (float, double, int, long, etc).


Ultrasonic sensor confusion Here is a code snipet for ultrasonic sensor

digitalWrite(trigpin,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);

duration=pulseIn(echopin,HIGH);

Assume trigpin and echopin pins are already defined.

Now according to Arduino reference guide pulseIn funcion:

  Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0 if no complete pulse was received within the time out.

So shouldn't I be getting 10 microseconds as my answer, since since initial state of echo pin is low, now when the reflected sound hits receiver, echo pin goes high, the timer gets started and when and when the pulse ends the echo pin goes low again and since pulse sent was of 10 microseconds of length, the ans should be 10, but any ultrasonic program I have seen uses this code to find the duration the ultrasonic wave takes since it gets emitted to the time it gets into the receiver.

What happens is:

You send a pulse of 10 ms with TTL signal. This is the first line in the picture below.
Than you call pulseIn. This waits for the echo pulse.
The echo pulse will become high when reflected. This happens internally in the module. This is the second line.
The echo pulse will stay high depending on the time it took to be echoed back and makes a pin high (echo pin). This is the third line.
Than your pulseIn command returns with the time (of the echo pin length).


3.3V, 5V and 9V pins on Arduino On my Arduino Uno R3 and Arduino Mega R3, there are 5V and 3.3V pins.

However on this page Introduction to the Arduino Board, there is a 5V and 9V pin but no 3.3V pin. The page at Arduino: What Adapter? also mentions a 9V pin.

Why is there a discrepency?

The link you provide looks rather old and I don't think it applies to UNO Revision 3 as it has more pins than on the diagram you show.

I suggest you rather take a look at this Arduino UNO link which contains uptodate information about the UNO; in there you will see that for R3, the "power rail" has been extended and has the following pins, left to right:

1 unlabeled pin (can't remember what it is)
1 IOREF pin (used by shields to know if they should operate as 3.3V or 5V devices)
3.3V regulated output
5V regulated output
2 GND pins
Vin pin: this pin can be used in 2 different ways:

either as a voltage supply input (instead of using the power plug or the USB); the input voltage should be in 7-12V range and will be regulated internally (by the board circuits) to 5V
or an output supply voltage (if you plugged voltage supply through the power plug or the USB plug) that is a "copy" of the voltage input through the power plug or USB plug (not regulated yet)


Is there a way to read real-time port selection on Arduino IDE when using third-party toolchain and uploading program? I am using a third-party program to build the binary file and upload it under Arduino IDE's GUI, meaning I am not using the built-in avr-gcc nor avrdude for building and uploading. As there is a on-board DAP chip, uploading binary file is done by copy&paste the binary file into the flash memory recognized as a removable storage by the OS.

However, this make reading user's current port selection very difficult because the IDE is written in Java, but the thrid-party program I am using is in C++.

Knowing which port the user has currently selected is very important to me, as sometimes I need to program multiple boards at the same time and monitor their received data on the serial port.

If someone can point me into the right direction or link me to the previously-solved similar question , it will be much appreciated!

PS: I am working under Ubuntu&Windows10 OS and using latest Arduino IDE.

After someone from Github gave me a link, I think I ve found the way to read the real-time port selection even using third party uploading program.

The key is command line argument in the "Platform.txt" file located under "arduino15" folder. If you have the same issue as mine, try look up this link, where you will find loads of useful information:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification

PS: rmb, after you change the command lines in the txt file, always close and restart your arduino IDE before those changes you made take effect.


Rectangular Input signal on digital pins I have a silly question.
Today I saw a function for arduino, that is pulseIn(). So to test what it does I applied a rectangular wave at a pin same as the arduino reference page did and it worked fine. There was a line in the reference page which stated :-
Works on pulses from 10 microseconds to 3 minutes in length.
So as it seems it will work upto 100KHz signal. Is there any way to read signals of much higher frequency than this? like in the range of MHz or so?

Reading high frequency signals can be done. It's possible to read signals up to about 6MHz or maybe even higher (depending on the system clock frequency).

That is, as long as all you want to know is the fundamental frequency of the signal.

Pin 5 of the Arduino Uno (PD5) is connected to Timer 1 and can be set to be the clock source for that timer.  By connecting that to your signal and allowing the timer to count up from zero using that signal as the clock source, and then waiting for a pre-defined time period, you can easily find how many clock pulses have arrived from your signal in that time. From that, you can calculate the frequency of the signal.

  The Timer/Counter can be clocked by an internal or an external clock source. The clock source is
  selected by the Clock Select logic which is controlled by the Clock Select bits in the Timer/Counter control
  Register B (TCCR1B.CS[2:0]).

Since all you are working with us the number of pulses over a given period you lose any information such as the duty cycle of the signal.

You should read the datasheet section 20: "TC1 - 16-bit Timer/Counter1 with PWM" for more detail about how you can use the timer to count the frequency of a signal.


I2C Read Operation in TCA9539 I am using this TI device TCA9539 (http://www.ti.com/lit/ds/symlink/tca9539.pdf) with the pins A1 and A0 tied to ground resulting the write address to 0x74.

I don't have any issues writing to this device address and perform the necessary functions, however when I try to read registers using Arduino read functions, getting NACK there. Is 0x75 correct read address?

For second question:

Based on the device spec for read operation:

  Reading from a slave is very similar to writing, but requires some additional steps. In order to read from a slave,
  the master must first instruct the slave which register it wishes to read from. This is done by the master starting
  off the transmission in a similar fashion as the write, by sending the address with the R/W bit equal to 0
  (signifying a write), followed by the register address it wishes to read from. When the slave acknowledges this
  register address, the master sends a START condition again, followed by the slave address with the R/W bit set
  to 1 (signifying a read). This time, the slave acknowledges the read request, and the master releases the SDA
  bus but continues supplying the clock to the slave. During this part of the transaction, the master becomes the
  master-receiver, and the slave becomes the slave-transmitter.
  The master continues to send out the clock pulses, but releases the SDA line so that the slave can transmit data.
  At the end of every byte of data, the master sends an ACK to the slave, letting the slave know that it is ready for
  more data. When the master has received the number of bytes it is expecting, it sends a NACK, signaling to the
  slave to halt communications and release the bus. The master follows this up with a STOP condition."

This is the code I am trying to use,

Wire.begin();
Wire.beginTransmission(0x74); // start i2c transmission as write addr
Wire.write(0x01)              // the register i need to read from
Wire.beginTransmission(0x75); // start i2c transmission as read addr given

I believe the device I2C read and arduino library functions for read is not making sense to me. Has anyone used this device for read?

The arduino i2c libraries expect a 7 bit slave address, not 8 bit address + r/w bit, and will manage the read write bit internally based on if you do a write or read.

So begin transmission 0x74

Write 0x01

End transmission

Begin transmission 0x74

Read n

End transmission


Pointers, libraries, and arrays: I'm trying to pass variable addresses to functions/methods within a custom library that should change the values at the specified addresses.  However, I think I'm missing something as it's taking me ages to tweak things just to get it to compile, let alone gather some useful information from it.

Note:
I've not tested the code as I'm focused on understanding (1.) through to (5.) and is just a quick example of the current pipeline:

Main.ino

#include <customLibrary.h>

CustomLibrary cLib();

byte someByte[6];
unsigned int theAddress;

setup(){};

loop(){

    // (1.)
    theAddress = &someByte; // normally need this here, or before setup(), for it to work.

    cLib.setValues(theAddress);

    // because:
    // cLib.setValues(&someByte);
    // doesn't seem to work
};

customLibrary.h

#ifndef CustomLib
#define CustomLib
#if(ARDUINO > 100)
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class CustomLibrary {
    public:
        CustomLibrary();
        void setValues(unsigned int theAddress); // (2.)
    private:
};
#endif

customLibrary.cpp

#include <customLibrary.h>

CustomLibrary::CustomLibrary(){
};

void CustomLibrary::setValues(unsigned int theAddress){ // (3.)

    byte _someNewValues[6] = {a,b,c,d,e,f};

    // Assign the variable from _someNewValues[_x] to (theAddress + _x)
    int _x = 0;
    for(unsigned int i = theAddress;i < (theAddress + 6);i++){ // (4.)
        // (5.)
        _x++;
    };

};

(1.) - Feels like it should be simpler.

(2-3-4-5.) - I have left out any "*" and "&" hoping that someone can provide the preferred way of doing this, or provide a better solution as it's taking far too long to get this working with everything else leading me to think I'm missing something basic.

There are some excellent tutorials out there which I have been
following with great success, but, only when all the pointers are within the same file.  Once I try and use them in a library it's a constant headache at the moment and I don't understand it enough to know what's wrong.

Need to go before I can proof-read and check it, but I think it's all there.  I'll be back later/tomorrow if there's anything that needs clearing up.

Edit:
I didn't know who to mark for the answer as both @dannyf and @KIIV answered perfectly.  I considered marking the answer based on the time it was posted, but decided instead to let @dannyf have it as his reputation was only 1.

Thank you both! Much appreciated!

somebyte itself is a pointer. so "&somebyte" doesn't make sense.

instead, use "&somebyte[0]" (or "&somebyte[5]" if you want an offset), or "somebyte" (or "somebyte + 5" if you want an offset).

arrays are actually pointers.


Controlling 4 motors using the Arduino Uno I've decided to make a quadcopter but since I'm a rookie, i decided against doing it from scratch. I'm planning to order this kit, first understand the dynamics and then try and make a quadcopter on my own using the components in it.
My first question are

Can I control the 4 motors using 2 H-bridges (L293D)?
Are ESC's necessary if I use the PWM pins?

Thanks in advance!

Can I control the 4 motors using 2 H-bridges (L293D)?

Yes. Two per chip.

  Are ESC's necessary if I use the PWM pins?

There is one thing you must understand first: there are two kinds of DC motor - Brushed and Brushless.

The Brushed motor is the "normal" kind - you apply power to it and it spins.  These you control with the likes of an L293D and use PWM to control the speed.

Brushless motors are the kind you have in hard drives and the like. They consist of a number of coils that get turned on and off at the right time to pull a magnet around in a circle (to put it crudely). These require special timing and control to get the coils energised at the right time and in the right way. This is what an ESC is for.

Brushless motors are smaller and lighter for the same power than brushed ones. They also have a longer life. Because of this they are generally preferred to brushed motors on quadcopters.

Brushed motors have a very high starting torque, don't require complex control logic and use less energy when not running full speed.

If you use brushless motors, which ideally you should (though I can't tell what kind of motors those are in that kit) then you must either use an ESC or build your own ESC using an Arduino and multiple motor driver circuits. Simplest to use an ESC.

If you don't use brushless motors then an ESC is not what you want to use - just the L293D chips and PWM.


How can i connect 4 stepper motors and 3 sensors to an Anduino? I have an Arduino AT MEGA 2560 circuit. I want to buy 1 Nema-17 bipolar stepper motors, 3 M49SP-2K stepper motors, 3 KY-032 sensors to do my project but i dont know how to connect them to my Arduino.
Is there any Arduino shield for my purpose? Can I use Ramps 1.4 Arduino shield?

Take a look at the Ramps V1.6, it is what I use. It plugs onto the AT Mega board.

https://reprap.org/wiki/RAMPS_1.6

The 1.6 has a few improvements. I like the solder in power connectors rather than the plug in ones. More reliable.

Because I already had the AT Mega board I decided to try the ramps. There are better boards now, with 32 bit processors. But as a starting point the Ramps combo is the simplest to get going and it does the job.

Other boards may work out a little better, but the firmware is a bigger issue. Still in development.


Button not working - Arduino Due project (MiniEngine v2) I am building Arduino Due based project called MiniEngine v2 (an open-source motion control software for timelapse photography).

The project is not very active anymore but there are still all the documentation at github. Project owner had webshop where he sold MiniEngine shields for arduino but they are not available anymore. There was gerber files available at project github page so I orderer PCB's form seeed.com.

Project's Github page is at:
https://github.com/airiclenz/miniEngine2

Everything seems to work ok but one of the buttons is not working. There is only 2 buttons and one rotary encoder.

I think the reason why the button is not working is that the output voltage for button from 74HC14N (hex smith trigger) is too low (I am not very good at electronic so I might be totally wrong.

I tried to measure values with voltage meter and here is the result what I got for those two buttons:

Here are the values in written format ( I took measurement from SN74HC14N )

btn_2 (pin9 input, pin8 output)
btn_1 (pin11 input, pin10 output)

SETTINGS BUTTON (btn_2) -> this one works fine

1) button up  - metering from input pin 11 => 3.26
2) button down -metering from input pin 11 => 0
3) button up - metering from output pin 10 => 0.6
4) button down - metering from output pin 10 => 2.38

START/BACK BUTTON (btn_1) -> this one does not work

1) button up  - metering from input pin 9 => 3.26
2) button down - metering from input pin 9 => 0
3) button up - metering from output pin 8 => 1.43
4) button down - metering from output pin 8 => 1.53

Here is how the buttons are initialized:

    void input_init() {

  // set pin modes
  pinMode(PIN_ROTARY_PRESS, INPUT);
  pinMode(PIN_KEY_1, INPUT);
  pinMode(PIN_KEY_2, INPUT);

  // attach interrupts for the keys
  attachInterrupt(PIN_ROTARY_PRESS, input_interrupt_keyRotary_press,  RISING);
  attachInterrupt(PIN_KEY_1,        input_interrupt_key1,             RISING);
  attachInterrupt(PIN_KEY_2,        input_interrupt_key2_press,       RISING);

  // attach interrupts to both encoder pins for every state change
  attachInterrupt(PIN_ROTARY_A,     input_interrupt_rotary,           CHANGE);
  attachInterrupt(PIN_ROTARY_B,     input_interrupt_rotary,           CHANGE);

  // set the initial rotary values & configurations
  rotary.setPosition(0);
  rotary.setKeyMode(true);
  rotary_old_pos = 0;
}

And here is function for btn_1 press that is never called (except once in powering the shield/arduino due)

void input_interrupt_key1() {

  if ((key_1_time + DEF_INPUT_DEBOUNCE) < millis()) {

    key_1_time = millis();
    setBit(input_status, BIT_2);

  }
}

I can only use 2 links in posts (I do not have 10 reputation) so you can find the code for inputs at Github (link above). (folder MiniEngine2/Software/miniEngine2/mE2_input.ino)

All code files are at Sotfware at folder: MiniEngine2/Software/miniEngine2

I have put Serial.println command in code and nothing is printed when btn_1 is pressed. When I plug power on then the btn_1 is triggered once...

Here is link to the the schematic for that shield ( it is quite big so that's why I did not embed the photo):

Schematic for shield is at Github folder : Hardware/miniE shield v2 revB BED board - schematic.pdf

Here is also link to the video where you can see how I took the measurements:
https://youtu.be/wFR7P65qMGA

Please ask if I need to provide more information...

It was the Arduino Due issue. Arduino digital pin 43 was faulty or something. I managed to change 43 to 53 and now the button works...


Built-in LED lighs up spontaneously I'm trying to connect my ESP32 to this CO2 measurement device. I admit I am clueless about connecting devices with independent power sources to one another.
I connected ground to ground and CLK to PIN2. Just to be on the safe side, I put a resistor between CLK and PIN2.
I started with 4.8KOhm of resistance. ESP's ADC measured 2.1V and it seemed fine. But when I switched to 1K resistor, trying to get closer to the level of "logical 1" (the way I understand it), something unexpected happened. ADC measured 2.65V, which is still beyond 3.3V ESP should be able to handle, and the built-in LED lit up, although nothing in my sketch called for it.
Though the configuration worked stably for some minutes while I was testing it, and no smoke appeared, I am afraid the LED lighting spontaneously might be a sign of an electrical breakdown.
The both devices are sitting on the same USB hub.
Here is the sketch I am using:
#define PIN_CLOCK  2

void setup() {
  pinMode(PIN_CLOCK, INPUT);
  Serial.begin(4800);
}

bool last = 0;

void loop() {
  int x = analogRead(PIN_CLOCK);
  bool val = x > 1500;
  if (last != val)
    Serial.println(x*3.3/4095);
    last = val;
  }

Can someone explain why the LED lights up?
Can someone recommend a good article/video on basic rules about interconnecting such devices?

You do not need a resistor in the circuit. Just connect the devices together directly as shown in the tutorial you link to. They are both 3.3V devices and operate perfectly together with no additional components.
Reading an analog value from a clock signal is pretty meaningless anyway, so there's really no point in your experiments at the moment. They prove nothing.
As to why the light came on - that is most likely because the ESP is configured to use that LED to indicate the WiFi status or something similar.  The thing with an ESP32 is there is a whole lot more going on than just your code. Your code is just one thread in a complex system.


Arduino PWM Pins Interrupt I am creating pwm from an arduino pin with 50% duty cycle. I just want to know how can i detect its every falling edge using timer interrupt? I don't want to connect that PWM pin to an external interrupt pin. Please help me.

You can define an interrupt service routine (ISR) for each Timer and PWM pin that it handles. These are known as TIMERn_COMPA_vect, TIMERn_COMPB_vect and TIMERn_COMPC_vect. The Mega has six Timers (n=0..5).

ISR(TIMERn_COMPA_vect)
{
// Timer/Counter compare match A
}

Check the PWM configuration for how the pin is set, cleared or toggled.

Cheers!


Transfer serial data to struct variable in Arduino I have declared a struct with some variables that right now are fixed, but one of the variables on the struct needs to be what the Arduino's serial port reads.

struct testing_var
{
    const char *name;
    byte key[32];
    byte pt[16];
};

static testing_var const test1 = {
    .name        = "Speck-128-ECB",
    .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
};

As you can see for how I have declared it, I'm trying to get a plaintext from the serial port and the Arduino should encrypt that. I have a function that does this encryption, but I can't quite figure out how to pass what the serial port reads to the struct.

void loop() {

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

I need to pass this var1 as the variable pt in the struct. Any clues? I'm maybe missing something very obvious, but I don't usually work with structs.

EDIT:
I'm trying to assign the value read by the serial port to the struct by creating another function that goes like this:

void setPlain(struct PlainText *myPlain, const char* thePlain){
    myPlain -> plaintext = the Plain;
   }

Then, in the loop, I use:

  if (Serial.available()>0) {
    var1 = Serial.read();
    setPlain(&PlainText, var1)
}

I'm getting an error using this function, I guess that it has something to do with the type of variable I'm trying to assign, these values are in HEX, not in char. But I'm not really sure it that's it or what other workaround should I use.

You read the serial port one char at time, and assign it to test1.pt[i], where i is an index varying from 0 to 15.

And test1 cannot be const, because you are going to modify it with the serial data.

Here is a test code showing how to do it.

struct testing_var
{
    const char *name;
    byte key[32];
    byte pt[16];
};

//  test1 cannot be 'const'
static testing_var test1 = {
    .name        = "Speck-128-ECB",
    .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
};

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

void loop() {
  Serial.println("Enter 16 chars:");
  //  Read 16 chars from Serial
  for (int i=0; i < 16;) {
    if (Serial.available()) {
      test1.pt[i++] = Serial.read();
    }
  }
  // Do something with the data, like print it.
  for (int i = 0; i < 16; i++) {
    Serial.print(char((test1.pt[i])));
  }
  Serial.println();
}


Include my header files let's suppose I have folder called AES, in this folder is file "AES.ino" where is code and folder "AESLib" what is library. In "AESLib" is file called "AESLib.h",

now when I try to include AESLib.h with

#include "AESLib/AESLib.h"

in my AES.ino, then Arduino command line tool complain that its not able to find "AESLib.h"

Where could be the catch?

Thanks

I have the same problem using the Arduino IDE 1.5.6 beta.
Adding the library(s) using the menu (Sketch->include library->something) makes it work until the IDE is closed.


How can I reduce the redundancy of this code, so one function can perform the task of printing on Serial and Softserial? void Multi_print (String str)
{
  Serial.print(str);
  mySerial.print(str);
 }

void Multi_println (String str)
{
 Serial.println(str);
 mySerial.println(str);
}

void Multi_parse_int (int value)
 {
    Serial.print(value);
    mySerial.print(value);
 }

Just send your data to a tee: this is a type of pipe fitting where you
push the data through one end and it goes out through the other two
ends. As it happens, both Serial and Softserial (and almost anything
that can print()) inherit from the virtual Print class. You can
implement a tee as a Print that outputs to two Prints:

class Tee : public Print
{
public:
    Tee(Print &_p1, Print &_p2)
    : p1(_p1), p2(_p2)
    {}

    size_t write(uint8_t c)
    {
        size_t count1 = p1.write(c);
        size_t count2 = p2.write(c);
        return min(count1, count2);
    }
private:
    Print &p1, &p2;
};

The write(uint8_t) is the only method you really need to implement to
have a working Print. Then, all the print() and println() methods
will work.

Example usage:

Tee dualSerial(Serial, mySerial);
dualSerial.print("The answer is ");
dualSerial.println(42);

Note that parseInt() will not work, as it is not a method from
Print. But if you think twice, you will realize that parseInt() on a
pair of channels just does not make sense.


Which transistor I should use to switch 12V 0.8A? I am have circuit with Arduino NANO and I need to control air valve, which is powered with 12 Volts and 0.8 Amper. Problem is that Arduino NANO is powered with 5 volts. I want to use transistor to achieve it. Which one the best option in this case ?

Thank you for help

PS: I need ON/OFF states only.

PSS: I want to use transistor, not relay, because transistors are quicker.

If you look for "transistor" using the search box on this website, you'll find hundreds of results.

Here are a few examples that will answer your question.

Using a MOSFET

Using a TIP120 Transistor


How to solve problem AT+INQ ERROR (1F), AT+INIT ERROR(17) on Bluetooth Module HC-05? i have problem with accessing at-command in module Bluetooh HC-05.

i just follow all tutorial to activate at-command like this,
http://www.martyncurrey.com/arduino-with-hc-05-bluetooth-module-in-slave-mode/

or in this video
https://www.youtube.com/watch?v=Vr4cdpsoVEo&t=31s

and just read some explanation and implemented to my problem
HC-05 Bluetooth AT+INQ command not working

but i just still get same error.
i cant use AT+INQ command, always get ERROR(1F).
AT+INIT get ERROR(17).

i have module HC-05 with version 3.0-20170601

This is my code i use it.

#include <SoftwareSerial.h>
SoftwareSerial BTserial(8, 9); // RX | TX`

const long baudRate = 38400;
char c=' ';
boolean NL = true;

void setup()

{
   Serial.begin(9600);
   Serial.print("Sketch:   ");   Serial.println(__FILE__);
   Serial.print("Uploaded: ");   Serial.println(__DATE__);
   Serial.println(" ");

BTserial.begin(baudRate);
Serial.print("BTserial started at "); Serial.println(baudRate);
Serial.println(" ");
}

void loop()

{

// Read from the Bluetooth module and send to the Arduino Serial Monitor
if (BTserial.available())
   {
       c = BTserial.read();
       Serial.write(c);
   }

   // Read from the Serial Monitor and send to the Bluetooth module
if (Serial.available())
   {
       c = Serial.read();
       BTserial.write(c);

    // Echo the user input to the main window. The ">" character indicates
    the user entered text.
    if (NL) { Serial.print(">");  NL = false; }
    Serial.write(c);
    if (c==10) { NL = true; }
   }

}

I have two modules:

(A) HC-05 with firmware version 3.0-20170601

(B) HC-05 with firmware version 2.0-20100601 (ok)

I have the same problem: when the AT command "AT+INQ" is sent on (A) module, the response is always "ERROR:(1F)". This error code seems not be reported in any document or specification available on internet. This BT module have firmware version (AT+VERSION) 3.0-20170601. Also I have noticed that command AT+INIT on (A) module returns always ERROR:(17), this error normally can be ignored if the command has been sent already (Initiate SPP lib), but the first time should be return "OK" as on (B) module.

The (B) module with firmware version 2.0-20100601 works ok with the following commands (set PIN34 high at power-up, or press button on module and keep pressed during commands):

AT+RMAAD -> delete all paired devices list

AT+ROLE=1 -> Set master mode

AT+RESET -> reset module to enter into master mode

AT+CMODE=1 -> Permit connection with any device

AT+INQM=0,5,9 -> Set Search parameters(Query mode standard, 5 devices, 9secs)

AT+INIT  --> Init SPP profile mode (first time response: "OK")

AT+INQ  --> Start search devices (return device list after some seconds)

The differences between two modules are:

On AT+INIT the (A) module return always ERROR:(17), the (B) module return "OK" first time and ERROR:(17) if the command is sent twice.
On (A) module the command AT+INQ return always ERROR:(1F), the (B) module return the list of the BT devices.

Also the (A) and (B) modules are physically different. The (B) module have some components (resistors/capacitors) between the two big black chips, the (A) module no.

Also I noticed that on (A) module the AT+CLASS? return "1f00" value (default?). The correct value should be "0" as (B) module ? Anyway setting AT+CLASS=0 on (A) module the result is always the same.

In slave mode (AT+ROLE=0) both modules works fine.

With (A) module I'm unable to use it as "MASTER" and connect it to any other slave BT modules because did not perform devices search. (INQ fails).

I think that in 3.0 firmware is needed to set other(s) parameter(s) in order to start SPP profile correctly (INIT) and then avoid ERROR:(1F) in INQ command (search).

Someone already solved the problem ?