I have multiple components that are lagging I have multiple components such as LED's, Servos, ultrasound, and a photoresistor. For context, certain LED's light up and a buzzer makes a certain sound depending on the range of distance the ultra sound picks up and the servo moves based on the photoresistor data etc. They work just fine but they do not work at the same time. Data is collected one after the other but not at the same time like I want them to. Is there any way I can make them collect data at the same time?

As already stated in Look Alterno's comment and dannyf's answer, the
Arduinos are single-core, and they cannot perform several processes in
parallel. However, unless you have sub-millisecond timing requirements,
this should not be an issue. Your Arduino can just perform one task at a
time and, if it goes fast enough, it should meet your requirements.

So the good question to ask is: given the tasks you want it to
perform, can the Arduino do them while keeping the latency below some
threshold of your choosing? Latency is the time lag between the Arduino
receiving some stimulus (say, a change in light level) and it performing
the required action (e.g. moving a servo). For the kind of actuations
you mention in the question (servos, LEDs, buzzer), it makes little
sense to require sub-millisecond latency, and the Arduino (any Arduino)
should be able to meet your timing requirements hands down.

If your Arduino is really slow, this is generally because you have
something in your program that blocks the CPU for too long. It may be
some process that is very CPU-intensive, but this is unlikely because
you can do a significant amount of computation in one millisecond. More
likely, you are calling some blocking library function: a function
that blocks the CPU inside a do-nothing loop while it waits for some
external event to happen. You will have to go through your code and
hunt down any such blocking calls.

  I have multiple components such as LED's

LEDs are no issue. You can switch them on or off with a digital pin.
Once switched on, you don't need to do anything to keep them on. They
only consume a tiny bit of CPU time when you switch their state, but
none when you leave them in a fixed state.

If you want to dim an LED, then you will have to toggle it on and off
very fast. You can do this using analogWrite() on a PWM-capable pin.
Then, the toggling is done by a hardware timer, and it does not cost you
any CPU time. If you are short of PWM pins, you can also do the toggling
by software, but this will obviously cost you some CPU time.

  servos

Servos are typically driven using the Servo library. This uses a
combination of hardware (a timer for generating interrupts) and software
(an interrupt service routine that sends the control signals to the
servos). The CPU load should be small, unless you have a lot of servos.
Expect the interrupt to add some latency to the rest of your program.
Something like a few tens of microseconds or so (I haven't measured it).

Also, the servo library will use one of your timers, so you loose the
PWM feature on a couple of pins.

  photoresistor

You typically read a photoresistor with analogRead(). This
is a blocking function: it blocks the CPU while it waits for the ADC to
do its conversion. It will eat about 110 µs every time you call it,
so it is probably not such a big deal.

  buzzer

You switch a self-drive buzzer on and off just like an LED, with any
digital pin. If it's an external drive buzzer, you will have to
continuously toggle it. This is typically done with the tone()
function, which uses Timer 2 and costs you no CPU time.

  ultrasound

Ultrasound sonars are typically read using pulseIn(). This is a
blocking function, and often a very serious offender: it block the CPU
while waiting for the echo to come back. If the target is 16 cm
from the sonar, you will have to wait for about 1 ms, and
proportionately longer for a target further away. If the sonar cannot
see a target, pulseIn() will wait until it times out, and the default
timeout is a whopping full second!

If you are using pulseIn(), the first thing to do is to make sure you
provide an explicit timeout in the call. Make that timeout slightly
longer than the echo time for the longest distance you want to sense. If
that is still too long, you will have to look for a non-blocking
alternative to pulseIn(). You may find some on the Web.

  delay()

You did not mention delay() in you question. You are not using
delay(), right? If you are, then you only get what you are asking for.


Parsing JSON on the Arduino I'm using the ArduinoJson library. There is a great example for parsing a single JSON object in the source code. I am attempting to iterate over an array of JSON objects:

#include <JsonParser.h>

using namespace ArduinoJson::Parser;

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

  char json[] = "[{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}, \
    {\"sensor\":\"gps\",\"time\":1351824140,\"data\":[50.756080,21.302038]}]";

  JsonParser<32> parser;
  JsonArray root = parser.parse(json);

  if (!root.success()) {
    Serial.println("JsonParser.parse() failed");
    return;
  }

  for (JsonArrayIterator item = root.begin(); item != root.end(); ++item) {
    // unsure of what to do here.

    Serial.println((*item)["data"]);
    // results in:
    // ParseJsonArray:21: error: call of overloaded
    //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous

    JsonObject something = JsonObject(*item);
    Serial.println(something["sensor"]);
    // results in :
    // ParseJsonArray:26: error: call of overloaded
    //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous
  }
}

void loop() {}

item is of type JsonValue. I would like to treat it as a JsonObject and pull some data out of it.

This is how I would write this loop:

for (JsonArrayIterator it = root.begin(); it != root.end(); ++it)
{
  JsonObject row = *it;

  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

And, if C++11 is available (which is not the case with Arduino IDE 1.0.5):

for (auto row : root)
{
  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}


Mac Big Sur don't recognize generic Wemos D1 MINI PRO based ESP-8266EX I bought one of theses cheaps & generic Wemos D1 MINI PRO with ESP-8266 to make a system to connect my lamp with google home etc.
But the problem is to upload the code into wemos. The Arduino IDE do not recognize the USB port that is connected.

When I connect to my Mac the board flashes the blue LED, so I suppose that it's not dead or something.
I've tried 5 different cables e nothing. I've read some articles about drivers to install but is only for Sierra or High Sierra.
Also, uninstalled and installed the arduino IDE.
I installed the ESP8266 Boards in the Boards Manager.
I tested it out with an Arduino UNO board and it recognized normally.
I have no idea what to do. I don't have a windows PC in my house to test it out, as well.
Here the pics of the board:


Questions about HMC5883L library I'm studying the structures of libraries currently. I want to learn how good programmers write code, what are the strategies they follow, the art the programmer followed to develop the library. And how important the library should be written in the well arranged form.

But as I'm go back and forth into the library over and over, I really need to understand, the way the programmer followed, and the reasons behind the applied strategy.

The example I'm studying now is the HMC5883L and how the programmer used the Wire library to manage the developing the library. This should be quite easy for experienced programmers, but I'm really studying the concepts, strategies .. etc.

As I'm going over and over I have different questions, so to start this discussion I want to begin with this question about the programmer writing two very similar functions that pretty much do the same thing.

// Read byte to register
uint8_t HMC5883L::fastRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    #if ARDUINO >= 100
        Wire.write(reg);
    #else
        Wire.send(reg);
    #endif
    Wire.endTransmission();

    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    #if ARDUINO >= 100
        value = Wire.read();
    #else
        value = Wire.receive();
    #endif
    Wire.endTransmission();

    return value;
}

// Read byte from register
uint8_t HMC5883L::readRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    #if ARDUINO >= 100
        Wire.write(reg);
    #else
        Wire.send(reg);
    #endif
    Wire.endTransmission();

    Wire.beginTransmission(HMC5883L_ADDRESS);
    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    while(!Wire.available()) {};
    #if ARDUINO >= 100
        value = Wire.read();
    #else
        value = Wire.receive();
    #endif
    Wire.endTransmission();

    return value;
}

Update:
Actually, the programmer used the 1st version only in the HMC5883L.begin(); function, but why?

if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
|| (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
|| (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
{
return false;
}

Everything else in the library used the 2nd version.

So, basically the two functions are to read a specified register in the HMC5883L, my questions:

what is the difference? I know that there's an extra care has been put into the second function, but why ?
Is it so important ?
Are there situations that require any version of the functions ?

TBH the second version of the function is trash. The first version is (almost) the right way to do it.  There's stuff in the second version that really shouldn't be there. There is absolutely no reason why the creator of the library created that second function.

It "waits" for data to be available, when that data will be available the moment requestFrom() completes - so is completely redundant
It makes a spurious beginTransmission() call right before the requestFrom() call. beginTransmission() is only for writing, not for reading. It's pointless there.

However:

Both functions do an endTransmission() after the receiveFrom(), which makes no sense - the endTransmission() goes to balance a beginTransmission() only - not a receiveFrom().  receiveFrom() is a completely self-contained function that needs no other handling.

This library is probably not a good one to study for learning how to use the Wire library. It contains code that indicates the author themselves didn't have a proper grasp of the workings of the library.


Reverse engineering LIN bus on E-bike system As a project I am trying to 'hack' an old E-bike.
The electronic system of the bike consists of:

A torque sensor measuring deformation of the rear.
A 'spin' sensor measuring if the person is pedeling.
A battery pack with BMS
A speed controller inside the hub motor.
A display to control speed, lights and display distance information etc.

From researching I concluded that the sensors, dislay and speed controller are communicating over LIN because they have a ATA6661 LIN transceiver and they are all connected parallel over the VS, LIN and GND wire.
When I power up the speed controller on its own I can see some LIN communication on my oscilloscope:

I do not have a LIN transceiver to log the data but I attached a USB-TTL transceiver to the uart-side of the LINtransceiver. From my oscilloscope a deduced that the baud rate was 9600. I used termite to listen on my serial port and set it to hex view. This is what I got:

I'm not sure if I should change the amount of bits or parity bits.
My goal is to understand the frames that are send and to deduce which frame holds which sensordata or results in a certain activity.
When I compare this to an CANbus project I was doing it was fairly easy to for example deduce which command was controlling my car's left window because with can-utils (candump) I could see every packet. I could filter unchanged packets and it colorcoded which bit(s) in each packet recently changed.
Any advice/ideas on how to do this for LINbus?

As a starter point I would hookup your rigol ds1054z via usb to sigrok
https://sigrok.org/wiki/PulseView this will enable you to log dump and analyze your lin frames . It has a frame decoder for LIN protocol.
This should give you a great view of what is transiting over the lin bus and which slave PID to call .
From there you may use a macchina.cc  to comunicate over lin or use
https://github.com/macchina/LIN with a arduino due and a lin tranceiver.
Cheerz


Efficient algorithm/data structure to calculate moving averages Currently I am developing a graphic LCD system to display temperatures, flows, voltages, power and energy in a heat pump system. The use of a graphic LCD means that half of my SRAM and ~75% of my flash have been used up by a screen buffer and strings.

I am currently displaying min/max/average figures for energy At midnight when the daily figure resets, the system checks if the consumption for the day is above or below the previous minimum or maximum, and stores the value. The average is calculated by dividing the cumulative energy consumption by the number of days.

I would like to display the daily average over the last week and month (4 weeks for simplicity) i.e. a rolling average. Currently this involves maintaining an array of values for the last 28 days and calculating an average over the whole array for monthly and last 7 days for weekly.

Initially I was doing this using an array of floats (as the energy is in the form "12.12kWh"), but this was using 28 * 4 bytes = 112 bytes (5.4% of SRAM). I don't mind having only a single decimal point of resolution, so I changed to using uint16_t and multiplying the figure by 100. This means that 12.12 is represented as 1212, and I divide by 100 for display purposes.

The size of the array is now down to 56 bytes (much better!).

There is no trivial way to reduce the figure down to a uint8_t that I can see. I could tolerate the loss of a decimal place ("12.1kWh" instead of "12.12kWh"), but consumption is frequently higher than 25.5kWh (255 being the highest value represented by a 8-bit unsigned integer). Consumption has never been below 10.0kWh or above 35.0kWh, so conceivably I could subtract 10 from the stored figures, but I know that one day we will exceed these limits.

I then tested code to pack 9-bit values into an array. This gives a range of 0-51.2kWh and uses 32 bytes in total. However, accessing an array like this is pretty slow, especially when you have to iterate over all values to calculate an average.

So my question is - is there a more efficient way of calculating a moving average with three windows - lifetime, 28 days and 7 days? Efficiency means smaller in terms of SRAM usage, but without the penalty of huge code. Can I avoid storing all values?

If your data has low standard deviation, then one method would be to sum values over the window, and then keep subtracting the mean from the sum, while adding the new value.

This would work well if there are no outliers, thereby leading to the aggregate error tending to zero over time.

//Pseudocode

count=0
while new_reading and count<7:
    sum += new_reading        //Calculate the sum of first 7 values
    count++

while new_reading:            //Loop till new readings available
    avg = sum / 7             //Calculate average
    sum -= avg                //Subtract average from sum
    sum += new_reading        //Add next reading to sum
    print avg


Interfacing Arduino UNO with TFT LCD and WiFi Shield I'm trying to interface my Arduino UNO with both a 1) TFT LCD screen and 2) WiFi Breakout board/shield.
The WiFi breakout board uses many of the same Digital pins as the LCD screen so is it possible for the arduino to interface with both devices simultaneously?

I also noticed that the shield goes over the arduino, but covers the header pins. Does this mean that I can't use these pins?

I've never worked with shields or breakout boards and would like some advice before I purchase either component.
If neither of these solutions will work, please provide me with alternate methods.

Your time/feedback is greatly appreciated :)

-Vip

I agree with Chris on this. The uno is limited where it comes to pins and and ram, you should probably look at a mega, or similar.

As far as running both at once, i don't think it would be possible with the uno, with the ram limitations, as well as pin limitations, you'll be hard pressed to get them going at the same time, within the same sketch.

While technically it is possible to use alternative pins, i doubt there will be enough unused pins to shift an entire shield over to on the Uno

If you're looking for a cheaper rout, you may look at adding a secondary Uno to run the wifi, and send any data you need displayed to the uno running the tft via serial coms.


Arduino Leonardo runs unusually hot I have a genuine (purchased from Adafruit) Arduino Leonardo that I have had for 2 years and I have not had any issues with. However, I have always noticed that it seems to be running suspiciously hot for a low power microcontroller, sometimes even too hot to comfortably touch. I measured the temperature today with an infrared thermometer at 121 degrees Fahrenheit (~49C). Based on observations by feeling the board, the 32U4 seems to be what is getting hot and everything else is cool to the touch. This happens when it is powered over USB as well as through the power jack. The chip gets hot even when nothing is connected to the I/O or power pins. The board is entirely working and does not appear visibly damaged. I am a bit worried about this as I may use this board in a project where it will be inside in enclosure and running for long periods of time. Any ideas why this is happening and if this normal?

My Leonardo, which I leave on all the time, is not hot. The CPU chip feels at room temperature as far as I can tell. If you were powering something from it, maybe you are drawing too much current. If it gets hot just sitting there doing nothing, and with nothing connected, something is wrong.

Maybe you damaged it in the past? Maybe hooked up some LEDs without current-limiting resistors? If not, it sounds like a faulty device to me.


What could cause interrupts from MCP23017 suddenly stop working? I have 4 rotary encoders connected to an MCP23017 which in turn is connected to interrupt port 0 on the arduino (and to I2C of course). Everything works fine: I get interrupts for all 4 rotary encoders, can read the values for them and even store these values in the EEPROM and load them in setup.

Now, I connect a WS2812 LED to the arduino (with a resistor and a capacitator in front of it). I connect the UNO and the led lights up. I attach the serial console (resetting the UNO) and it stops working (LED does not light up). This could just be simple wiring mistake and is not my real problem.

I remove the LED (and the capacitor) from the board and start everything up again. I can see via the serial console that the UNO works, however it does not receive any interrupts anymore. I exchange the MCP23017 thinking I fried it somehow but that doesn't change anything either...

Is there some sort of state the UNO has I could have affected?

Or could I have fried the interrupt "sub-system" on the UNO (again: all the other stuff still works)?

EDIT: The code is here: https://github.com/qollin/Liting/blob/master/src/Liting.cpp

I think I figured out whats wrong: you need to reset the interrupt handling of the MCP in setup() (by reading from both INT pins). Otherwise the MCP may start in a state where it does not generate new interrupts, because it waits for the old ones to be handled...


How to use IRremote library with atmega8a A few days ago I tested  a circuit on a  breadboard based on a ATmega8a with 1 MHz internal oscilator. It sould turn on and off a relay based on a IR code that is received and if it matches the programmed in the EEPROM it shoud enable or disable the relay. Now I developed a PCB and soldered everything together but now it isn't working. On an Arduino Nano it is working ok.

#include <IRremote.h>
#include <EEPROM.h>

int RECV_PIN = 11;
int RELAY_PIN = 4;
int setpin = 3;
unsigned long work_at;
unsigned long adres;
unsigned long irbuffer;
IRrecv irrecv(RECV_PIN);
decode_results results;

void dump(decode_results *results) {

    if(digitalRead(setpin) == 0){
      work_at = results->value;
      Serial.println(work_at, HEX);
    }
    irbuffer = results->value;

}

void eeprom_writer(){
  if (irrecv.decode(&results)) {
    if(digitalRead(setpin) == 0 && work_at != 0){
      EEPROM.put(0, work_at); //put walue
      Serial.println(work_at, HEX);
      adres = work_at;
      Serial.println(adres, HEX);
      delay(1000); //wait
   }
  }
}
void setup()
{
  EEPROM.get(0, adres);
  pinMode(setpin, INPUT_PULLUP);
  pinMode(RELAY_PIN, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();

void loop() {
  if (irrecv.decode(&results)) {
    // If it's been at least 1/4 second since the last
    // IR received, toggle the relay
  //  if(&results == adres){
      dump(&results);
      if (millis() - last > 250) {
        on = !on;
        if(on == true && adres == irbuffer){
          delay(5000);
          digitalWrite(RELAY_PIN, on ? HIGH : LOW);
          dump(&results);
        }else if(on != true  && adres == irbuffer){
          digitalWrite(RELAY_PIN, on ? HIGH : LOW);
          dump(&results);
          delay(5000);
        }
      }
    //}
//    Serial.println(dump(&results));
//    Serial.println(count, DEC);

    eeprom_writer();
    last = millis();
    irrecv.resume(); // Receive the next value
  }
}

Changing the internal oscillator to 8MHz helped.


Reading and sending with Arduino? I am using Arduino in an IOT application where I have to read impulses coming from a sensor and send a mean value of these impulses without missing any impulse while sending the value so is it possible to achieve such operation knowing that Arduino is a single core chip.

I read about Protothreading libraries but it may miss an impulse during the check phase so I want to know if there is another solution

Although the Arduino only has one CPU core and can only execute one program instruction at a time, it's not limited to only doing one thing at a time.

An MCU is a complex device with lots and lots of peripheral devices built into it. The CPU is only one small block of the overall device.

Much of a program is merely instructions telling the peripherals how to perform.

For instance, when sending data through Serial the CPU doesn't say "Send this bit. Now wait. Now send this bit. Now wait again" - instead it just says "Here's this byte to send. Now go and send it and tell me when you're done". The UART peripheral then sends the byte by itself with no further input from the CPU leaving the CPU free to do other things.

Then there's the Timer peripherals.  The CPU sets them up to count from a clock source, and do different things depending on different events, like a specific number is reached in the counting, etc. The CPU has no need to go "Count up one. Count up one. Count up one." - it just goes "Count up from 0 using this clock source and tell me when you reach 100" (for example).

Similarly, there are "External Interrupts". The CPU doesn't need to sit watching an IO pin all the time, going "Have you changed yet? Have you changed yet? Have you changed yet?" - it just goes "Tell me when you have changed" and the CPU goes off to do other things.

Of course, all these things have caveats. The biggest is that if the CPU is doing something very timing critical, such as "bit banging" serial data manually through a GPIO pin (for example with SoftwareSerial) it can be set to ignore all these interrupt signals from the peripherals. That means, if you're using an "External Interrupt" to count pulses, and you have to use SoftwareSerial to communicate, it's possible that SoftwareSerial's sending or receiving routines could cause the detection of a pulse to be either delayed (not really a problem) or to be missed completely.

So you don't want to use SoftwareSerial if it can be avoided if you want to use External Interrupts for this kind of operation.

The other option is to use a timer. I mentioned that they just count up from 0 (or they can count down, too) using a configurable clock source. That counting happens completely independently of the CPU, and carries on regardless of whether interrupts are enabled or disabled. And the great new is that most timers can be configured (depending on which Arduino you use) to use an external signal as the clock source for the counting.

That means you can configure a timer to count your pulses for you regardless of what the CPU is doing. All you have to do is every so often (how often depends on how frequently your pulses arrive - the timer has a limit on how many it can count before it overflows) ask the timer for what it has counted up to and reset its count to 0. That could be done as part of your "sending" routine. Get the count, reset it to 0, and send the results.


Problems splitting a string to get authentication and command Good afternoon,

In a nutshell I'm having some difficulty with splitting and returning part of a string.

Essentially I'm working on the code for transmitting a password (24 character string) and command (string) in a single packet. However, the 'get_command' function is only returning the first character of the string (T) as opposed to the whole string (T1) and I'm not sure why. Any help would be greatly appreciated. Thanks in advance.

The entire sketch is below so you should be able to just drop it in and compile.

char *received_data = "KkV3vKvLgC4PdBZRs5kkKM86T1";
char *password = "KkV3vKvLgC4PdBZRs5kkKM86";

int authenticate_transmission(char *data) {
    if(strncmp(data, password, 24)) {
        Serial.println("no match");
        return false;
    } else {
        Serial.println("match");
        return true;
    }
}

char *get_command(char *data) {
    char command[3];
    strncpy(command, data + 24, 3);
    // Fine here
    Serial.println(command);
    return command;
}

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

void loop() {
    // test received data - message is T1 at the end.
    if (authenticate_transmission(received_data)) {
        char *command = get_command(received_data);
        // But just prints out first char when returned from a function
        Serial.println(*command);
    }
    delay(10000);
}

The command array created inside get_command() is local data. That means it's only available while that function is being executed.

However, you're returning a pointer to it. That means when you're trying to use command afterwards from inside loop(), you're trying to refer to data which has been deallocated. By that point, it's getting used for something else.

There are various solutions to this. A fairly simple approach would be to have the caller allocate the command array, passing a pointer to it into get_command(). For example:

void get_command(char *data, char *command) {
    strncpy(command, data + 24, 3);
}

From loop(), you would call it like this:

char command[3];
get_command(received_data, command);

The command array is still local data in this case. However, it's local to the loop() function (or wherever else you put that code). That means it will still be available when get_command() is called.


Built-in capacitive touch detection with SAMD21 development board (Arduino Zero Compatible) I bought this SAMD21 development board which shows up as an "Arduino/Genuino Zero (Native USB Port)" when plugged in. And I've successfully got a blink sketch running on it all good so far:

The reason I picked up this board was to experiment with the built-in capacitive touch sensor on the SAMD21. In the datasheet for this chip it claims to support a 'Peripheral Touch Controller with 256-Channel capacitive touch and proximity sensing'.

Does anyone know what this exactly means and how I would access this functionality to detect touches in my Arduino code? Obviously there are not 256 IO pins so how would this work? Is there some kind of internal multiplexer?

The 256 channel capacitive touch controller is also mentioned in a Sparkfun video about their SAMD21 board, so it must be possible to access this functionality.

Can someone direct me towards an Arduino library or method and more information on the wiring and pin connections for this. Thanks.

You have three options for the silicon-based PTC (peripheral touch controlller).

LibrePTC - My own library that targets the SAMD11 but should work with some modifications for other SAMD architectures. The README file has lot of information on how the PTC works and how to specify designs for it.
Adafruit FreeTouch - Works only with the SAMD21. Given the high quality of the register documentation, I suspect they may have had inside help from Atmel but I haven't been able to reach Ladyada, their primary contributor, to learn more.
QTouch, which is Atmel's library available in closed source only but is extremely feature-rich. Arduino team decided not to allow closed source stuff in their IDE so its been banned from official distributions. However, it is possible to hack it into the Arduino IDE and I've used it successfully that way. However this requires esoteric modification to boards.txt that are beyond the scope of this answer.

The PTC hardware peripheral on the SAMD chips works on self-capacitance using "Y" lines specified in the data sheet. See the README on LibrePTC for details. Some chip variants have more pins broken out. For instance, the SAMD21G has fewer available Y pins than the SAMD21J, although the J series is not as readily available in breakout boards as of the summer of 2017 and it has limited Arduino IDE support. I personally prefer the SAMD11 because it is cheaper ($1.00) and has way more available Y lines in the QFN package.

As of August 2017, I intend to attempt a merge between the Adafruit and LibrePTC libraries but no guarantees when this will happen. I don't have access to insider documentation so my library was 100% reverse engineered through trial and error.


How to make a pairing and mode button on a remote control receiver I'm working on a remote control project and have come across many different RF receiver/transmitter modules. Many have a pairing/mode button on the receiver that serves to pair the receiver and transmitter and to choose which mode the transmitter is in, momentary, latching, toggle, etc.

How can I replicate this feature using Arduino and those cheap RF transmitter/receiver combos on Ebay? Specific code would be nice, but just a general idea as to how it would be done in theory will work too. I've watched several tutorials that explain the use of the Radiohead library with the cheap RF combos, but none demonstrate how to set up a feature such as this. Thanks.

Remote sends a number before the command bits. The receiver checks if this number is the same with the number that corresponds with the position of the switches.
You can do the same in software. Have the first few bits be some number. The receiver can then check if the first few bits of the received "message" matches that number. If it doesn't it will just throw it out.
This is the same method used with IR-remote controls. The signal from your VCR remote will also be received by your TV. But the TV sees that the code doesn't match the one it's expecting. So it will ignore those.


Automotive Lighting Control Module I am looking for an Arduino-based solution for an automotive lighting application.

System Requirements:

Able to Operate in Automotive (Interior) Environment (12 +/- 2V DC    Voltage)
Minimum 3 12 V DC Inputs (Preferably 6)
Minimum of 3 12 V DC Outputs capable of operating standard automotive-style
relays. (Preferably 6)
Compact/Condensed Form-Factor

Finding an Arduino that runs on a 12 V power supply is simple, but finding one that can handle 12 V I/Os has proven tricky.

Using a relay shield for the outputs is straightforward enough, and would be a safe way to step up the output voltage and current (although current is of little concern, given I'm only going to powering the coil in a relay). But what to do about the inputs? I don't want a transistor on each input - that would get quite tedious and large very quickly. Using relays on both sides would work, but most shields are setup to receive coil activation signals from the Arduino and as such also can't handle 12 V inputs, so using a relay shield to step-down from 12 V to 5 V also seems problematic.

Is there an all-in-one I/O solution that can step-down incoming voltages for the board and step-up output voltages on the other side?

What are my best options? I'd prefer not to have to custom-make a shield for such a basic I/O application...

Any and all help is greatly appreciated!

A Logic Level Converter can step-down incoming voltages for the Arduino inputs and may also work to drive the relay coils. Heres an example of a 4 channel board:

https://www.sparkfun.com/products/12009

and there are also 8 channel boards:

http://www.ebay.ca/itm/8-Channel-I2C-IIC-Logic-Level-Converter-Module-Bi-Directional-for-Arduino-MF-/172424799119?hash=item282551a38f:g:6Q0AAOSwo4pYPDwg.

The boards are small and use BSS138 MOSFETs, which, according to the data sheet: http://cdn.sparkfun.com/datasheets/BreakoutBoards/BSS138.pdf can handle a maximum of 0.22A continuous current and a Drain-Source Voltage of 50V. The SparkFun link has lots of information about these devices. Normally, you would use them to translate between 5V and 3.3V but I don't see why you couldn't power the "high voltage side" with the vehicles 12 - 14V and the "low voltage side" with 5V from the Arduino.


Arduino Compiling Error I recently format my  Windows 8 and installed Windows 8.1 . In Windows 8, I was using Arduino IDE and there was no error in compiling.But then I installed Windows 8.1 and re-installed Arduino IDE.I tried various codes for motor drivers and everything but they didn't compile.So, I tried to compile blink LED example first and even it didn't compile.It shows the following error on UPLOADING BLINK LED Example-

Arduino: 1.8.2 (Windows 8.1), Board: "Arduino/Genuino Uno"

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries C:\Users\Admin\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10802 -build-path C:\Users\Admin\AppData\Local\Temp\arduino_build_754363 -warnings=none -build-cache C:\Users\Admin\AppData\Local\Temp\arduino_cache_657645 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -verbose C:\Program Files\Arduino\examples\01.Basics\Blink\Blink.ino
C:\Program Files\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries C:\Users\Admin\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10802 -build-path C:\Users\Admin\AppData\Local\Temp\arduino_build_754363 -warnings=none -build-cache C:\Users\Admin\AppData\Local\Temp\arduino_cache_657645 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -verbose C:\Program Files\Arduino\examples\01.Basics\Blink\Blink.ino
Using board 'uno' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\sketch\Blink.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\sketch\Blink.ino.cpp" -o "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\preproc\ctags_target_for_gcc_minus_e.cpp"
exit status 1
Error compiling for board Arduino/Genuino Uno.

I tried RE-installing the software and drivers.It didn't work

Why is this happening?What is the Solution?

Right click on the Arduino icon, select properties. Under the compatibility tab, check "Run this program in compatibility mode" and select Windows XP. You might also want to run it as administrator.

This should hopefully solve the issue.

Source


Why are some letters reserved? I wrote a function that takes characters and noticed that the Arduino Compiler treated some characters like system-reserved, and other like functions, and a few just like characters. Lowercase doesn't seem to be effected.
I'm just wondering why.

The Arduino IDE does keyword coloration according to a very crude system. It simply scans for all the keywords.txt files included with:

Arduino IDE
Libraries bundled with the Arduino IDE
Libraries you have installed to the libraries subfolder of your sketchbook
Libraries bundled with the hardware package of the currently selected board - Hardware package of the currently selected board (recent IDE versions only)

There are several types of keyword identifiers that determine which color is used. The reason those letters are colored in your IDE is because some library you have installed just happens to have added them to its keywords.txt file.
The Arduino IDE makes no attempt to determine whether you have included those libraries and so coloration doesn't necessarily mean they are "reserved". If you have not included the library that defines a specific keyword then the coloration of that keyword is meaningless.

For more information on keywords.txt see:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#keywords


Measuring power consumption on Arduino off of DC supply I am working on a project involving the Uno, and I would like to benchmark the power requirements of Arduino. I am using the external 9V supply option.

Specifically, the Uno will be in to states,power-intensive and power-save. In the first mode, I am doing some heavy processing tasks (RF and some sensors are the only external loads), and the Arduino typically runs loop() without any delays. In the second mode, loop() is execued about every 10-40 seconds.

I am interested in benchmarking how much power is consumed in both states (I need this to estimate the size of the battery required for the 9V supply).

Obviously, googling yielded me solutions that involved measuring current using chips in series with the supply (I probably can pull this off with a multimeter). What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

The Uno cannot measure its own power consumption. Indeed, a Uno which has a voltage regulator, power LED, and USB interface chip is not your ideal solution for low-power applications.

See Power saving techniques for microprocessors


SPI Arduino Due conflict with pinMode(), bug? Consider the following minimal example, where I set pinMode before calling SPI functions:

#include <SPI.h>

void setup() {
  pinMode(10, OUTPUT);
  SPI.begin(10);
  SPI.setDataMode(10,SPI_MODE1);
}

void loop() {
  delay(1000);
  SPI.transfer(10,1);
}

Now when SPI.transfer(10,1) is called in loop(), I always see that the slave selected pin goes down to 1.65V, but not 0 as it should! (see image below)

If we don't call pinMode(), like this:

#include <SPI.h>

void setup() {
  SPI.begin(10);
  SPI.setDataMode(10,SPI_MODE1);
}

void loop() {
  delay(1000);
  SPI.transfer(10,1);
}

We get what we would expect when calling SPI.transfer:

Is that a bug or do you have an explanation for that behaviour?

Thank you very much in advance for your time and interest!

It might have something to do with the internal pull up resistor. According to the SAM3X/A datasheet,

Control of the pull-up resistor is possible regardless of the
configuration of the I/O line.
After reset, all of the pull-ups are enabled.

If you dig through all the include files you find:
../Arduino/hardware/arduino/samd/cores/arduino/wiring_digtal.c

Line 124 defines the pinMode(uint32_t ulPin, uint32_t ulMode) function. Examining the switch/case statement for INPUT vs INPUT_PULLUP vs OUTPUT you see the following:

INPUT sets a register to reg = PORT_PINCFG_INEN.
INPUT_PULLUP sets a register to  reg = (PORT_PINCFG_INEN | PORT_PINCFG_PULLEN)
OUTPUT sets a register to reg &= ~PORT_PINCFG_INEN.

The 'register' in each case is the same. I cannot for the life of me find what value PORT_PINCFG_INEN or PORT_PINCFG_PULLEN are defined as, but they're no doubt just 8-bit masks (they're cast to uint8_t when they're assigned to the 'register'). Thus, we can assume that whichever bit controls input/output is active when asserted, as is the pullup bit. For example:
 PORT_PINCFG_INEN   = b'00000001';
 PORT_PINCFG_PULLEN = b'00000010';
~PORT_PINCFG_INEN   = b'11111110';

If pull-ups are enabled after reset, we can say that on reset:
 reg = b'xxxxxx1x';

Point (3) above strongly implies that the instruction is:
 reg = b'xxxxxx1x' & 'b11111110';
   so
 reg = b'xxxxxx10'; // pull-up is enabled!

Therefore, if you call pinMode(X, OUTPUT) before anything else you will end up with the pullup resistor enabled. Setting the pin to an input will clear the pullup enable bit, after which you can set the pin to an output and the bit will remain clear.
However, the whole arguement falls down with the simple fact that if you don't call pinMode() at all, the problem doesn't occur...


Using Sprintf() to left pad a string? I've been at this all day, and I just can't seem to wrap my mind around how to use sprintf() to set a width for my string so that my characters are right justified.

What I'm trying to do is scooch my output over to the right on my touchscreen when the value is positive.
My output string is always a predictable length, so it seems like it should be easy.
I tried concatenating a string with just a space in it, and every other way I could think of to add a space to the beginning of my string. No luck.

char stringval[8] = 1.08;
char juststringval[8];
            if (hashpos > 0 && hashpos < 10) {

                sprintf(juststringval,  " %5s" , stringval);
                Serial.println(juststringval);
            }

output:

1.08 (no spaces in front)

In case you're curious why I need to use a string, my touchscreen will print floats, but my library won't rotate them properly.
Only strings can be rotated the way I need them.

Isn't there some simple way of doing this?

EDIT:

It seems I can use the width trick as long as I include some character besides an empty space.
For example:

void setup()
{
char stringval[33] = "1.08";
char juststringval[33];
char space[] = "rr";         ////THIS WORKS: OUTPUT IS  rr      1.08
float hashpos = 1.08;
if (hashpos > 0 && hashpos < 10) {

    sprintf(juststringval, "%s  %7s", space, stringval);
    Serial.println(juststringval);
}
}

void setup()
{
char stringval[33] = "1.08";
char juststringval[33];
char space[] = " ";     ////THIS DOESNT WORK. OUTPUT IS 1.08 LEFT JUSTIFIED
float hashpos = 1.08;
if (hashpos > 0 && hashpos < 10) {

    sprintf(juststringval, "%s  %7s", space, stringval);
    Serial.println(juststringval);
}
}

But I can't live with other characters in my string.
Isn't there something I can do?

The mistake in question and in comments (except of Bigoldsofty's comment), is missing character for justifying. This character should be in format string before the required width. "% 5s" not "%5s"


Installing a different firmware on Arduino Is it possible to upgrade the firmware on an Arduino so that it can do more things such as change undervolting/ overvolting in order to provide more processing power. To do this you would have to most likely re flash the chip itself, so how would that be accomplished?

To answer the aspect of your question regarding the "firmware" on the ATmega328p MCU used in most of the Arduino boards:

There is no firmware on the ATmega at all aside from the bootloader. The programs you write are running directly on the hardware.

There are certain "fuse" settings which are set with a ISP programmer. However, there are only 24 of them (three bytes), and they largely relate to low-level configuration, and are not what I think you're asking:

There is also the Bootloader, which is a small program that sits in a separate segment of the MCU's program memory and allows it to update itself at startup (which is how all arduinos are programmed). However, it only runs for a short period of time at startup, and is completely removed from memory after the MCU has jumped to the main program.

Lastly, there are auxiliary MCUs (ATmega16U2/8U2) on most arduino boards that are used as USB-serial interfaces, that can be updated to behave differently (e.g. emulate a keyboard/mouse), but again, this isn't actually a change to the core processor, so whether it counts as "installing a different firmware" depends on how you define the arduino.

Really, I'd strongly reccomend reading the ATmega328P datasheet. This is the documentation for the MCU that basically forms the "Arduino". It should address what seems to be misconceptions.


Works with gcc, not with Arduino. error: taking address of temporary array I need to hard code 8 byte addresses into char arrays of length 8. This must be done many places in my code (in function scope), so I have tried to come up with a one-liner. The following works perfectly in C when compiling with gcc.

char a[8];

void cpaddr(char target[], char *source) {
    int i;
    for (i=0; i<8; i++)
        target[i] = source[i];
}

int main() {
    char b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
    cpaddr(a, b);

    // line below does not compile with Arduino IDE
    cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
}

When compiling on Arduino the last line, which is the one-liner I was aiming for, does not compile. It gives:

/home/bob/Desktop/ate/Ate.ino: In function 'int main()':
Ate:101: error: taking address of temporary array
cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
^
exit status 1
taking address of temporary array

What is the problem here, that apparently is not a problem with gcc?

How do I fix it?

It is quite right, using that kind of syntax is not allowed. It's a bit of a pain, but it's ok since there is an alternative method - kind of a "trick" if you will.

That trick is to use a string, not an array. After all, a string is just an array, it's just handled slightly differently by the compiler.

Instead of using {...} use "..." and use the hexadecimal character escape sequence \xNN, such as:

cpaddr(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D");

You could even lose your custom function and use a standard library function - memcpy():

memcpy(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D", 8);

On the 8-bit AVRs you can save RAM by using the progmem variant and the F() macro:

memcpy_P(a, F("\x00\x10\xFF\xCA\x00\x00\xA2\x7D"), 8);


Arduino port recognition New Arduino Uno, Arduino 1.6.3, MBP running 10.10.5.

The Arduino IDE is running, I connect to the laptop via usb. The green LED is on the amber light is on but it's not blinking.

I attempted to upload the blink file from File>Example>Basic>Blink. It compiles without issue but won't upload. I get the can't open device "/dev/cu.usbmodem1421" : No such file or directory...

I have attempted using the reset button, changing ports, cycling the IDE and the computer. The killer is that I've had an Arduino on this laptop before.

Any suggests for getting the Arduino linked and operational.

Sorry to dredge up an old thread (well, really only replying to one that got robo-dredged :), but maybe this will help someone someday.

A /dev/cu.<something> is a unix port designation. "cu." meant a port used for modems, back in the mists of time but probably isn't relevant today. But what we do learn from it is that the OP is probably using a Mac, and for sure, not Windows.

"/dev/cu.usbmodem1421" is a typical device name for an Arduino as seen by a Mac on a particular one of its USB ports - the numeric part varies according to which Mac USB port the Arduino is connected to each time.

Arduinos & FTDI devices do not need additional drivers on Mac OS (that may not be true for other, non-FTDI USB-to-serial devices).

In this case, the OS already reports seeing (what looks like) an Arduino. The suggestion already put forward, checking the board-type and port selections in the IDE's 'Tools' menu, is the place to start.


Light only half of the LEDs How can I only let half of the LEDs light up,
for example, LED 1 on, LED 2 off, LED 3 on...and so on.

I did it this way
(this example fades also all LEDs on and off)

   int x = 1;
   for (int i = 0; i > -1; i = i + x){
      leds[0] = CRGB(i,0,0);
      leds[1] = CRGB(0,i,0);
      leds[2] = CRGB(i,0,0);
      leds[3] = CRGB(0,i,0);
      Serial.println(i);
      FastLED.show();
      if (i >= 55) x = -1;             // switch direction at peak
      delay(10);
   }

but that is not so nice if you have 100 LEDs or so.

I don't know much about neopixel but as a general coding practice if you want to do something for every other object, you use the modulus operator like so

if(i % 2 == 0)
{
  //i is even
  //off
}
else
{
  //i is odd
  //on
}

So just wrap your current for loop in another one and to the above with the iterating variable.


EEPROM size limitation issue I am creating a test program with Arduino Nano where I can save network and password. Here is my code to start with:

void SaveNetwork(String ssid, String pass){
  String com = ssid + "~" + pass;
  const char *array = com.c_str();
  for(int i = 0; i<sizeof(com); i++){
    EEPROM.write(i, array[i]);
  }
  Serial.println("Saved");
  char ar[255] = "";  //test read string.
  for(int i = 0; i<sizeof(com); i++){
    ar[i] = EEPROM.read(i);
  }
  Serial.println(ar);
}

SaveNetwork("Testing", "Network123......");

Now I print ar string which is suppose to return ssid, "~" and password.

BUT what I get is "Testin" instead of "Testing~Network123......".

Is there is a limitation for EEPROM size? If so, how can I expand the capacity, should I use a memory chip, or what is the code I should use to resolve this?

The problem is with sizeof(com) in your loops. sizeof() is for C arrays, not string objects. If you print it, it will report 6, which is not the length of the array. For string objects you should use com.length() instead. Then the output becomes

Saved
Testing~Network123......

P.S. The EEPROM can store 1024 bytes on ATmega328P-based boards (I believe that's what most Arduino Nanos use (clones included).


How to create custom bootloader with accompanying program loader for ATMega2560 Just for some context, I have created a custom board based on the ATMega2560. I currently have the original Arduino Bootloader for the ATMega2560 and have no problems uploading code via the USB Port on TX0 and RX0.

What I am hoping to achieve is creating a custom Bootloader that allows me to upload my .hex binaries to flash but in a proprietary way, so that any program cannot be uploaded to it with the standard Wiring Protocol used by Arduino IDE. In addition, I will need a custom PC based program that can upload the code via the USB port.

The reason why I need this is that I will have this device out in areas where I would not want someone taking the device and uploading their own program to it and screw it up. I know it sounds paranoid, however, it would be preferred to have this feature so I can update the firmware via the USB Port without using the Wiring protocol.

Has anyone accomplished this before?

TL;DR

Want to upload custom Bootloader to Arduino Mega so that I can upload my firmware with a proprietary programmer via the USB Port on TX0 and RX0 because I am paranoid.

The source of the bootloaders is publicly available, so a simple thing would be to make a minor modification, for example XOR each incoming byte with 0xEE. That would mean the bootloader wouldn't work with normal uploading programs (the IDE) but with a modified uploader.

However even simpler would be to upload your code using ICSP and not include a bootloader at all. Or, leave the bootloader there but turn off the BOOTRST fuse so that the processor ignores it.

That way, it takes some effort for people to replace your code.


Reading multiple cases on Serial I am using a Leonardo board and am testing the APIs in the Serial type. The board is talking to a screen using serial.

The pseudo code is as follows (I show code relevant to Serial):

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

void loop(void) {

    if(Serial.available())
    {

        if (Serial.find(0x30))
        {
             func1();
        }

        if (Serial.find(0x31))
        {
             func2();
        }

    }

 }

 void func1()
 {
      // Serial.print() used multiple times

      asm volatile ("  jmp 0");
 }

 void func2()
 {
      // Serial.print() used multiple times

      asm volatile ("  jmp 0");
 }

I test using the Arduino IDE (1.8.0) and its Serial Monitor. When I send 0x30 over serial, the first if case gets triggered to invoke func1, but when I send 0x31, I cannot get the second if case (func2) to get triggered. This even happens when I test 0x31 first; the second if case never gets triggered. Can someone tell what I am doing wrong here and what is the right way to use serial ?

Edit For testing, one can use the pseudo code itself; I tested using different number of LED blinks in func1 & func2, and the problem still holds.

Edit 2 Based on Dave's answer, I tried a test with serial using sample code from

I did another test where I used the sample loop code for read (https://www.arduino.cc/en/Serial/Read) and tried typing 0 or 1 through serial monitor. I observed the following:

// Typed 0
I received: 48
I received: 13
I received: 10
// Typed 1
I received: 49
I received: 13
I received: 10

It is looping faster than the serial is delivered, so each time there is a byte delivered, it tests it against 0x30 until nothing is left, and then drops out, leaving nothing .available() for the next if(), so it fails out as well and starts up the loop() again.

I'd read a byte at a time and work with that:

int incomingByte = 0;   // for incoming serial data

void loop(void) {

if(Serial.available())
{
    incomingByte=Serial.read();

    if (incomingByte == 0x30)
    {
         func1();
    }

    if (incomingBute == 0x31)
    {
         func2();
    }

}


Analogue input 0 staying at 0 when sensing light with Arduino and a photocell I am doing a circuit for capturing light intensities.

I followed the tutorial provided by Adil Moujahid

Yet, when I plug the jumper wires on 5V the circuit stops working and when I plug on 3.3V the analog in A0 sent back only a series of zero...

What did I missed? I acknowledge that I tried to be the most economical on the jumper wires...

The sketches, program and circuit given by Adil Mouhajid

My attempt

The two strips on either side of the bread board, color red and blue (typically) are power rails, and each strip is all connected. Your circuit connections that are on that strip are shorted together and will not work. I suggest following his layout exactly to begin with, and once you've learned the basics of breadboard connections, you can start doing your own layouts.


Extending EEPROM life I'm working on some software using an Uno (ATmega328P). I have a stage byte that can be 1 of 5 values (0-4) in my code and it will increase by 1 every 2.5 hours. If I lose power I need to ensure that on wake up the stage is the same as it was at the time of power loss, so each time the stage is updated I save it to EEPROM.

To ensure the EEPROM lasts as long as possible I want to write some code that uses more than a single byte which I continually erase and write to. I was wondering if there is any library to do this or if my idea below would work?

I currently don't need to use the EEPROM for anything else so to extend the EEPROM life I was going to section of 1 quarter of it (0-255 bytes) for saving this value. Each time I change the stage I will write 3 bytes to EEPROM which will be:

An index byte (used to shift addresses I write to).
A stage byte (the stage I need to store).
A count byte (the amount of times I have wrote the stage at the current index).

To begin with the index will be written to byte 0 in the EEPROM, the stage to byte 1 and the count to byte 2.

My plan is to allow the stage to be written to byte 1 250 times, then clear the count and shift the index to 3. This will in turn move the bytes that the stage and count are being written to to 4 and 5. I will do this until the index reaches the end of the 255 bytes and then return the index to 0. So in total I should be able to shift 85 times.

Each byte has 100,000 erase/write cycles so this means I can pass through bytes 0-255 400 times, writing the stage 250 times each pass. So instead of having 100K writes I would have about 8.5 million writes.

This is my first idea and I realize there is also some waste in the way I do it. I haven't worked with EEPROM much and I was just hoping for some advice as I'm sure I could be going at this completely wrong.

You can load spread by saving the current value ORred 0x80 or 0x00.

When writing you write to the next memory location and when it wraps you take the other value to OR with.

The values in the eeprom will be

[{0x00|value},{0x00|value},{0x00|value},...,{0x00|value},{0x00|value},{0x00|value},{0x80|value},{0x80|value},{0x80|value},...,{0x80|value},{0x80|value}]

or

[{0x80|value},{0x80|value},{0x80|value},...,{0x80|value},{0x80|value},{0x80|value},{0x00|value},{0x00|value},{0x00|value},...,{0x00|value},{0x00|value}]

Then you read the first and last byte and if the upper bit is equal you take the last value.

If they are not equal you binary search until to the position changes, the most recent value will be the one right before the change.


How to run stepper motor at its maximum speed I am running a stepper motor using arduino and IC l293d. What is the maximum possible speed of rotation that I can achieve with the IC and what should be the applied voltage for the same? Earlier, I got the optimum rotation with a step size of 30 at 7V. I want to increase the step size. What should I do?

As this link states:

  Stepper motors are normally used for positioning, and are not known
  for their speed.

However, the link is to an on line stepping motor speed calculator.

As for the size of the step, this is a function of the way the stepping motor is built.  Some controllers / stepping motor combinations can do half steps or micro steps.  Disable these feature for the fewest number of steps per revolution.

These are some of the basic concepts which deal with practical stepping motor applications.  As speed increases, other factors come into play.  For example, resonance and inductance.

In this paper resonance is discussed:

  If a rigidly mounted stepping motor is rigidly coupled to a
  frictionless load and then stepped at a frequency near the resonant
  frequency, energy will be pumped into the resonant system, and the
  result of this is that the motor will literally lose control.

The paper also discusses the effect of the stepper motor's coil inductance:

  An important consideration in designing high-speed stepping motor
  controllers is the effect of the inductance of the motor windings. ...
  The inductance of the motor winding determines the rise and fall time
  of the current through the windings. ...


What is the frequency of PWM output on Arduino What frequency do Arduinos use for normal PWM when you use analogWrite()?

And is it different for different Arduino model? I'm interested specifically in the Mega 2560, but also want to know if it's consistent between models.

I've seen a passing references to the Arduino using 500 Hz, which seems really slow.

The PWM signal is generated by timers on the AVR chips. Each timer can generate a PWM signal on two or three different pins. Each pin can have it's own duty cycle, but they share the PWM frequency. You can change the frequency of the PWM by changing the clock source for the timers. By default they use the CPU clock divided by 64, ie. they have their prescaler set to 64 by Arduino initialization code.
  To confuse things more there are two different PWM modes: fast PWM and phase correct PWM. In fast PWM the timer counts to 255, then overflows and starts over from 0 (256 different states). In phase correct PWM the timer counts to 255, then changes direction and counts downwards to zero, changes direction and so on (510 different states).

The Arduino Mega has 5 timers, timer0 - timer4. Because timer0 is also used for the millis and micros functions it uses fast PWM, whereas the other timers are configured for phase correct PWM. This results in different frequencies on different pins:

Pin 4 and 13, controlled by timer0:
16 Mhz / 64 / 256 = 976.56 Hz
Other PWM pins, controlled by timer1-4:
16 Mhz / 64 / 510 = 490.20 Hz

The calculation is: Clock / Prescaler / PWM mode number of states

The situation is the same for all other Arduino boards I know of, except they have less timers that connect to different pins.

You can change the PWM frequency by changing the timer prescaler. See this page: http://playground.arduino.cc/Main/TimerPWMCheatsheet

It is also possible to make the timers count to a different value than 255. On the 8 bit timers you will loose an output pin, but on the 16 bit timers you can use the Input Capture Register to define a TOP value. The input capture functionality is a feature rarely used in the Arduino community so you likely won't miss it.

The Arduino libraries only allow you to use 8 bit resolution, even on the 16 bit timers. If you want the higher resolution, you will have to write your own analogWrite, or use a library made for the purpose.
On the Arduino Mega timer0 and timer2 are 8 bit, while the rest are 16 bit.

By changing the mode of the 16 bit timers to make use of the full resolution, in combination with changing the prescaler and the TOP value, you can achieve a very wide range of PWM frequencies.

The maximum frequency you can achieve is clock / 4, by setting the prescaler to 1 and TOP to 3 in fast PWM mode - a lower value isn't allowed. This will give you a 4 MHz PWM with 2 bit resolution. It can be on 0%, 25%, 50%, or 75% of the time. A higher TOP value will give you a higher resolution at a lower frequency.

For a longer explanation read this article or refer to the datasheet.

Changing the prescaler, PWM mode, or TOP value for timer0 will mess with millis() and micros().


How can I set two PWM at two different frequencies? I'm using the arduino uno hooked up to two LEDs. One is in pin 3 and the other one in pin 5. I know that pin 3 is controlled by timer3 and pin 5 by timer 1. I've tried a lot of things to have two independent frequencies. I really don't care about the PWM, I have it to 50% (constant).

There are resources to set the frequency (http://playground.arduino.cc/Main/TimerPWMCheatsheet), but these are predefined frequencies. I need to have one PWM at 650Hz and the other at 850Hz.

Any recommendations on how to approach this problem?

The ATMega PWM hardware underlying the Arduino primarily supports changing the duty cycle; the frequencies can only be selected from a few fixed choices.  Typically the timers run from 0 to 255 or 65535 and loop back to 0, and you can select where within that full cycle the output changes on and off.

Since what you want is a simple 50% duty cycle with fine control of frequency, the PWM functions are not very useful.  What you want is tone or frequency control.  The ATMega timers support this too, but it's a different function than PWM. For frequency control, the timer will cycle from 0 to your choice of upper limit.  So for example, you might count up to 200 instead of 255; or to 201 - so you get much finer control of frequency.

Unlike PWM, on the ATMega328p used in the Uno, you can only get one frequency per timer (you can get two PWM outputs per timer - both at the same frequency).  And if you want millis() and microseconds() and delay() to continue to work, you don't want to mess with timer 0 for frequency control (you can get PWM from timer 0 if you accept the default frequencies).

So that leaves you with two frequency controllable timers - timer 1 (16 bit resolution) and timer 2 (8 bit resolution).

See the tone() function in the Arduino library for examples of a single tone at a time.

For multiple simultaneous frequencies (on different pins) see this library: https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation.  You can have two tones at a time, or three if you don't need millis() etc.


ATTiny85 and DHT11 - Sensor always returning 0 Good day.

I am making a small weather station using ATTiny85, DHT11, and an OLED display.

There are many, many tutorials that explain how this works, and various libraries that show you how to get the DHT11 to work with the ATTiny85 and others that are dedicated to the SSD1306 Oled displays, some even show you how to combine them together. Well, for the better part of 2 days nothing worked for me.

My schematics is as follows:

And here is a picture of the actual thing, working with a CR2032 Coin Cell:

The Libraries I am using are:

OLED Libraries for ATTiny85 - Source: http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/
Rob Tillaart DHT Library - Source: https://github.com/RobTillaart/Arduino/tree/master/libraries

My Code is as follows:

    //OLED Libraries for ATTiny85 - Source: http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/

#include <font6x8.h>
#include <font8x16.h>
#include <num2str.h>
#include <ssd1306xled.h>
#include <ssd1306xled8x16.h>
#include <SSD1306_minimal.h>
#include <TinyWireM.h>
#include <USI_TWI_Master.h>

#define DEG "\xa7" "C"

SSD1306_Mini oled;

char strHum[4];
char strTemp[4];

#include <dht.h>
dht DHT;
#define DHT11_PIN 1

void setup()
{

  TinyWireM.begin(); // initialize I2C lib - comment this out to use with standard arduinos
  oled.init(0x3c);
  oled.clear();

}

void loop()
{

  //            DHT Code goes here                              //

  DHT.read11(DHT11_PIN); //Calling the read function

  float hu  = (DHT.humidity, 1);
  float te  = (DHT.temperature, 1);

  //            OLED Start -- DO NOT CHANGE ANYTHING            //

  //oled.clear();

  oled.startScreen();
  oled.cursorTo(10, 0);
  oled.printString("ATTiny85 & DHT11");

  oled.startScreen();
  oled.cursorTo(12, 9);
  oled.printString("Temp & Humidity");

  oled.startScreen();
  oled.cursorTo(10, 18);
  oled.printString("www.MDChaara.com");

  oled.startScreen();
  oled.cursorTo(0, 27);
  oled.printString("mdchaara@gmail.com");

  oled.startScreen();
  oled.cursorTo(0, 45);
  oled.printString("Humidity(%): ");

  oled.startScreen();
  oled.cursorTo(110, 45);
  oled.printString( itoa(int(hu), strHum, 10));

  oled.startScreen();
  oled.cursorTo(0, 55);
  oled.printString("Temperature(c): ");

  oled.startScreen();
  oled.cursorTo(110, 55);
  oled.printString( itoa(int(te), strTemp, 10));

  //            OLED End          //

  delay(5000);
}

Now I know that the OLED code works, and it was a very interesting round or research to get it to work. The DHT code is another story. I have tried 6 different libraries and none of them worked. They all either return 0, 1, or blank readings on the screen.

I have checked if the sensor is working with an Uno and a Nano, works well! I checked the connections, and the soldered parts and did continuity tests, but the issue still remains.

I am asking because I am hoping a fresh set of eyes can pin-point the issue that I am facing. Any help will be highly appreciated.

Arduino IDE: 1.8.2
OS: Windows 7 64 bits
Micro controller: ATTiny85-20PU

Sketch is uploaded to the micro controller using Arduino Uno as a programmer.
Sketch is uploaded at Internal 8MHz clock setting.

Thank You.

Ok i tried something like that for myself and thanks to this and ..many other posts and forums/videos i could make myself something that works but with a little other setting like in the start post (other libs ect)

in my case the main reason for the "1" output on the oled was this:

  float hu  = (DHT.humidity, 1);    //original

  hu  = (DHT.humidity);       //what worked for me

Maybe you can figure out more Problems, my code is shure not perfekt! But maybe it helps someone for a vew steps

#include <dht.h>
#include <U8x8lib.h>
#define DHT11_PIN 1
dht DHT;
int temp = 0;
int humi = 0;
char strTemp[4];
char strHumi[4];

U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ 2, /* data=*/ 0, /* reset=*/ U8X8_PIN_NONE);         // Digispark ATTiny85 Pin 0 Data, Pin 2 clock

void setup(void)
{

  u8x8.begin();
  u8x8.setPowerSave(0); //enegergiesparen 0 aus

}

void loop(void)
{

  int chk = DHT.read11(DHT11_PIN);

  temp = (DHT.temperature);
  humi = (DHT.humidity);

  u8x8.setFont(u8x8_font_chroma48medium8_r);
  u8x8.drawString(0,0,"~~~~~~~~~~~~~~~~");
  u8x8.drawString(0,1,"Temperatur");
  u8x8.drawString(1,2,( itoa(int(temp), strTemp, 10)));
  u8x8.drawString(4,2,"Grad Celsius");
  u8x8.drawString(1,3,"--------------");
  u8x8.drawString(0,4,"Luftfeuchtigkeit");
  u8x8.drawString(1,5,( itoa(int(humi), strHumi, 10)));
  u8x8.drawString(4,5,"Prozent");
  u8x8.drawString(0,6,"~~~~~~~~~~~~~~~~");
  delay(200);
}


How to create array of references? I have a class named timeOut dealing with timeout tasks.

I'm to write a sketch, common for Sonoff basic and Sonoff Dual, meaning that I may have 1 task for Basic and 2 tasks for Dual.

Declaring instances looks like:

timeOUT timeOut_SW0("SW0",TIMEOUT_SW0);
timeOUT timeOut_SW0("SW1",TIMEOUT_SW1);

for code simplicity I'd rather create an array of references and call it using a for loop:

timeOUT TO[]={timeOut_SW0,timeOut_SW1};

is it the right way to call it as a reference ?

You can't. The C++ language doesn't support arrays of
references. You have the choice to either create an array of
objects:

timeOUT TO[] = {timeOUT("SW0",TIMEOUT_SW0), timeOUT("SW1",TIMEOUT_SW1);}

or an array of pointers:

timeOUT *TO[] = { &timeOut_SW0, &timeOut_SW1 };


Unstable reading from Raspberry Pi I'm trying to send a signal from Raspberry Pi GPIO to Arduino. I made a sketch that basically reads the state of the digital read, but the reading are very unstable. I understand that there is a floated voltage and the obvious solution is to configure the pullup resistor and connect the input to ground, but my goal is to read the incoming signal.
I'm using Arduino Mega 2560 and Raspberry Pi 2B.

I hope this info is enough!

As Majenko commented, you need to not only connect the data wires together but also the ground wire (from the Arduino to the Pi).

  ... the reading are very unstable ...

Without a consistent "ground reference" the readings would indeed be unstable.


How can I connect an ultrasonic sensor to my Arduino motor driver shield l239D when I don't have any space left? Can you tell me how many sensors I can connect to the l239D motor driver shield? I want to put an ultrasonic sensor and two infrared sensors. Is it possible?

you might have noticed that there are spaces for analog pins on the shield. All of those are free so you can connect your ultrasonic and IR sensor there. Talking about digital pins, some are free but some are not. So it is better to use the free analog pins instead of bothering about digital pins unless necessary. And your sensors will work fine on those analog pins


Programming options other than C++ Can I program my Arduino using any programming language other than C++? If so, which programming languages? What software would I need for compiling and loading my code onto the Arduino?

In theory, any compiler which outputs AVR assembly could be used (modulo limitations on code size, ram usage etc).

AVR backends exist for both LLVM and  GCC -- so in theory, with some effort, most languages which are supported by LLVM and GCC's front-ends could be compiled to AVR. A big question will be library support, etc.

Never the less, here's a couple of odd choices for the spirit of the question, rather than its letter [1].

AMForth, a forth dialect can be flashed onto an Arduino.
AVR-Ada: Ada for AVR micro-controllers.
BASIC: Bring back the Goto!

Oh, and you could write raw AVR Assembly!

[1]- I Haven't tried these though!


Waking Arduino from sleep with an ultrasonic sensor I have a parking guide using an ultrasonic sensor (HC-SR04), based on the instructions here. I'm trying to modify the code so that the Arduino goes to sleep after a certain period of inactivity (say, 30 seconds), and wake again when the sensor 'sees' a car drive into the garage. The code here shows how to wake it with a solar panel.

However, the way I understand it, the solar panel is able to wake the Arduino because it doesn't need external power to work (because it's a solar panel). Would it be possible to do the same with an ultrasonic sensor (HC-SR04), which does need power?

It'll be running off mains power, but I don't want it to be drawing power when it's not needed.

In order to make the ultrasonic sensor work, the Arduino has to run some code to control it.  So it won't do anything while the Arduino is asleep.

What you can do is have the Arduino sleep for some reasonable amount of time, wake up and read the sensor, and then go back to sleep.  Maybe wake it up once every few seconds.  Do you really need to react to a car in the lot the millisecond it pulls in?


nRF24L01 module using Mirf library was working and then stopped I have two nRF24L01 modules, they are both attached to a sensor shield that has special ports for this type of module, on Arduino Unos.

I have this code on the Arduino that is sending the signal:

#include <MirfHardwareSpiDriver.h>
#include <MirfSpiDriver.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <SPI.h>
#include <Wire.h>

//0 = stop, 1 = left, 2 = right, 3 = forward, 4 = backwards
long command;
long last_command;

long Joystick_1_X;
long Joystick_1_Y;
long Joystick_1;

void setup() {
  // put your setup code here, to run once:
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setTADDR((byte *)"serv1");
  Mirf.payload = sizeof(long);
  Mirf.config();
  Serial.begin(115200);
}

void loop() {
  Joystick_1_X = analogRead(A0);
  Joystick_1_Y = analogRead(A1);

  if(Joystick_1_X < 450){
     command = 1;
  }else if(Joystick_1_X > 600){
    command = 2;
  }else if(Joystick_1_Y > 600){
    command = 3;
  }else if(Joystick_1_Y < 400){
    command = 4;
  }else{
    command = 0;
  }
  if(command == last_command){
  }else{
    Mirf.send((byte *)&command);
    last_command = command;
   }
  }

and this code on the Arduino that is receiving

#include "SPI.h"
#include "Mirf.h"
#include "nRF24L01.h"
#include "MirfHardwareSpiDriver.h"

int TN1= 3;
int TN2 = 4;
int ENA = 9;

int TN4 = 5;
int TN3 = 6;
int ENB = 10;

long data;

void setup() {
 pinMode(TN1, OUTPUT);
 pinMode(TN2, OUTPUT);
 pinMode(TN3, OUTPUT);
 pinMode(TN4, OUTPUT);
 pinMode(ENA, OUTPUT);
 pinMode(ENB, OUTPUT);

 Mirf.spi = &MirfHardwareSpi;
 Mirf.init();
 Mirf.setRADDR((byte *)"serv1");
 Mirf.payload = sizeof(long);
 Mirf.config();
 Serial.begin(115200);
 Serial.print("begin");

}

void loop() {

  // put your main code here, to run repeatedly:
  receiveCommand();
  if(data == 1){
    left();
  }else if(data == 2){
    right();
  }else if(data == 3){
    forward();
  }else if(data == 4){
    backwards();
  }else if(data == 0){
    stop_rover();
  }
}

void receiveCommand(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();
    Serial.print(data);
  }else{
    Serial.println("No data to be recieved");
  }
}

void forward(){
  digitalWrite(ENB, HIGH);
  digitalWrite(ENA, HIGH);
  digitalWrite(TN4, HIGH);
  digitalWrite(TN3, LOW);
  digitalWrite(TN1, HIGH);
  digitalWrite(TN2, LOW);
}

void backwards(){
  digitalWrite(ENB, HIGH);
  digitalWrite(ENA, HIGH);
  digitalWrite(TN4, LOW);
  digitalWrite(TN3, HIGH);
  digitalWrite(TN1, LOW);
  digitalWrite(TN2, HIGH);
}

void left(){
   digitalWrite(ENA, HIGH);
   digitalWrite(TN1, HIGH);
   digitalWrite(TN2, LOW);
}

void right(){
  digitalWrite(ENB, HIGH);
  digitalWrite(TN4, HIGH);
  digitalWrite(TN3, LOW);
}

void stop_rover(){
  digitalWrite(ENB, LOW);
  digitalWrite(ENA, LOW);
  digitalWrite(TN4, LOW);
  digitalWrite(TN3, LOW);
  digitalWrite(TN1, LOW);
  digitalWrite(TN2, LOW);
}

This was working, and the rover did spin its wheels when the remote broadcasted a signal, but then it just stopped. The sensor shield says that they are plugged into the 3V port, I tried using the RF24 library and that did not work either.

Any help would be greatly appreciated.

Using the MIRF Library that I got from here, and then using this code to send

 Mirf.send((byte *)&command);
    while(Mirf.isSending()){
        }

and this code to receive

 if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();
else(){
}

I was able to get it to work


Arduino UNO/ZERO PRO, enough computing power for PID-controller? I am currently working on a project, where I design a PID-Controller for a 2-axis stabilization with brushless-propeller-motors.

My question is: Does an Arduino UNO have enough computing power to perform this task in a useful manner? Arduino UNO Specs

And secondly: If the UNO was really too slow for this task, would the newly released Arduino ZERO PRO perform at an acceptable rate? Arduino ZERO PRO Specs

Thanks for your help and inputs in advance!

Assuming you're not doing anything too fancy, yes, it should be fine.

There's even a library to do all the work for you: http://playground.arduino.cc/Code/PIDLibrary


Unexpected value change of 2nd Potentiometer I'm trying to connect 2 potentiometer (10k) and pass their value to Hairless Midi software (For Serial to Midi Bridge) the first pot is working fine but the second pot's value keep on changing and when i move around the knob of pot1 the value of pot 2 also changes.

I have tried reading the value twice but no luck....

My code:

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

void loop()
{
  analogRead(0);
   val = analogRead(0)/8;   // Divide by 8 to get range of 0-127 for midi
   if (val > lastVal+1 or val < lastVal+1 )
   {
   MIDImessage(176,1,val);}
   lastVal = val;

  analogRead(2);
   val2 = analogRead(2)/8;   // Divide by 8 to get range of 0-127 for midi
   if (val2 > lastVal2 + 1 or val2 < lastVal2 + 1 )
   {
   MIDImessage(176,2,val2);}         // 176 = CC command, 2 = Which Control, val = value read from Potentionmeter 2
   lastVal2 = val2;

   //val3 = analogRead(2)/8;   // Divide by 8 to get range of 0-127 for midi
   //if (val3 != lastVal3)
   //{
   //MIDImessage(176,3,val3);}         // 176 = CC command, 3 = Which Control, val = value read from Potentionmeter 3
   //lastVal3 = val3;

delay(100);
}

void MIDImessage(byte command, byte data1, byte data2) //pass values out through standard Midi Command
{
   Serial.write(command);
   Serial.write(data1);
   Serial.write(data2);
}

As I was having chat with @Maxmilian Gerhardt he suggested to check the voltage of pot 2 so when I checked I was getting 0 volt So he Suggested me there may be a loose connection or something with the beadboard.

So This was a workaround :

Thnx for the help @Maxmilian Gerhardt


Arduino Due connection with FLIR Lepton I'm trying to connect a FLIR Lepton to an Arduino Due. A thread by pureengineering talks of rerouting some pins. I am not sure what they precisely mean.

Does this rerouting mentioned in the link also apply to Arduino Due?

According to the highlighted part of Due schematics it'd be better to connect 3.3V to the AREF pin as there might be some significantly big resistor between AREF and 3.3V source. So it might not be needed but one never knows.


How can I differentiate between multiple circuits? I'm building a puzzle for an escape room. I want to give the user 6 wires and 6 terminals, then confirm that they've connected the correct wires to the correct terminals (one-to-one).

My first (successful) attempt to implement this puzzle was to connect the wires to 6 PWM analog outputs set to different levels, and connect the terminals to 6 analog input pins. By time-averaging the readings on the input pins, I was able to determine which wire(s) are connected to which terminals, if any.

I currently have no resistors in the circuits.

As the puzzle is currently designed, it's possible for the user to do weird things like:

Connect multiple wires to the same terminal.
Connect multiple wires together, without connecting them to any terminal.
Touch multiple exposed wires and/or terminals.

My questions boil down to two:

Is my current approach dangerous, either for the Arduino or my users, and are there recommended precautions I should take?
Is there a better (safer or simpler or more robust) way to implement the puzzle?

I'm a software engineer, but a complete noob when it comes to real electronics and Arduino, so please feel free to assume I know nothing.

First, let's consider the logic of your program. You have two groups of
pins: 6 pins connected to the wires and 6 pins connected to
the terminals. The first thing I would do is forget that these are two
different groups. Consider you just have 12 pins that the user has
to connect in a specific fashion. This way most “weird things” the user
could do, like connecting wires together, are not a special case
anymore. They are just another invalid combination. Now what you have to
do is, for every pair of pins among those 12, determine whether or
not they are connected together. If any pair is connected that shouldn't
be, you have an invalid combination. If any pair is not connected while
it should be, it's again an invalid combination. If every pair is the
expected state (either connected or not connected), then the user did
solve the puzzle.

Now, for the hardware side. A simple way to know whether two pins are
connected together is to set one of them to INPUT_PULLUP and the other
one to OUTPUT LOW. This second pin should be the only one
accessible to the user that outputs a LOW. All other exposed pins
should be set as either INPUT or INPUT_PULLUP. Now, if the first pin
reads LOW, you know have a connection. If it reads HIGH the two pins
are not connected together.

Here is an example program demonstrating that principle. It loops over
the 66 possible pairs to check whether they are connected or not.
You just have to replace the inner if with your code that validates
the combination.

const int PIN_COUNT = 12;
const uint8_t pins[PIN_COUNT] = {...};

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

    // Set all pins to INPUT_PULLUP.
    for (int i = 0; i < PIN_COUNT; i++)
        pinMode(pins[i], INPUT_PULLUP);
}

void loop() {
    // Loop over all pin pairs (pins[i], pins[j]).
    // Set pins[i] to OUTPUT LOW, then read pins[j].
    for (int i = 0; i < PIN_COUNT - 1; i++) {
        pinMode(pins[i], OUTPUT);
        digitalWrite(pins[i], LOW);
        for (int j = i+1; j < PIN_COUNT; j++) {
            if (digitalRead(pins[j]) == LOW) {
                Serial.print("pins ");
                Serial.print(pins[i]);
                Serial.print(" and ");
                Serial.print(pins[j]);
                Serial.println(" are connected together.");
            }
        }
        pinMode(pins[i], INPUT_PULLUP);
    }
}

As for the safety, you should be fine as long as the users do not have
access to any low-impedance ground or voltage source. In particular, the
GND and 5V pins should not be user-accessible. For extra protection, you
could put a 1 kΩ resistor in series with each pin, but then all the
pins that are not actively being tested should be set to INPUT rather
than INPUT_PULLUP, otherwise multiple pullups in parallel may start to
compete with the series resistor.


Why is this spitting giberish instead of serial numbers? #include <TrueRandom.h>

void setup() {
  char* ss= (char*)TrueRandom.random(111111111,999999999);
  char* finalss;
  Serial.begin(9600);
  finalss[0] = ss[0];
  finalss[1] = ss[1];
  finalss[2] = ss[2];
  finalss[3] = '-';
  finalss[4] = ss[3];
  finalss[5] = ss[4];
  finalss[6] = '-';
  finalss[7] = ss[5];
  finalss[8] = ss[6];
  finalss[9] = ss[7];
  finalss[10] = ss[8];
  Serial.println (finalss);
}

void loop() {
  ; // Do nothing
}

This is supposed to output a randomly generated number in this format nnn-nn-nnnn.
Updated Code (Doesn't seem to output anything):

#include <TrueRandom.h>

void setup() {
  String ss;
  ss = (String)TrueRandom.random(111111111,999999999);
  String finalss;
  Serial.begin(9600);
  finalss[0] = ss[0];
  finalss[1] = ss[1];
  finalss[2] = ss[2];
  finalss[3] = '-';
  finalss[4] = ss[3];
  finalss[5] = ss[4];
  finalss[6] = '-';
  finalss[7] = ss[5];
  finalss[8] = ss[6];
  finalss[9] = ss[7];
  finalss[10] = ss[8];
  Serial.println (finalss);
}

void loop() {
  ; // Do nothing
}

Casting a number to a char* doesn't convert the number to a string. Instead it converts the number to a pointer and starts reading chars from that location.

Either pass the number to a String constructor, or pass it through ltoa().

EDIT:

String ss(...);

or

char ss[11];
ltoa(..., ss, 10);

Also, don't forget to allocate memory for finalss and NUL-terminate it.

char finalss[12];
 ...
finalss[11] = 0;


Different ways (and the fastest) to compute sines (and cosines) in Arduino I am using an Arduino Uno board to compute the angles of my system (robotic arm). The angles are actually 10 bit values (0 to 1023) from the ADC, using the full range of the ADC. I am only going to be operating in the 1st quadrant (0 to 90 deg), where both sines and cosines are positive, so there is no problem with negative numbers. My doubts can be expressed in 3 questions:

What are the different ways to compute these trigonometric functions on Arduino?
What is the fastest way to do the same?
There are the sin() and cos() functions in the Arduino IDE, but how does the Arduino actually calculate them (as in do they use look-up tables, or approximations etc.)? They seem like an obvious solution, but I would like to know their actual implementation before I try them out.

PS: I am open to both standard coding on the Arduino IDE and assembly coding, as well as any other options not mentioned. Also I have no problems with errors and approximations, which are inevitable for a digital system; however if possible it would be good to mention the extent of possible errors

The two basic methods are mathematical calculation (with polynomials) and lookup tables.

The Arduino's math library (libm, part of avr-libc) uses the former. It is optimised for the AVR in that it is written with 100% assembly language, and as such is almost impossible to follow what it's doing (there's zero comments as well). Rest assured though it will be the most optimised pure-float implementation brains far superior to ours could come up with.

However the key there is float. Anything on the Arduino involving floating point is going to be heavyweight by comparison to pure integer, and since you are only requesting integers between 0 and 90 degrees a simple lookup table is by far the simplest and most efficient method.

A table of 91 values will give you everything from 0 to 90 inclusive. However if you make that a table of floating point values between 0.0 and 1.0 you still then have the inefficiency of working with floats (granted not as inefficient as calculating sin with floats), so storing a fixed point value instead would be far more efficient.

That may be as simple as storing the value multiplied by 1000, so you have between 0 and 1000 instead of between 0.0 and 1.0 (for instance sin(30) would be stored as 500 instead of 0.5). More efficient would be to store the values as, for instance, a Q16 value where each value (bit) represents 1/65536th of 1.0. These Q16 values (and the related Q15, Q1.15, etc) are more efficient to work with since you have powers-of-two which computers love to work with instead of powers-of-ten which they hate working with.

Don't forget as well that the sin() function expects radians, so you first have to convert your integer degrees into a floating point radians value, making the use of sin() even more inefficient compared to a lookup table that can work directly with the integer degrees value.

A combination of the two scenarios, though, is possible. Linear interpolation will allow you to get an approximation of a floating point angle between two integers. It's as simple as working out how far between two points in the lookup table you are and creating a weighted average based on that distance of the two values. For instance if you are at 23.6 degrees you take (sintable[23] * (1-0.6)) + (sintable[24] * 0.6). Basically your sine wave becomes a series of discrete points joined together by straight lines.  You trade accuracy for speed.


Programming standalone Atmega328p-PU with NE555N timer IC I know I may sound a little idiotic to ask, but as I have seen in the internet that to program a standalone Atmel chip like that from of the Arduino's, you need 2 22pF ceramic capacitors and a 16mhz oscillator. As the oscillator is needed is clock the frequency of the chip, so a timer IC should work just fine, isn't it? or do I have wrong information?

The default configuration of these chips, as they come from the factory,
is to use their internal 8 MHz RC oscillator downscaled at 1 MHz. So you
do not need any extra oscillator to program them.

Once you program the chip the first time, if you configure it to use
an external resonator/oscillator, then you do need to have that
attached in order to reprogram the chip.

A 555 may be able to run the chip, but if you want to reprogram it, the
programmer may not cope well with the extra-low frequency the chip would
be running at.


Do I need an Arduino for BLE? I have built a prototype that uses RedBear Lab's Blend micro board (http://redbearlab.com/blendmicro/). The board combines Arduino and a BLE chip (Nordic nRF8001). The application is fairly simple

iPhone finds and connects to BLE chip
When user presses a button on iPhone a message is sent to the Blend Micro board
Based on the message (3 choices) the Arduino reads analog input from one of the pins
The reading is passed back to the phone via BLE

Everything works well. My question is

If I were to evolve this into something that can be taken closer to production, do I need the arduino? Seems like the Arduino is only adding a small amount of value in interpreting the message from phone and transmitting the reading
If I don't need Arduino, how do I program the BLE chip (Nordic nRF8001) directly? I have seen some kits on the internet and they all seem much more complex than programming Arduino.

I am a newbie to H/W - deep background in S/W engineering - but definitely motivated and interesting in making my project a reality. Advice and guidance are appreicated.

The nRF8001 can not run custom code, so you need an external microcontroller to use it. However, the nrf5 series (for example nrf51822) has a microcontroller and can run custom code.

Nrf5 is Arduino compatible thanks to sandeepmistry's nrf5 arduino core.

You will need a programmer though, since the nrf51822 uses swd programming. References to recommended programmers are available here.


How to convert byte array into a single variable In this code i am taking the TID data(20bytes of 160bits) in the form of array according documentation and and its working correctly and getting the output of RFID tags.

Now I just need your guidance that how can i convert the array of 20 Bytes into a single variable or into a double long datatype? or another. Because I have to push it on to my MySQL database server for further processing.

I had tried the following code which works fine

byte x[10] = "450210921";
long result = atol(x);
Serial.print("long value of the byte is: ");
Serial.println(result);

but when i put the above code into my main code, getting not any error and I am not getting the required output.!

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

void loop()
{
  byte response;
  byte myTID[20]; //TIDs are 20 bytes
  byte tidLength = sizeof(myTID);

  //Read unique ID of tag
  response = nano.readTID(myTID, tidLength);
  if (response == RESPONSE_SUCCESS)
  {
    for(byte x = 0 ; x < tidLength ; x++)
    {
      if(myTID[x] < 0x10) Serial.print("0");
      /*temp[x]=(myTID[x], HEX);*/
      //Swapping values into temp variable
      temp[x]=myTID[x];
      Serial.print(temp[x]);
    }
    /*byte x[10] = "450210921";*/
    //Convert a whole array into a single long variable
    long result = atol(temp);
    Serial.print("long value of the byte is: ");
    Serial.println(result);
  }
  else
    Serial.println("Failed read");
}

You can't convert 20 bytes to long. Send it as string of hex values. A byte takes two characters in hex, so you will send a 40 characters string, which can be simply decoded back to bytes.

char str[sizeof(myTID) * 2 + 1];
const char* hex = "0123456789ABCDEF";
for (int i = 0; i < sizeof(myTID); i++) {
  str[i * 2] = hex[(myTID[i] >> 4)];
  str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
}
str[sizeof(str)] = 0;
Serial.println(str);


How do I power an arduino without USB? I'm working on a project where my arduino talks to another device that uses serial communication. I've connected my USB cable to a USB-to-serial adapter, so it can communicate with the device.

The problem I'm running into is powering the device: if I'm using the USB for serial, I can't use it for power. I have made sure that the device isn't turning on by putting

pinMode(13, OUTPUT);
for (int i = 0; i < 10; i ++) {
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
}

at the start of the setup function: if it works, it should start by blinking LED 13.

I tried powering it with a 5V power supply through the power jack, next to the USB connector, but that didn't work. Is there something I'm missing? Do I need a different type of power supply?

my arduino talks to another device that uses serial communication

What other device? You haven't said which Arduino, but Arduinos are generally "devices" which talk to a "controller" (host) which is generally a PC / Mac.

The host has the job of supplying power (via the USB cable) to the device. Thus your Arduino will be powered by the device it is plugged into.

Disregarding this issue for the moment, you can supply regulated 5V power directly to the 5V pin on the Arduino. On the Uno (and many others) this is labelled "5V".

The power jack is to supply 7V to 12V (eg. from a wall-wart) which then goes through the voltage regulator on the Arduino (depending on the model in question).

There is quite a discussion about this on https://www.arduino.cc/en/main/arduinoBoardUno. On that it mentions:

  Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This is true. Directly supplying 5V to the 5V pin bypasses the regulator and also bypasses the reverse-voltage protection diode. However it is possible to do it.

  What about the Vin pin?

For a Uno you can see from the reference schematic what happens:

The power jack (on the left) goes into the reverse-voltage protection diode (D1). The other side of that becomes Vin. Then it goes into the 5V voltage regulator (U1). The other side of that becomes the 5V line.

Thus to supply 5V you can provide 5V power to the pin marked 5V. It is probably not ideal, because the voltage regulator may not be designed to have power applied on its "output" side.

There is more circuitry to decide whether to use the USB power or the Vin power (not shown above).