Sending serial data in an interrupt An ATMEGA328-P chip is used with a toggle switch attached to pin 8 and a momentary switch attached to pin 9. My objective is to send the following information over serial:

The status of pin 8, every second.
Count the number of presses of pin 9, sending the value as the counter increments

I understand that to achieve point 2 I will need to utilise interrupts, but I have become stuck in the way I am trying to use them.

I am familiar with the following code's simple style:

Within the loop...
Poll the status of the input
Send status over serial

Code A:

const int SWITCH_1 = 8;
const int READ_INTERVAL = 1000;

int val_s1 = 0;

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

    pinMode(SWITCH_1, INPUT);
    digitalWrite(S1, HIGH);
}

void loop() {
    val_s1 = digitalRead(SWITCH_1);
    Serial.print("S1:");
    Serial.print(val_s1);
    Serial.print("\n");

    digitalWrite(LED_BUILTIN, HIGH);
    delay(10);
    digitalWrite(LED_BUILTIN, LOW);
    delay(READ_INTERVAL);
}

When introducing the concept of interrupts, I have tried to retain the simplistic style of code A for testing purposes. The next snipped attempts to achieve the following:

Attach an interrupt to pin 9 when the voltage rises
No need for loop function (?)
Within interrupt callback function...
Increment the counter
Send the counter value over serial

Code B:

void c1_rise();

const int COUNTER_1 = 9;
const int READ_INTERVAL = 1000;

volatile int val_c1 = 0;

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

    pinMode(COUNTER_1, INPUT_PULLUP);
    attachInterrupt(COUNTER_1, c1_rise, RISING);
}

void loop() {
}

void c1_rise() {
    val_c1 ++;
    Serial.print("C1:");
    Serial.print(val_c1);
    Serial.print("\n");
}

I've tried to learn where I'm going wrong, but I have become stuck and have decided to ask my questions here.

Observation: I expect to see some data sent over serial when the button is pressed, but actually nothing observable happens.
Problem 1: This might be because the interrupt isn't being attached at all.
Problem 2: This might be because I misunderstand the limitations of interrupt callback functions.

While trying to solve problem 1, Arduino documentation implies that to use the attachInterrupt function, parameter 1 must be an interrupt, from digitalPinToInterrupt, but if I use that function I receive the following error message: error: ‘digitalPinToInterrupt’ was not declared in this scope.

From reading up about how interrupts behave, I found problem 2: it seems that even though I have declared the integer as volatile, using Serial from within a callback function isn't allowed. This is the limit of my knowledge currently, I hope that someone can help me out.

You cannot use Serial inside an interrupt. Transmitting Serial relies on interrupts being available, and from inside an interrupt they aren't.

All Serial communication must be done from loop().

So you need to just count the switch toggles and check to see if that value has changed in your loop.

volatile uint32_t toggles = 0;
uint32_t old_toggles = 0;
uint32_t ts = 0;

void setup() {
    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    attachInterrupt(0, toggle, RISING);
}

void loop() {
    if (toggles != old_toggles) {
        old_toggles = toggles;
        Serial.print("C1: ");
        Serial.println(toggles);
    }

    if (millis() - ts >= 1000) {
        ts = millis();
        Serial.print("S1: ");
        Serial.println(digitalRead(3));
    }
}

void toggle() {
    toggles++;
}


Shortening large chunks of code Some of the code that I have is unbearably long and drives me insane. I don't know if there were simpler ways to doing what I am doing.

long turn1;
long turn2;
long turn3;
long turn4;
long turn5;
long turn6;
long turn7;
long turn8;
long turn9;
long turn10;
long turn11;
long turn12;
long turn13;
long turn14;
long turn15;

#################

  turn1 = random(sizeof(turns) / sizeof(char*));
  turn2 = random(sizeof(turns) / sizeof(char*));
  turn3 = random(sizeof(turns) / sizeof(char*));
  turn4 = random(sizeof(turns) / sizeof(char*));
  turn5 = random(sizeof(turns) / sizeof(char*));
  turn6 = random(sizeof(turns) / sizeof(char*));
  turn7 = random(sizeof(turns) / sizeof(char*));
  turn8 = random(sizeof(turns) / sizeof(char*));
  turn9 = random(sizeof(turns) / sizeof(char*));
  turn10 = random(sizeof(turns) / sizeof(char*));
  turn11 = random(sizeof(turns) / sizeof(char*));
  turn12 = random(sizeof(turns) / sizeof(char*));
  turn13 = random(sizeof(turns) / sizeof(char*));
  turn14 = random(sizeof(turns) / sizeof(char*));
  turn15 = random(sizeof(turns) / sizeof(char*));

#

if (turn1 == turn2 or turn2 == turn3 or turn3 == turn4 or turn4 == turn5 or turn6 == turn7 or turn7 == turn8 or turn8 == turn9 or turn9 == turn10 or turn10 == turn11 or turn11 == turn12 or turn12 == turn13 or turn13 == turn14 or turn14 == turn15) {

#

lcd.print(turns[turn1]);
lcd.print(turns[turn2]);
lcd.print(turns[turn3]);
lcd.print(turns[turn4]);
lcd.print(turns[turn5]);
lcd.setCursor(0, 2);
lcd.print(turns[turn6]);
lcd.print(turns[turn7]);
lcd.print(turns[turn8]);
lcd.print(turns[turn9]);
lcd.print(turns[turn10]);
lcd.setCursor(0, 3);
lcd.print(turns[turn11]);
lcd.print(turns[turn12]);
lcd.print(turns[turn13]);
lcd.print(turns[turn14]);
lcd.print(turns[turn15]);

Yes you can, and the solution is very simple. It's in two parts, and they make up part of the absolute fundamental building blocks not just in C, but in almost any programming language.

You can read good information on arrays here, and 'for loops' here (it's about half way down the page). Without wishing to offend, it seems like you are missing some really basic concepts and I recommend starting at the beginning of the tutorial series that the two aforementioned links are part of.

I'll just cover the basics. If you don't understand anything, refer to the tutorials. If you still don't understand then please comment, but make sure you can convince us that you've really given it a good go. We're here to help as long as you're here to learn.

To declare an array of N variables, all of which are the same type, you use:

<type> <name_of_variable> [<number_of_elements>];

or:

long turns[15];

Now you have an array of 15 longs. Ta da!

You now have to set the values of each turn. As your values are all the same (if you ignore the fact that random() ultimately leaves you with different values) you can use a for loop:

for (int x=0; x<15; x++)
{
    turns[x] = random(sizeof(turns) / sizeof(char*));
}

I won't explain how a for loop works; I gave you a link to the tutorial to save me writing it all out myself.

That covers shrinking of part 1 and 2. Part 3 requires a little more thought. That said, as you didn't complete your if statement, I don't actually know what you plan to do if any two adjacent turn elements are the same. I shall assume that you would 're-randomise' one of the duplicates. For this you can again use a for loop, starting at the beginning and running to N-1 th element, where N is the total number of elements:

for (int x=0; x<14; x++)
{
    if (turns[x] == turns[x+1])
    {
        turns[x+1] = random(sizeof(turns) / sizeof(char*));
    }
}

You need make sure that turns[x+1] is not outside of the array, which is why the for loop runs for one iteration less than there are elements.

The fourth shrinkable part is just a matter of swtiching multiple print statements into single for loops:

for (int x=0; x<NUMBER_OF_PRINTS_IN_1st_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,2);
for (int x=WHERE_YOU_LEFT_OFF; x<NUMBER_OF_PRINTS_IN_2nd_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,3);
for (int x=WHERE_YOU_LEFT_OFF_AGAIN; x<NUMBER_OF_REMAINING_PRINTS; x++)
    lcd.print(turns[x]);

All done.


Buttons, LOW vs no connection I'm working with a very simple circuit to understand push buttons. The code in the tutorial uses the INPUT_PULLUP pinmode. I understand the idea of the pinmode, but I have two questions:

There must be a difference between a LOW reading and no connection, correct? How does the arduino differentiate between the two?

I tried to experiment with this idea. So my thought was that you could create a circuit where the LED only stays lit when you hold the button down. In this setup, I used just normal INPUT for pinmode. So the logic was: if LOW then turn light on, else light off. The turnout was the light was almost always on and just really finicky when i moved the board. Why?

Thanks!

There must be a difference between a LOW reading and no connection, correct?

No, the input circuitry measures a voltage. The exact details are in the datasheet, but how could it know there is nothing connected? There is not some sort of sensor that detects the insertion of a wire into the input. Therefore it is trying to read a voltage all the time.

With nothing connected then stray voltages from nearby circuitry will influence the reading.

  ... and just really finicky when i moved the board ...

Yep, you are influencing the voltage by capacitance from your hand.

You need to have a definite voltage for "no switch pressed" which can be a resistor to ground (eg. 10k) or a resistor to +5V.

I have a tutorial on this.

It sounds like you have wired your switch like this:

Because you don't have a definite voltage there, the input could "randomly" switch between LOW and HIGH.

You could add a pull-down resistor:

Or a pull-up resistor:

Or use the INPUT_PULLUP mode to create a pull-up resistor in the processor hardware. (There is no INPUT_PULLDOWN mode).

Then you will get consistent results.


Why do I keep blowing up Nanos when I solder them? I have blown up 2 Arduino Nanos and I'm trying to figure out what I'm doing wrong.

In both cases, I was powering the boards with a 16V supply (I know this is high, but the regulator datasheet says it is good to 25V, and the regulator was not damaged). I unplug the supply and USB cable and then start soldering to one of the pins (A6). When I plug the board back in, the L LED does not flash, indicating the bootloader has been erased. The POW light is on and I still measure 5V, indicating the regulator is working. When I connect the board to my PC, the serial port pops up just fine. But when I try to upload a sketch, the IDE times out and says it cannot communicate with the board.

I attempted to reprogram the bootloader using a raspberry pi but avrdude also says it cannot find the device either. It looks like the microcontroller is blown.

My iron tip is grounded, so my best guess is some residual power in the supply travels through the microcontroller to my iron and shorts something out. But this seems unlikely seeing as A6 is an input and grounding it should be just fine even when the supply is fully on.

Any ideas what I could be doing wrong? FYI, I am cross-posting this on the Arduino forums.

My advice would be not to solder directly to the Nano pins.  Instead, use the appropriately sized DIL socket, and solder to the pins of that instead.   Then plug in the Nano once the soldering is complete.


Please Correct my Delay Code without using delay(); This is my loop()function:

if(Serial.read() == 't') {
  tarestate = true;
}

while(tarestate == true) {
  timeNowTare = mills();
  if(mills() - timeNowTare >= 3000) {
    Serial.println("Tare");
  }
  tareState = false;
}

Where tareStare is a boolean, timeNowTare is a long.

I need to print on serial:

  Tare

three seconds after I enter "t" into serial.

With everything I have tried to date, the program either stops or tares immediately after entering “t”.

EDIT: Thanks to everyone who responded with answers.
The solution was simply to move the timeNowTare = true; declaration up to the Serial.read() if statement. I also changed the while loop to an if statement because it seemed to make my code run quicker.

The easiest solution is to just use delay():

if (Serial.read() == 't') {
    delay(3000);
    Serial.println(F("Tare"));
}

What? You said “no delay()”? OK, then just write your own
implementation of delay() and inline it in place of the actual call to
delay():

if (Serial.read() == 't') {
    uint32_t timeNowTare = millis();
    while (millis() - timeNowTare < 3000) continue;  // wait
    Serial.println(F("Tare"));
}

This seems to be more or less what you attempted. You write a while
loop that blocks the program for three seconds. It is also what leoc7's
answer does.

However, doing so is completely foolish. Why would you write your own
version of delay() when the Arduino core provides you with a well
tested one? Why would you want to avoid the standard delay() in the
first place?

It turns out there is a very good reason to avoid delay(). The reason
is that delay() blocks your program for the entire delay duration.
If your code needs to be responsive to some external inputs (as any non
trivial program at some point needs), this means within that time window
the program will be completely unresponsive. The bad thing about
delay() is not the implementation (there is no point in replacing it
with your own), it's the fact that it blocks your program. If you
replace delay() by your own blocking code you have won nothing.

The real solution is to think in terms of a finite state machine. Either
the program is running in “tare mode” or not. The possible state
transitions are:

upon reading a 't' on the serial port, you enter tare mode and take
note of the current time
if you are already in tare mode and three seconds have elapsed since
you entered that mode, then you print out "Tare" and exit tare mode.

Here is a straight forward implementation of such state machine:

static bool tare_mode = false;
static uint32_t tare_start_time;  // meaningful only in tare_mode
if (Serial.read() == 't') {
    tare_mode = true;
    tare_start_time = millis();
}
if (tare_mode && millis() - tare_start_time >= 3000) {
    Serial.println(F("Tare"));
    tare_mode = false;
}

Now you can add more code to loop() and this extra code will never be
blocked by your “tare” feature.


send sketch to arduino via wifi I'm pretty new to arduino and need some help.

My task is to connect my UNO R3 to wifi AND then send data (sketch for blinking led) to it.
I successfully connected my arduino with my wifi, but how do I send the sketch?

I didn't find a tutorial for this. Do you know a good one or can you help me, please?

There is a difference between communicating via WIFI while a sketch is running or to send the sketch itself ... for the latter, I don't think there is an easy solution; you probably have to write your own AVR programmer, receiving the sketch via WIFI and store it on the Flash memory.


I have five pushbuttons that refer to a specific pin number. I need an efficient code to set the variable for the pin with state 1. What can I use? There are 5 push buttons each which correspond to a certain pin let us use 1 to 5 for an example. I want to set a variable, ActiveButton which will be set equal to the the only pin in the one state.
We make use of the concept that there can only be one active push button which means the pin of that would have a state of 1 and the rest would be 0. The long method for this would be to use if else and digitalRead(pin) == 1 for everything but that would be so long on code. I've considered using do while or while loops to stop until it reaches the push button with a state of 1, but I was wondering if there was a more efficient code. I was also thinking if there was something that made use of an array?
Though the idea of like having a simple array return the index which results to a corresponding value, like lets say Array[3] ==1 among all the indices from 0 to 4 feels easy to conceptualize, I believe this can be really taxing on the code and might not be able to be done in a short way.
I've also thought of possibly using switch case, where the variable would be the high state and the case values would be the digitalRead for each pin? But that would be wrong probably because I'm not sure but you can't set the switch variable to be a constant. It would be something like
switch (1)
case digitalRead(1):
case digitalRead(2):

There are 5 push buttons each which correspond to a certain pin let us use 1 to 5 for an example. I want to set a variable, ActiveButton which will be set equal to the the only pin in the one state.

Here is a short snippet of what I think, that you want. This is quite a long shot, since your question is not clear enough.
int ActiveButton = -1; // Initialize ActiveButton with -1 (no button is active)
int button_pins[] = {1, 2, 3, 4, 5}; //Array with pin numbers of the buttons

void loop(){
    for(int i=0;i < sizeof(button_pins)/sizeof(button_pins[0]); i++){
        if(digitalRead(button_pins[i])){ //if the i-th button was pressed
            ActiveButton = button_pins[i]; // assign i-th button pin number to variable
            break; // Break, since we have found our pressed button, ignore all following pins
        }
    }
}

This will assign the pin number of the pressed button to the variable. The condition in the for loop
sizeof(button_pins)/sizeof(button_pins[0])

will make the code loop over all elements of the button_pins array. sizeof(button_pins) returns the number of bytes in the button_pins array. Then we divide through the number of bytes in the first element to get the number of elements in the array.


Two data outputs to be displayed on one 16x1 lcd display Before pursuing this very far, I would like to know if I can get two different data outputs (one on the left 8 and the other data on the right 8).  And if so, are there any requirements on the display or any other thing that might be needed.  I'm thinking that as far as the proper Arduino platform being the Mega 2560.  My idea is to put together an FSX navigation radio for my flight simulator.

You can use

lcd.setCursor(x, y);

To set the cursor.

Than you can output text with

lcd.print("Text");

Make sure you add spaces in case there is already text written to overwrite older text.

You can also use

lcd.clear();

to clear the display, but this might result in flickering if you do it too often.

Another possibility is to create a 16 character string

char lcdText[16];

and write characters in this string and set it at once with:

lcd.setCursor(0, 0);
lcd.print(lcdText);


Detecting different objects closeness iam currently working on a new project, where i would like to detect the existence/closeness of several objects around the arduino up to like 1 meter. I was thinking about an rfid setup, but as the objects could have different sizes like 5 centimetre tall and only 3 centimetre wide, i think this won't work for the max distance. I was also thinking about a ble beacon, but as this one has to be activley powered all the time, it wouln't be the perfect solution. As the base could be fully customized, it may have some kind of sensors/wires overall the surface, but iam a bit lacking of a good idea for this.
I hope someone might had a similar setup, or a good idea to go.
PS: When i think about it twice, it would be better, if it can be differentiate between some areas within the one meter and the different objects, entering each area. I've added some image, hope this helps to understand, what i want to archive at the end.

Thank you and greetings,
Sebastian

As you might have already seen, a position sensing system can be really complex. Here I will list some possibilities, that come to my mind and might be fitting for your case or not.

Matrix based solutions: Here I mean sensors a some sort arranged in a matrix underneath the game table, which can sense the object placed on them. As you know from your wiring, where a specific sensor is located, you know from the triggered sensor, where the object was placed. The resolution directly corresponds to the numbers of sensors, that you place. You can use different sensors, which will give you different information, but are also very different in handling and costs:

Reed switches and magnets on the bottom of the objects. The magnet on the object would close the reed switch. A read switches are rather cheap (have seen 40 pieces for about 10€ on amazon; on aliexpress or others you might get them even cheaper) and can be easily placed in an electrical matrix or (depending on the number and places of object at any time) checked via shift registers, which are also not very pricey.

Hall sensors and magnets on the bottom of the objects. You would measure the magnetic field of the magnets with the hall sensors. You could use different magnet strengths to get different readings and thus directly distinguish between different object types. The hall sensors will be not that easy to read. Mostly they have an analog output, thus you would need extra ADCs and multiplexers to read them all.

RFID readers and RFID chips in each object. Very pricey and rather low resolution. Also very difficult to read from all of them with the Arduino. But you could go for the reed switch version and use a single RFID reader to first tell the Arduino, which object you are placing. In the game you would first hold the object to the reader, then place it on the board.

Lidar system: A Lidar scanner could scan over your board (it measures the distance in a circle around it). Each object would be a negative peak in the measured distance distribution. From the angle and the distance, you could calculate the position on the board. Though you would need to carefully place the sensor, as one object might hide the other behind it. You can tackle that with an additional Lidar scanner, but the processing will also be rather complex. And Lidar scanners are rather expensive.

Ultrasonic sensors out the board: If you place enough ultrasonic sensors around the board and measure with one after the other, you might also get fitting results. But I would guess, that you won't get good positioning results with them, especially for the rather small objects and distances used on a game table.

Computer Vision: Away from Arduino you could use OpenCV on a Raspberry Pi together with a small camera above your board to detect objects. General object detecting is rather easy with OpenCV and python; getting it's position in the camera image is trivial then (from where you can calculate the position on the board easily). With more work it should also be possible to detect the object themselves (meaning distinguishing between different objects). We might need to train OpenCV with top-down images of the objects for that. If you don't get good results with the normal camera mode, you could try the IR camera mode (by removing the IR filter of the Pi's camera) and put some good IR reflective stuff on the top of the objects. Then OpenCV only has to find the bright spots in the image. All that is possible, though I cannot help you with that and also it is off-topic on this site.

If you can have a board with fixed positions, you could make direct electrical connections between the objects and the board. Though that means, that you would have metal contacts all over the board. I recently used such electrical connections to distinguish between different objects, which can be put into a small number of bays. I have 7 pins on each object, one of them ground. On the object I connected some of the other pins to the ground pin to create a binary pattern. The pins of each bay get read by a shift-in register. All registers are chained together and connected to the Arduino with a total of 4 pins.

Depending on your needs you could combine some of these options. I would try the OpenCV solution, or alternatively the reed switch with one RFID reader solution.


How much power can a proto board handle? I have been working on a project where I will be powering an Arduino and some LED light strips (2 x 3 Meter strips w/ 30 LEDs per meter). I am powering all of it from a 5v 10amp power supply.

Currently I have split the power cable and have it running to the board and the LED's in separate runs.

As I move from a breadboard to a more permanent proto-board, it would be great to add a barrel connector onto the proto-board and just have a single plugin for power so I can easily disconnect it.

Will this cause any issues if all of the power comes from the proto-board? Thanks!

No, it's not practical do to that with protoboard of any form.

There are two reasons for this:

Barrel jacks are not rated for 10A - I think the most powerful I have seen is 3A.
To handle 10A over (for example) 6 inches of track you would require tracks roughly 8mm wide at 1oz copper. No protoboard provides such tracks.

Even if you're only using half the capacity of your power supply (5A) you still exceed a barrel jack, and would need traces about 3mm wide.


Reading values from the register of a slave I am trying to interface MPU6050 with arduino. Found a simple code online, but having a bit of trouble in interpreting it.

// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
}
void loop(){
Wire.beginTransmission(MPU);
Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print("AcX = "); Serial.print(AcX);
Serial.print(" | AcY = "); Serial.print(AcY);
Serial.print(" | AcZ = "); Serial.print(AcZ);
Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for   temperature in degrees C from datasheet
Serial.print(" | GyX = "); Serial.print(GyX);
Serial.print(" | GyY = "); Serial.print(GyY);
Serial.print(" | GyZ = "); Serial.println(GyZ);
delay(3330);
}

Now there are a few things i want to ask regarding this code:
1. Here we have specified that the data from 3B register of the slave should be the first one and master will receive in total 14 bytes. In this case the 14 registers are continuous (see datasheet here) .Now how should i go about reading the values if i am interested in registers which are not continuous ,let us say alternative?

2.AcX=Wire.read()<<8|Wire.read();

This line is taking the first 8 bits and last 8 bits and forming a 16 bit number . But why do we need to shift the first 8-bits byte 8 places to left.Please explain how exactly this line works?

For reading non-consecutive bytes, the “normal” way would be to do a
one-byte request and a one-byte read for each byte you want. However, if
the bytes you want are close enough (e.g. you want every other byte), it
would be faster to do a contiguous read and just ignore the bytes you do
not want. E.g.:

byte data1 = Wire.read();  // read first byte
Wire.read();               // read and ignore second byte
byte data3 = Wire.read();  // read third byte

For your question regarding the meaning of
Wire.read()<<8|Wire.read();:

Wire.read() return a 16-bit integer, where the 8 most significant
bits are zero and the 8 least-significant bits contain the actual
data. In binary, it's something like 00000000xxxxxxxx, where x
are the data bits.
<<8 means “shift left by eight positions”, where the missing bits
are replaced by zeros. Thus Wire.read()<<8 is xxxxxxxx00000000
in binary.
The second call to Wire.read() return another 16-bit integer in the
form 00000000yyyyyyyy.
The vertical bar | is the bitwise-or operator: each bit of the left
operand is or-ed with the corresponding bit of the right operand to
give one bit of the result: x or 0 is x, 0 or y is y.
Then, the whole expression gives xxxxxxxxyyyyyyyy, where xxxxxxxx
comes from the first Wire.read() and yyyyyyyy from the second.

The problem here is that the “first” and “second” Wire.read() in the
sentence above refer to the position of the call in the line, not to the
actual order in which the calls are performed. Thus you may be lucky and
get the the correct byte order... or not. You should instead do a single
read per statement if you want to control the byte order. For MSB first:

AcX = Wire.read() << 8;  // read most significant byte first
AcX |= Wire.read();      // then least significant byte

And for LSB first:

AcX = Wire.read();        // read least significant byte first
AcX |= Wire.read() << 8;  // then most significant byte


Need advice on serial bytes reading optimization I am doing some device serial data read and publishing values to MQTT. Using ESP8266 for this.

Currenty I request serial device by sending a command and parse all byte values individually, how to do this in better way ?

each byte parse is done in such way:

float Heat = (float)data[38];

  sprintf(mqtt_topic, "%s/%s", mqtt_topic_base, "Temp"); mqtt_client.publish(mqtt_topic, String(Temp).c_str());

float Power = (float)data[39];
......
..... and etc...

In principle it is ok to use your way, but a simple improvement is to change the magic numbers (38, 39) to constants or define:

const int offset_heat = 38;

…

float Heat = (float)data[offset_heat];

or a define:

#define OFFSET_HEAT 38

…

float Heat = (float)data[OFFSET_HEAT];

If all values are consecutive you can keep a variable to read the values:

int offset = 38; // Normally starts at 0 assuming you read values from the start

float heat = (float) readByte(&offset);

…

int readByte(uint8_t* offset)
{
    int value = data[*offset];
    (*offset)++;
    return value;
}

This increases the offset after reading the value.

Some remarks:

It's a convention not to use capitals for local variables (so change Heat to heat)
You don't use the Heat variable in sprintf, maybe this is intentional.


Arduino selection for RTOS I am brand new to Arduino and am having a difficult time understanding the "lay of the land". I'm looking for the beefiest, fastest, most compute-centric Arduino available to the market that will run embox.

As I understand it, there is really only the Uno and the Mega, both of which are 32-bit. However I also believe that 64-bit variations/designs exist and was wondering if anyone has actually implemented Arduino Uno/Mega as a 64-bit MCU. I also see there is the Arduino Due, but not sure how that fairs (beefiness-wise) with Uno/Mega.

So to summarize: What is the beefiest Arduino one can find, is it 32- or 64-bit, and will it run an embedded RTOS like embox?

While I'm not experienced with running an RTOS on it, I'd highly recommend Teensy 3.1 as the "beefiest, fastest, most compute-centric Arduino". FreeRTOS and ChibiOS both support Teensy.


Problems With Fading Through Neopixel Colors I have a 20x20 matrix of neopixel LED's. I have a certain set of LED's on in different places at different times. Each one is set to mainColor. Right now mainColor is just set to strip.Color(r, g, b) but I would like to have those color fade through the spectrum. I decided the easiest way would just be to do something like this, and simply return strip.Color(r, g, b) to mainColor, then calling it to turn change the colors like so:

strip.setPixelColor(pixelNumber, mainColor(5));

Here is the code for mainColor:
    int r;
    int g;
    int b = 255;
    int _r;
    int _g;
    int _b = 255;

void Color (int FADESPEED)
{
    // fade from blue to violet
    for (_r = 0; _r < 256; _r++) {
        r = _r;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from violet to red
    for (_b = 255; _b > 0; _b--) {
        b = _b;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from red to yellow
    for (_g = 0; _g < 256; _g++) {
        g = _g;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from yellow to green
    for (_r = 255; _r > 0; _r--) {
        r = _r;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from green to teal
    for (_b = 0; _b < 256; _b++) {
        b = _b;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from teal to blue
    for (_g = 255; _g > 0; _g--) {
        g = _g;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
}

This was good but it would only return r, g, b as it was on the last iteration of the last for loop, which obviously isn't what I want. But when I un-comment the Serial.print's the values were perfect. So then I put return strip.Color(r, g, b) into each for loop, however this only returns the first iteration of the first loop, which is also not what I want. Does anyone know how in the world I can return strip.Color(r, g, b) for every iteration of every for loop? Or if not, any alternatives that would work in this situation.

Thanks, Matthew

There appears to be a number of problems with this code.

The variables only have scope with in this function and are not static.  So they will not survive from call to call.  Every time you call this function it will be like starting over.

Putting returns in the middle of code is not good coding practice.  It is very difficult to follow and hard to debug.  It would be best to arrange your code so that there is only 1 return at the end of the function.

This code (from Adafruit) only controls 1 RGB LED.  If you are to control 40 RGB LEDs all at different stages of color changing you would need 40 copies of this function.  This is not very efficient. Instead use this function to populate one lookup table with R G B data.  Then track 40 variables, one for each RGB LED.  Use the 40 variables to lookup a specific color combination in the lookup table for each of the 40 RGB LEDs.


Is it possible to make a mathematical function generator using Arduino? I want to build a function generator but not the ones which outputs square wave or sawtooth ect. I will input a discrete function lets say f(n) = e^n for n=0 to n=100 and the output array will be outputs as voltage samples creating a e^x like signal on a scope?

Is this possible?

You can generate arbitrary waveforms using either the built-in PWM and a low-pass filter or an external DAC.

You won't get more than 16-bits in PWM ( or AFAIK non-audio DAC with arduino libraries ), so your e^N function will be below your resolution for most of the cycle.

Alternatively, generate a saw-tooth and use an op-amp exponential function


Baudrate is set to 9600 automatically even if specifying a different value You initialize the serial communication via USB with

Serial.begin(baudrate);

where baudrate is a long specifying the number of symbols you want to send over the connection per second. You can put pretty much any number in there, but not every number makes sense.

One thing that I found odd though is that I can't seem to actually use a different baudrate than 9600. The sketch compiles and uploads just fine, but if I check the actual speed of the serial port via

setserial -ag port

where port is the port of my Teensy 4.0 board (that command is something you can use in the terminal of Linux) or with

Serial.baud();

directly in the sketch it always says 9600. I suspect that this is caused by something inside the code behind Serial.begin() since I can manually set the baudrate via the terminal in Linux using

stty speed baudrate < port > port

where (again) baudrate is the speed I want to use and port is the port of my board (checking it with the first terminal command: it works). But when restarting the program on the board the baudrate reverts to 9600.

Does anyone know why this is and how to fix this?

The whole concept of Baud Rate with USB communication is completely meaningless.  There is no such thing as "baud rate" over USB.

What there is, and what you are confusing with "baud rate" is a configuration item which the host can send to the device which is a "I would like you to communicate with other devices at this speed" configuration item.

This is intended for use with USB to UART adaptors where it is used to configure the baud rate of a physical UART interface for downstream communication.

When you set the baud rate in your code it is ignored, since it has no meaning.

When you set the baud rate on your computer it sends it as this configuration value, which you can then retrieve, should you have an interest in that value, using the Serial.baud() function.


How to prevent interference between dc motor and arduino? It may be already asked question in somewhere but I am struggling!

I have a four wheel robot which I want to drive it to perform 90-degree left/right turn, I am using the MPU6050 3dof to get angles, however everything is ok when the DC motors are off and the readings from the MPU6050 are pretty good.

But when the DC motors are on, the readings start to be increase randomly. I tried to use a different power supply to the DC motors and the Arduino, but with no solution. At the end when I reset the Arduino everything was back to be normal even if the DC motors are on!

Any help will be appreciated and I am open for any suggestion.

There are two basic things you need to do:

Use proper pullup resistors on your I2C lines (2.2kΩ) instead of relying on the (terrible) internal pullups of the ATMega
Add capacitors to the motors.

For point 2 you need two or three small ceramic capacitors (10nF to 100nF) per motor.

Connect one from each terminal to the motor's body
Optionally connect a third between the two terminals of the motor

This will reduce the EMI produced by the motor, and the improved pullups should reject EMI easier.

(Even if this doesn't entirely fix your underlying issue, it's certainly something that you should do regardless.)


How to convert macros for Arduino code? I have a piece of code I'd like to make Arduino editor friendly. The code is written in C and contains macros the Arduino IDE can't deal with. Is it a good idea to turn those macros into functions?

#define AN221_EXECUTE_Low   cbi(PORTA, PIN0)        //drive EXECUTE low
#define AN221_PORb_High     sbi(PORTA, PIN1)        //drive PORb high
#define AN221_ACTIVATE      bit_is_set(PINA, PIN2)      //sense ACTIVATE high
#define AN221_NO_ERROR      bit_is_set(PINA, PIN3)      //sense ERRb high i.e. no rror
#define AN221_ERRb_Input    outp(0xEB, DDRA)        //make uP drive ERRb
#define AN221_ERRb_Output   outp(0xE3, DDRA)        //make uP sense ERRb

Is it a good idea to turn those macros into functions?

it depends.

macros are fast, but lack type checking.

functions offer type checking but incur overhead.

whether one is better than the other depends on your priorities.


Mini Voice Recorder for Arduino I am trying to find a small voice recorder that I can use with my Arduino Micro, and I found this. It is exactly what I am looking for, but it is now a retired product. I googled ISD1932, but many other sites are out of stock or not selling it anymore. Is there something of this size that does the same things, and why is it retired?

FYI, these ISD chips sample audio and store a variable charge on a single flash like cell. They do not convert a sample to a numerical value. There is no data to be read from the chips nor (AFAIK) is there an opportunity to write data to play back to the chips. AFAIK, for us common people, each ISD chip needs to have its recording entered individually. Think of it like duplicating cassette tapes. Think about this when considering how to go about building your project.


Reading from EEPROM and combining I'm trying to read from the EEPROM and combine the information and send it out over SoftwareSerial using write() function but i'm getting the following error

error: invalid operands of types 'const char [3]' and 'const char*' to binary 'operator+'

void loop()
{
  const char* eTest1 = EEPROM.read(1);
  const char* eTest2 = EEPROM.read(2);
  const char* eTest3 = EEPROM.read(3);

  char combinedVal[] = eTest1+":"+eTest2+":"+eTest3;
  bluetooth.write(combinedVal);
}

You cannot use the + operator for that.

However, since EEPROM.read only returns one byte and not a string, you can do a much easier implementation:

void loop()
{
  char result[] = "1:2:3";
  for (int item = 0; item < 3; item++)
  {
    result[item * 2] = EEPROM.read(1 + item);
  }
}

This first create a string "1:2:3", where the digits are overwritten in the for loop by that item. Note that the digits in the string do not matter, it's just some free 'comment', it also should work when using "x:x:x".


Can I power the arduino UNO through the 5V pin while I use USB cable to collect data? I understand that if the Arduino is powered by Jack or Vin when the USB cable is connected, the internal circuitry would inderdict the USB powering.
But what if I power the arduino througn 5V pin while the USB cable is connected? How does the internal circuit do the choice?
Did I just connect the 5V power supply directly with USB port of the laptop (since the 5V rail directly connects 5V pin and USB port)? Is this allowable? Is this dangerous?
Thank you!

If u use the VIN pin of arduino, You shouldn't have a problem , as arduino selects it required voltage automatically, it's voltage regulator senses the voltage from USB and External source, if the power of the external source is higher than usb, the the power is bypassed to the External power. But don't know if you are using the 5 volt pin to turn on the arduino.
Well everything I said is applicable for UNO boards don't know other ones.
Thanks...


Why my servo motor is always on? Why my servo motor is always on?

#include <Servo.h>

Servo myservo;

int pos = 0;

void setup() {

pinMode(2, INPUT);
myservo.attach(9);

}

void loop() {

  if (digitalRead(2) == LOW) {

    for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(15);
    }

    for (pos = 180; pos >= 0; pos -= 1) {
      myservo.write(pos);
      delay(15);
    }
  }
  else {
    myservo.write(0);
    delay(15);
  }
}

It looks like you need to enable the pull-up resistor on D2.  As written D2 is left floating and most likely is a low voltage relative to ground.  Enabling the pull up resistor will force the pin high until you flip the switch.


I'm trying to use a E18-D80NK but the output is always 1 i'm trying to use a E18-D80NK sensor with arduino but the output is always at 1, i really don't understand why
This is my code :

int irPin2 = 8;// define pint 2 for sensor

void setup() {
  Serial.begin(9600);// setup Serial Monitor to display information
  pinMode(irPin2, INPUT);// define pin as Input  sensor
}

void loop() {
  int out = digitalRead(irPin2);// read the sensor

    Serial.println(out);

  delay(250);
 // E18-D80NK Obstacle Sensor
}

and circuit:

There are a few possibilities for what is wrong:

1) The wiring may be wrong: the datasheet you reference lists two types (red,black,yellow) and (blue,brown,black) but in your pic it looks like you have (blue, grey, black).  I wouldn't assume the color coding of the sensor wires are correct.

2) The "pull-up" resister mentioned in the data sheet referenced (and included schematic) is not functioning as a pull-up resistor.  I would get rid of the resistor and plug the digital-output wire of the sensor directly into the arduino input.   Also, try configuring the input with pull-up like:  pinMode(irPin2, INPUT_PULLUP);
The Arduino inputs are high impedance and typically do not need a series resistor.


8Ω speaker, what resistor values to use? I want to connect 2 speakers of 8 ohm to 2 (different) pins of the Arduino.
However, for this example one speaker is enough.

I came across a lot of circuits without or with a single resistor which on other foras was not adviced, where one pin directly controls the speaker. This way (assuming 0,02A is the max recommended output for a pin), the resulting power is like 0.02A * 5V = 0.1W.

My speaker is 0.5W (8 ohm) and I want to hear how hard that is :-)

But it seems I have to use something with a transistor to isolate the path.
I came across this circuit:

However, when I would calculate the values or R1 and R2 myself I would get:

R2: Afaik, the recommended output for a pin is 0.02 A. This means:
V = I * R <=> 5 = 0.02 * R <=> R = 5 / 0.02 = 250Ω -> 270Ω (nearest higher value)
R1: my speaker is 0.5W, 8Ω.
P = V * I <=> 0.5 = 5 * I <=> I = 0.1A
V = I * R <=> 5 = 0.1 * R => R = 50Ω, which is Rtotal below:
Rtotal = Rspeaker + R1 <=> R1 = Rtotal - Rspeaker = 50 - 8 = 42Ω => 47Ω (nearest higher value)

This result in
V = I * R <=> 5 = I * (R1 + Rspeaker) <=> I = 5 / (47 + 8) = 5 / 55 = 0.0909 A
P = V * I = 5 * 0.0909 = 0.4545 W (so I lose 'just' 10%)

Are my calculations correct, and I assume the +5V pin of the Arduino will not have trouble giving 90.9 mA ?

Update:

I have some more questions regarding the accepted answer:

Would it mean if I use 7 transistors, all my voltages will be used for transistors and nothing is left (7 times 0.7 V which is approx. 5 V?)
**** Answer = No, a transistor will add Voltage so 7*0.7= 4.9Volt added ***
I assume I can better use as less as possible to 'switch' a transistor? * Answer = No, 0.7-Volt required, 5V is fine depending on the rating of the transducer   (but enough to be able to switch it) ? You say R2 can be smaller, but I can better make it higher not to waist voltage?  Answer = Changing the resistor will change the volume, look at the wattage rating for the speaker *
I already built the circuit below (but with a BC547 transistor) ... using a 0,25W R1 resistor. I guess I was lucky (?) * Answer = No, luck has no part, that transistor would work fine within the parameters used, look at the datasheet *
Regarding the base pin of the transistor ... by making the resistor higher (see item 2 above) ... that would help also not to burn the transistor pin? * Answer = No... please view the datasheet and ratings for the hw *
Again about the transistor, so I should make the resistor R2 in such a way that the gain times the mA is driving the speaker? (need to calculate this again) * Answer No, and I think you are thinking of "Gain" the wrong way, "Gain" is a "DB" measure and is for how well AC is transferred between antenna. *
You say to remove R1 completely ... but than I expect V = I * R <=> 5 = I * 8 => I = 0.625A ... P = V * I = 5 * 0,625 = 3.1W which blows the speaker? * Answer = Wrong way of looking at the 8-Ohm Impedance rating, Impedance is AC *

The speaker rating of 8 Ω is AC resistance, speaker impedance. Impedance (AC-Resistance) changes based on the frequency of the signal fed into it.

If you are worried about hurting the speaker and need to calculate power driving that particular "load", look at the speaker Wattage rating.
Say it is 1 W for example, and you are providing 5 V d.c., the amperage required will be: 0.2 A.

V * A = W
0.2 * 5 = 1

So the DC resistance is actually:

V = I * R (0.2 / 5 = 0.04 Ω).

Give it a higher amplitude... say 5.7 V to account for a transistor no resistor, and you get about 0.175 A. and a change in DC resistance again to 0.0301 Ω.

If the power supply is AC, the impedance needs to be matched to the speaker impedance to get best energy efficiency, otherwise the amplifier can be damaged.

For that circuit I suggest you place a variable resistor where the resistor is in your circuit to allow for a volume change. Also a flyback diode maybe a good idea, that will protect the speaker but take down voltage 0.7 V d.c. keep in mind you have that transistor there adding 0.7 V d.c.! so it evens things out too using that diode.

That diode placed on the high (+) side of the circuit, before the speaker and after the variable resistor.


What is recommended color recognition sensor RGB for different cases? What is recommended color recognition sensor in the following two cases:

To determine the color of the floor while the robot is moving (multi-color line follower).
To determine the color of an object in distance 10cm at least.

For both cases above, I am looking for a sensor so that I can get values like (R: 252 , G: 217 , B: 0) not only red, green or blue as an result, and no problem with small errors.

You have a conceptual error. You don't need n wires to transmite n bits of information. If you use a serial protocol, one wire or two is enough to transmit information of any size: you just send one bit after another.

Just think: you are downloading sketchs in your Arduino thru a cable with only 4 wires ...

Most sensors (and modules) for Arduino use I2C or SPI to transmit commands/information in digital format. You can learn a lot in this tutorial that covers I2C, SPI and USB.

A quick search on Aliexpress show me this APDS-9960 sensor

The sensor provide ambient light and color measurement, proximity detection and non-contact gesture detection. The APDS-9960 has built in UV and IR blocking filters, four separate diodes sensitive to different directions, and an I2C compatible interface.

Pins: VL (optional power to IR LED), GND (Ground), VCC (power to APDS-9960 sensor), SDA (I2C data), SCL (I2C clock), and INT (interrupt). Each APDS-9960 also has a detection range of 4 to 8 inches (10 to 20 cm).

It works with 3.3V.


The need to use logic level converter Why do we need level logic converter to have 5V or 3.3V?

Because in Arduino Uno/Mega (don't know about other boards), they already provide 5V and 3.3V for us to use.

Level logic converting for level shifting is different from powering a device.

Logic level is the state of a digital input/output. No voltage (or very little of it) is considered LOW.   Over the threshold voltage is HIGH. On a 3.3V system, if you set pin to HIGH, it has 3.3 V.  On a 5 V system, HIGH is 5 V.

A digital input pin reads HIGH once the threshold voltage is surpassed. If the input pin is for 3.3 V and doesn't have 5 V tolerance, feeding 5 V as HIGH could destroy it.  That is why you need level converter from 5 V to 3.3 V.

If the input pin is for 5 V and the threshold voltage is higher then 3.3 V,  3.3 V input will not be read as HIGH.  That is when you need level converter from 3.3 V to 5 V.

You must consult the 3.3 V device datasheet and check if the input pins are 5 V tolerant.   You should also check the digital pin threshold voltage on a 5 V device in case you want to communicate with it using 3.3 V.


What is the Arduino Uno default sketch? When I bought my Arduino Uno and connected it to my computer, I tried to make the simple blink circuit (before programming the Arduino) and suddenly the LED started blinking. Is the blink example the default Arduino sketch?

I am sure that I didn't uploaded anything to the board.

Some may have the "Blink" sketch pre-installed, but many don't. However, when there is no sketch installed the board sits in bootloader mode waiting for you to upload a sketch.  While it's in bootloader mode the LED pin pin D13 blinks.

If your LED is blinking about once a second then it's the Blink sketch.  If it's rapidly blinking three or four times per second or so then it's in the bootloader and you have no sketch loaded.


Error: Function not declared in the scope I want to make a timer library. The cpp file I have written is:

#include "avr/interrupt.h"
#include "Arduino.h"

#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
    TIFR1 |= _BV(OCF1A);
    TCCR1B = 0X00;
    digitalWrite(13,!digitalRead(13));
}

void AllTimer::setTimer(void)
{
    TCNT1 = 0x0BDC;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
}

ISR (TIMER1_OVF_vect)
{
    dofun();
}

And the header file:

#ifndef AllTimer_h
#define AllTimer_h

class AllTimer{
public:
    AllTimer();
    void setTimer(void);

private:
    void dofun(void);
};

#endif

While compiling the file i am getting the following error:

sketch_jan05a.cpp: In function ‘void __vector_13()’:
sketch_jan05a.cpp:34:9: error: ‘dofun’ was not declared in this scope

Because in the call:

 dofun();

you should put from which class you are calling that function.
In your case:

AllTimer::dofun();

in that case your function must be declared as static method.

EDIT:
Thanks to the comment:

I'm not pretty sure if your code reflects what you want to do. Because you can create your timer after defining the class:

Alltimer mytimer;

and call the method as a normal function (it must be declared as public):

ISR (TIMER1_OVF_vect)
{
    mytimer.dofun();
}

But it is hard to say since I m not sure what you want to do.


How to read temperature from multiple DS18B20 faster? I am writing an Arduino sketch to read temp data from multiple DS18B20 sensors and then write it to serial. The problem is, as I am connecting more sensors, the delay between my temp data is written to a serial increases (like 100ms for 1 sensor and 1s for 4 sensors). Can I somehow improve my sketch to read it faster?

Here is the sketch I am using:
(I am using DallasTemperature to simplify it all)

#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 10
#define TEMPERATURE_PRECISION 8
#define BAUD_RATE 9600

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress devices[10];
int devicesFound = 0;

void setup(void)
{
  // start serial port
  Serial.begin(BAUD_RATE);
  //Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(sensors.getDeviceCount(), DEC);
  Serial.println(" devices.");

  devicesFound = sensors.getDeviceCount();

  // report parasite power requirements
  Serial.print("Parasite power is: ");
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  for (int i = 0; i < devicesFound; i++)
    if (!sensors.getAddress(devices[i], i))
      Serial.println("Unable to find address for Device" + i);

  // show the addresses we found on the bus
  for (int i = 0; i < devicesFound; i++)
  {
    Serial.print("Device " + (String)i + " Address: ");
    printAddress(devices[i]);
    Serial.println();
  }

  for (int i = 0; i < devicesFound; i++)
    sensors.setResolution(devices[i], TEMPERATURE_PRECISION);
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

// function to print the temperature for a device
String printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC < 10)
    return "0" + (String)tempC;
  else
    return (String)tempC;
}

// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
  Serial.print("Resolution: ");
  Serial.print(sensors.getResolution(deviceAddress));
  Serial.println();
}

// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
  Serial.print("Device Address: ");
  printAddress(deviceAddress);
  Serial.print(" ");
  printTemperature(deviceAddress);
  Serial.println();
}

void loop(void)
{
  if (devicesFound == 0)
  {
     Serial.println("No devices found.");
     return;
  }

  sensors.requestTemperatures();

  String sent = "";

  // print the device information
  for (int i = 0; i < devicesFound; i++)
  {
    sent += printTemperature(devices[i]);
    if (i != devicesFound - 1)
      sent += " ";
  }

  Serial.println(sent);
}

With 12 bits precision, DS18B20 may take up to 750 ms converting a temp.

Try using async reading, so you don't have to wait for the end of the process.

First you ask for a reading, later your read it

    DallasTemperature sensors(&oneWire);
    ...
    sensors.setWaitForConversion(false);  // makes it async
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);
    ...
    // Do something else while temp is been reading by the sensor
   ...
   float temp = sensors.getTempCByIndex(0);


analogRead returning 0 constantly when connected to joystick What reasons could there be for a joystick to return 0 when using analogRead?

X-pin is connected to AO and y-pin is connected to A1.

VCC is connected to 5V and GRND is connected to GRND.

By default (as in when not using the joystick) the value should be approximately 500, right? Well why is the value then 0? Can this only be a wiring issue?

Follow these steps to identify the problem.

Disconnect A0/A1 from Arduino and use a multimeter to check the voltage coming from the joystick X and Y. If it swings from 0 to 5V....the problem is in the Arduino. Check your code and connections. Maybe your wires are damaged?
If the voltage is not changing at X and Y pins, disconnect power from the joystick and use a multimeter to check the joystick potentiometer. Check all three terminals in each axis of the joystick. If R is the measured resistance between the two outer pins, then the resistance between the central pin and each of the outer pins should vary from 0 to R depending on the position of the joystick.
If there is no problem at all with the joystick readings by potentiometer then the problem has to be on the Arduino side.


Atmega328p - PCB ISP pins for bootloader and sketch upload I want to design my PCB with Atmega328p chip on it and I want to be able to burn Bootloader and sketch after that while everything is soldered on the PCB. So my question is, what would be the best way to do that? My current idea is to leave extra pins for burning a Bootloader, and to leave also extra pins for uploading the sketch, and to "unplug" other stuff connected on these pins (for example on hardware UART) by adding\removing jumpers.

I'm pretty new to all this stuff, so I'm not quite sure what's the best approach.

Realistically, you should design ATmega boards to support both ISP and bootloader pins.  The logic is simple:

Unless you buy pre-programmed chips, or have a programming fixture, you will need ISP either to load the firmware itself, or to load a bootloader.
Even if you plan to use only ISP for programming, it is still worth providing external connections to the UART pins for interacting with firmware during development; generally with ATmega-based Arduinos you do not have a breakpoint debugger, so debug messages on serial are your primary visibility into what is happening.
You should wire the reset line to somewhere that you can manipulate it, so you don't have to power cycle your firmware every time you want to restart it in testing.

Once you have done all that, you end up with support for both ISP and UART bootloader - regardless if you plan to use them both or not.


Led issue with arduino controled by raspberry pi/python I'm having an issue with my project. My project is 8 leds and a potentiometer on an arduino being read and controlled by a raspberry pi running python.

when I'm using a potentiometer the signal is received by my raspberry pi with python which then tells a set of leds to either turn on or off. However my leds flash on my low threshold when they shouldn't, the leds on my higher threshold work as expected and stay on till my pot is out of that range. How can I fix this?

Here is my script!

from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

serial_manager.connect('/dev/ttyUSB0')

POT = 0
LED1 = 13
LED2 = 12
LED3 = 11
LED4 = 10
LED5 = 9
LED6 = 8
LED7 = 7
LED8 = 6

Arduino.pinMode(POT, Arduino.INPUT)
Arduino.pinMode(13, Arduino.OUTPUT)
Arduino.pinMode(12, Arduino.OUTPUT)
Arduino.pinMode(11, Arduino.OUTPUT)
Arduino.pinMode(10, Arduino.OUTPUT)
Arduino.pinMode(9, Arduino.OUTPUT)
Arduino.pinMode(8, Arduino.OUTPUT)
Arduino.pinMode(7, Arduino.OUTPUT)
Arduino.pinMode(6, Arduino.OUTPUT)

print "starting"
while True:
    pot = Arduino.analogRead(POT)
#this is the section that is blinking when it should stay solid
   if pot < 450:
        Arduino.digitalWrite(LED1, Arduino.HIGH)
        Arduino.digitalWrite(LED2, Arduino.HIGH)
        Arduino.digitalWrite(LED3, Arduino.HIGH)
        Arduino.digitalWrite(LED4, Arduino.HIGH)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.5)
# end of section
   if pot < 650 > 450:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.1)
    if pot > 650:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.HIGH)
        Arduino.digitalWrite(LED6, Arduino.HIGH)
        Arduino.digitalWrite(LED7, Arduino.HIGH)
        Arduino.digitalWrite(LED8, Arduino.HIGH)
        sleep(.5)
    print pot

Your second condition is written wrongly. It should be this way:

elif pot >= 450 and pot <= 650:
    # do stuff

Your code should be such that only an option is chosen at any time. There should be only one 'if' condition at the top and the rest should be 'elif'.


analogRead Function AC Voltage Reading Capabilities Usually when you sense AC voltage, you get a sinusoidal waveform. However, for AC voltage sources, Arduino analogRead ( ) only presents positive voltage values. So what's basically happening? Is it skipping half the cycle where the voltage is negative. If so, how can I account for that when I try to use the voltage values to calculate for total electrical energy generated by the source (piezoelectric film) and avg. power?

I guess that you are showing the voltages there directly calculated from analogRead() and that you connected the AC voltage directly to the analog input (and it's ground with the Arduino's ground).

The reference for every communication/voltage measurement/digital input is ground. Naturally the Arduino can only measure voltages inside of it's own supplied voltage range, meaning 0 to 5V for the Uno. If you apply a negative voltage (relative to ground), you will measure a voltage of 0V. You can even damage the microcontroller, if the negative voltage is too high.

If you have negative and positive voltages, you should offset the signal at the analog input pin, so that the resulting signal stays in the range from 0 to 5V. You can do this with a simple voltage divider. Use two resistors with the same value (for example 5kOhm), so that you will get a new zero point at 2.5V. The AC signal will then variate around that value.

For what is happening inside the microcontroller:

The ADC is responsible for measuring the voltage. For this the voltage on the analog input pin will first be sampled (loaded onto an internal condensator) and then step by step compared to the voltages, that the ADC generates by dividing the supply voltage range into 1024 distinct values (10 bit). Again the reference, to which the voltage is measured/compared, is ground. It cannot generate negative voltages, thus cannot compare them.


Trouble with setting the PWM frequency for Arduino Due I'm using Arduino Due and I set the analog read and write resolution to 12-bit for better resolution. Basically all I do is to vary PWM duty cycle by controlling analog DC input voltage from 0 to 3.3V. The simple code as it is now works fine as follows:

int pwmPin9 = 9;
int analogPin0 = 0;
int val = 0;

void setup() {

  Serial.begin(9600);

  pinMode(pwmPin9, OUTPUT);  // sets the pin as output
  analogWriteResolution(12);
  analogReadResolution(12);

}

void loop() {

  val = analogRead(analogPin0);  // read the input pin
  Serial.println(val);
  analogWrite(pwmPin9, val);

}

My problem is I need to set the frequency of the PWM output to 25kHz or at least something nearest above 25kHz.

I have been searching forums hours and couldn't find any solution. Here I came across a way but there is no library called variant.h in my folders. And that code if I include in my script doesn't change anything.
What could be a workaround for this?

(I used to achieve this via this site by using Arduino Uno but for Due couldn't find any working solution)

Edit: I found the file and made the following change in variant.h:

 * PWM
 */
#define PWM_INTERFACE       PWM
#define PWM_INTERFACE_ID    ID_PWM
#define PWM_FREQUENCY       20000
#define PWM_MAX_DUTY_CYCLE  4095
#define PWM_MIN_DUTY_CYCLE  0
#define PWM_RESOLUTION      12

/*
 * TC
 */
#define TC_INTERFACE        TC0
#define TC_INTERFACE_ID     ID_TC0
#define TC_FREQUENCY        20000
#define TC_MAX_DUTY_CYCLE   255
#define TC_MIN_DUTY_CYCLE   0
#define TC_RESOLUTION       8

But it only works for 20kHz. If I set to 25kHz or 30kHz I don't get any error but also don't get any output :((

There are a few things to do. I've used this successfully in the past with older projects.

As a side note one can very easily change PWM settings on pins with the esp32, a single line of code being ledcSetup(PWM_Channel_Number, Frequency, resolution) without ever having to actually dive into modifying variant.h

To Quote Kerry D. Wong:

  If you take a look at the function PWMC_ConfigureClocks in pwmc.c, you will see that the highest PWM frequency can be accommodated as the function input is 42 MHz, this is because inside the function it calls FindClockConfiguration which in turn ensures that the frequency parameter passed in is less than the MCK frequency. Thus for integer dividers, the highest frequency we can pass in is 42 MHz (with divider 2).

  To achieve the highest output frequency, we can use a one bit PWM which essentially just outputs a square wave with a duty cycle of one. We can then set the prescaler to 2 to obtain an 84 MHz waveform.

#include <Arduino.h>

uint32_t pwmPin = 8;
uint32_t maxDutyCount = 2;
uint32_t clkAFreq = 42000000ul;
uint32_t pwmFreq = 42000000ul;

void setup() {
  pmc_enable_periph_clk(PWM_INTERFACE_ID);
  PWMC_ConfigureClocks(clkAFreq, 0, VARIANT_MCK);

  PIO_Configure(
    g_APinDescription[pwmPin].pPort,
    g_APinDescription[pwmPin].ulPinType,
    g_APinDescription[pwmPin].ulPin,
    g_APinDescription[pwmPin].ulPinConfiguration);

  uint32_t channel = g_APinDescription[pwmPin].ulPWMChannel;
  PWMC_ConfigureChannel(PWM_INTERFACE, channel , pwmFreq, 0, 0);
  PWMC_SetPeriod(PWM_INTERFACE, channel, maxDutyCount);
  PWMC_EnableChannel(PWM_INTERFACE, channel);
  PWMC_SetDutyCycle(PWM_INTERFACE, channel, 1);

  pmc_mck_set_prescaler(2);
}

void loop()
{

  Note that VARIANT_MCK is defined in /arduino-1.5.7/hardware/arduino/sam/variants/arduino_due_x/variant.h as 84000000. PWM_INTERFACE_ID and PWM_INTERFACE are defined in variant.h as ID_PWM and PWM which in turn are defined in /arduino-1.5.7/hardware/arduino/sam/system/CMSIS/Device/ATMEL/sam3xa/include/sam3x8e.h.

  So as the conclusion, the highest stable frequency we can generate using an Arduino Due is 84 MHz. The pictures below show the captured waveforms under different frequencies. For the 21 MHz waveform, pwmFreq is set to 21000000, no prescaler is used. For the 42 Mhz waveform, pwmFreq is set to 420000 with no prescaler. The 84 MHz waveform is generated with set to 42000000 and the prescaler set to 2.

Hope this helps.


arduino beginner documentation help I plan to buy these 2 products to begin to play with arduino to learn.

Board with LCD touch
Yun board expansion

I have a mega 2560 which i bought with a starter kit and i love to play with. I have not played with the shield yet. I understand some shields can be used together, some not. and some with modification on the board and in the code.

I can't find pins specification for the touch screen and the support on the website doesn't respond.

If some one can help me find specifications for the touch screen, or help me choose some shields that will allow me to use a USB host, wifi, and a touchscreen it will be nice.

Thanks all.

The link you posted describes a TFT LCD Touch screen unit with the SPFD5408 controller, referenced in this Instructable for use with the Mega. You might start there and migrate to the Yun once you get the screen working.


softwareserial between arduino uno and esp8266 I have an Arduino UNO and HUZZAH ESP8266  module.  I need to send data between Arduino UNO and ESP module via Software Serial.  Right now I have the ESP module write data and Arduino UNO display data, but not working. When I run the Arduino UNO  and open its Serial Monitor, nothing is printed using below source code.

ESP8266 RX PIN connected to Arduino UNO PIN 2.
ESP8266 TX PIN connected to Arduino UNO PIN 3.
Using the FTDI cable that came with HUZZAH ESP8266 to power this module.  I just individually connected the RX and TX pins to the ARDUINO PIN 2 and 3 as mentioned above.

Any ideas what why not working? Below is code for both modules. Thanks,

Arduino UNO

#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // RX | TX

void setup(void){
  //Start hardware Serial communication
  Serial.begin(115200);

  //Start the software serial for communication with the ESP8266 component
  ESPserial.begin(57600);

}

void loop(void){

if (ESPserial.available()){
  Serial.println("ESP available!!!");
  Serial.println(ESPserial.read());
}

}

HUZZAH ESP8266

#include <ESP8266WiFi.h>

#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // RX | TX

void setup(void){
  //Start the software serial for communication with the Arduino UNO component
  ESPserial.begin(57600);

  //TODO: setup Wifi
}

void loop(void){
   ESPserial.write("This message generated by ESP module.");
   delay(500);
}

Make sure that:

RX pin on the Arduino UNO is connected to the TX pin on the ESP8266.
TX pin on the Arduino UNO is connected to the RX pin on the ESP8266.
Baud rate should be set to the same value from both the Arduino and ESP8266.

I don't know about your arduino but looking at this schematic, your RX and TX should be swapped.


Arduino IDE libraries search Where I can do search libraries on WEB, that similar search in IDE? I did not find search page on arduino.cc

You get widest search with Google. Write "arduino" and then the device or topic name.

Most of the libraries have a GitHub repository. You can use a search field on GitHub.

A list of selected libraries sorted by topic is on Arduino playground.


Two signal with delay I have a two pins for two blinks leds but I need delay the second signal from first. I start the first signal and I need start the second signal 50ms later. The first signal is 500ms HIGH and 500ms LOW, and the second signal is 400ms LOW and 600ms HIGH. If I start the second signal 50ms later, I can center the high period of the first signal with the low period of the second signal.

This is my code:

long DelaySecondSignal = 50;
int A = 1;

while (A == 1)
{
    long millis_actuales = millis();

        //Control Salida_A
        if (millis_actuales - TiempoTranscurrido_SalidaA > (Estado_SalidaA ? 500 : 400)) {
            digitalWrite(SalidaA, Estado_SalidaA = !Estado_SalidaA);
            TiempoTranscurrido_SalidaA = millis_actuales;
        }

        if (millis_actuales > DelaySecondSignal)
        {
            //Control Salida_B
            if (millis_actuales - TiempoTranscurrido_SalidaB > (Estado_SalidaB ? 500 : 600)) {
                digitalWrite(SalidaB, Estado_SalidaB = !Estado_SalidaB);
                TiempoTranscurrido_SalidaB = millis_actuales;
            }
        }
}

TiempoTranscurrido_?? is a int and Estado_Salida? is a boolean.

I need start the second signal with 50ms of delay but "if (millis_actuales > DelaySecondSignal)" no work.

Thanks.

Your problem is that you are treating both signal separately. Instead you need to think about the events of turning LEDs on and off and where they lie on a combined timeline:

     0    100   200   300   400   500   600   700   800   900  1000
     |-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|
     ^  ^                       ^  ^
  1 on  2 off                2 on  1 off
  1: ooooooooooooooooooooooooooooooo
  2: oooo                       oooooooooooooooooooooooooooooooooo

You see how I have looped the time around so that the turning off of the second signal, which would normally come at 1050ms, in fact comes at 50ms. By just working in a single 1000ms block of time as a loop things become much simpler.

You can do it now with just a simple set of delays, now you have it laid out in a single timeline like that:

void loop() {
    digitalWrite(led1, HIGH);
    delay(50);
    digitalWrite(led2, LOW);
    delay(400);
    digitalWrite(led2, HIGH);
    delay(50);
    digitalWrite(led1, LOW);
    delay(500);
}

All the delay() calls add up to 1000ms and it keeps looping around.

If you want to make it non-blocking you should set it up with a small finite state machine. There are 4 steady states which are the four spaces between the events on the timeline. There are 4 transitions, which are the events on the timeline.  So you:

Start in state 0 with both LEDs on (which is how they are at the start of the timeline).

0: When 50ms have passed turn off LED 2 and move to state 1.
1: When 400ms have passed turn on LED 2 and move to state 2.
2: When 50ms have passed turn off LED 1 and move to state 3.
3: When 500ms have passed turn on LED 1 and move to state 0.


Cheap 2-5mb memory to use with arduino I'm looking for a storage solution for small files that would be moved into a small sensor running arduino-like processor.

Ideally the single memory unit would be cheap (in 1-10 cents range), but the memory can be very limited (several megabytes).

The closest I've got so far is small SD Memory card, but the smallest 4GB ones cost several dollars (at least bought in quantities < 100). Anything else I should be looking at?

I assume that, if this is a cost sensitive item, you need a reliable supply of multiples (so looking for small SD cards on e-bay isn't a viable solution).

Does it need to be non-volatile storage? If it does't you may be able to find small 8-bit wide RAM chips at a pretty good price. If it needs to be non-volatile, you might look at individual flash chips. I found this one, an 8-bit by 512 KB Serial-SPI flash chip for £0.19 (about $0.28 US) in single units and £0.176 if you can by 100 at a time. I would expect DRAM chips and chips with a simpler interface to be less expensive (but you might end up spending more on interfacing the chips so it might end up as a wash).

If you're able to consider a variety of processor chips it might be worth looking for something that has adequate storage on chip. That might be the most cost effective way to get the space.


How does arduino fetch instruction string from sms and execute? I am working on a project in which i have to send commands using sms (GSM shield) to the arduino uno to control dc motor. What i want to know is that how can i define the instruction strings that i can send in form of sms and arduino uno reads it and executes it.

P.S. I am a total beginner at arduino coding so please help me out.

Your GSM shield will receive the SMS which your Arduino code can retrieve as a string of characters (that description hides a mountain of detail, most of which you won't need to know). It doesn't care what the content of the SMS message is.

Your Arduino code will have to translate from the message text to motor-control commands so you want some text commands that will be easy to parse, but not so trivial that any random message might wrongly be interpreted as legitimate commands.

The digit pair "15" might command motor 1 to speed 5. But you wouldn't want any message with a couple of digits in it to change a motor. (You didn't say you had multiple motors, and if not you can leave that part out).

Let's make the message distinctive enough that it's unlikely to appear in some other context, yet simple enough to distinguish as legitimate. It would be nice if it's simple to thumb-type, too!

"motor,1,5" could convey the same information as the "15" in our first example, doesn't limit you one-digit values, isn't likely to appear in a "Hey Dude, lunch at 12:15?" type of conversation, is easy to parse and isn't too long to type on a tiny keyboard. You could extend it later, so "motor,1,+2" could mean to increase motor 1's speed by two units, "motor,1,off" could mean power it down (not just zero speed), and "motor,all,off", well, that's probably obvious.

Look up the function sscanf() [oops: not sprintf()] for one way to parse the incoming strings and collect their data.

Update: sscanf() does the reverse of sprintf(): It reads a string, collects values from it, and assigns them to variables. Search sscanf on the web for a description of its use.
Here is a sample program that reads a few possible SMS messages, checks whether they are motor commands (according to my simple example SMS above), and if it is, assigns the contained values to some variables in your program. You can see by the return values of sscanf() whether and how many conversions it made from each message, thus your code can tell whether a received SMS looks like a motor command, as well as what the command values are:

/*
 * sscanf example - Uses sscanf to test and collect data from a
 * a command string.
 */

#include <WProgram.h>

void test_sscanf(const char *sms);

// Sample of SMS messages to test whether our sscanf() format string
// can recognize good ones and reject bad ones. Experiment by adding
// ones of your own:
const char *SMS[] =
{
   "motor,1,5",
   "Hello World,3,2",
   "motor 123 456",
   "moto, 7, 13",
   "motorized, 4, 11"
};

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

   delay(1000);     // delay for user to launch a terminal (if you're quick)

   // Test each SMS example in the SMS array
   for( uint8_t s = 0; s < sizeof(SMS)/sizeof(char *); ++s ){
      test_sscanf(SMS[s]);  // test one SMS string
   }
}

void loop() {
   ;            // nothing to do here
}

// Tests a sample SMS, prints the number of variables it assigned, and what
// their values were. '0' means it didn't assign any, probably because the
// command-word failed to match.
void test_sscanf(const char *sms)
{
   int16_t assigned, values[2];

   // Print the SMS and convert it.
   Serial.print("\nSMS: \""); Serial.print(sms); Serial.println("\"");
   assigned = sscanf(sms, "motor,%d,%d", &values[0], &values[1]);

   // Display the results
   Serial.print(assigned);  Serial.println(" values assigned"); // How many values? A good command has 2.
   if( assigned > 0 ){
      for( uint8_t i = 0; i < assigned; ++i){
     Serial.print("value["); Serial.print(i+1); Serial.print("] = "); // print each assigned value
     Serial.println(values[i]);
      }
   }
}


How to fix this code so instead of having to hold button to change led, you can press? const int buttonPin = 1; // the pin number of the pushbutton input pin
const int ledPins[] = {2, 3, 4, 5, 10, 11, 12, 13};    // variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonPressCount = 0;
int numberOfLED = 8;

void setup() {    // initialize the LED pin as an output:
  for (int i = 0; i < numberOfLED; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
  pinMode(buttonPin, INPUT);
}

void loop() {    // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);    // check if the pushbutton is pressed.    // if it is, the buttonState is HIGH:
  if (buttonState  == HIGH) {
    for (int i = 0; i < numberOfLED; i++) {
      if (buttonPressCount % numberOfLED == i)
        digitalWrite(ledPins[i], HIGH);  // turn LED on
      else
        digitalWrite(ledPins[i], LOW);   // turn LED off
    }
  }
  buttonPressCount++;
  delay(300);
}

instead of changing every time the buttonState == HIGH, change it when the button state was LOW the previous time but HIGH now:

buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState && buttonState == HIGH) {
    //...
}
oldButtonState = buttonState;

However keep in mind contact bounce. Which can result in multiple transitions being detected. Most solutions for that set a minimal delay between handling transitions, dropping all others detected.


Where are the Arduino Due registers? Having most of my experience on ATmega chips, and just starting up with Arduino (to reduce hardware development time) I'm happy to see that the usual registers such as TIMSK0, PCICR, TCNT1H and others can be used from the Arduino IDE just as they appear in the Atmel datasheet.

Migrating to the Arduino Due, however, came with a shock: the registers specified in the datasheet of the Cortex-M3 are not recognized by the Arduino IDE (although I downloaded the extension necessary for being able to select the Due). I wanted to do something very simple, like configuring a timer. I found TC_CMR0 in the datasheet, but the Arduino IDE doesn't recognize it. I found an example using the Arduino Due with timers in an obscure forum, and they used REG_PWM_CMR0. I tried it in the Arduino IDE, and it was accepted by the compiler.

I searched the Arduino and other forums, and couldn't find any hint whatsoever about the naming of the registers. Why are the names of the registers different? And can I find a conclusive documentation about the register names, or am I doomed to research each and every one of the hundreds of registers individually?

There are a few files in the Arduino Due core that you should have a look at. They give great insight into the SAM register set up; variant.h, variant.cpp and chip.h

After that you can dive into the libsam and the many components (include/source).

The SAM code has a very different structure and style compared to AVR.

Cheers!


Servos stop after a while in case of 8 servo motor control I recently purchased 10 units of MG996R servo motor and the 16 channel 12-bit PWM/Servo driver from Adafruit for a small project. I confirmed that all of my servos are functional and that my code is correct. My issue is that there seems to be a limit on the number of servos I can run. With 4AA batteries, I can power about 3 of the MG996R servos. Starting with the 4th one, they stop moving. I supposed that the current drawn from the servos is high, so I tried powering the servos by providing two 4AA batteries in parallel (8AA). This appeared to have increased the number of servos I can run. But after a few minutes, the servos stop responding and I have to disconnect the power for a while before the servos respond again. I read on Adafruit that I may need to add a capacitor to the PWM/servo drive if I have multiple servos. Is this my problem or I just need to provide more power? Why do the servos seem to respond initially but stop moving after a while? Thanks in advance.

If Adafruit say to use the kit to drive multiple servos you need to add a cap and without the cap you can't drive multiple servos, then yes your first port of call should be to add the cap.

However that's probably not all that's wrong.  If it runs for a bit before dying then it could be a number of causes.

Not enough power.
Something is overheating.
Code problem.

Use a decent transformer with more than enough amps to power your motors.
Use your nose, does something smell hot?  If you use your fingers you will get burnt!
We can't fix invisible code.


Arduino Micro: how to switch off its blue power LED? everybody!

I have a genuine Arduino Micro ("designed with adafruit", made in Italy) which is working perfectly well.

One thing I'd like to do but cannot figure out how (or at all), is to turn off the blue power LED. I hate blue LEDs, they hurt my eyes, and this one is particularly bright too.

I could just paint it over with black paint but maybe there are programmatic ways to switch it off?

Regards

Unfortunately the blue LED is a direct connection between 5V and GND. You can see below in the schematic exactly how it is connected

The only way to 'turn off' the LED would be to remove either the 1K resistor or LED with a soldering iron.

Another possibility is to take a sharp knife and make a cut in the track directly before or after the LED. I've marked the locations where to cut on the eagle screenshot.


ESP8266 only executes Sketch after switching on/off CH_PD pin I started a new project with an ESP8266-01 module. I want to use it as stand-alone circuit to send an Email at the press of a button.

The wiring is:

VCC    -  3.3v VCC
CH_PD  -  3.3v VCC
GND    -  GND
GPIO_2 -  Push down button (internal pullup)

I've the sketch (Arduino IDE), I've upload it and it essentially works. However:

If I call the sendEmail(); method inside the void setup(){}, it works like a charm.
If I add an push down button on Pin #2 (GPIO_2) it only works if I previously have removed VCC from the CH_PD pin and reattached it again shortly after.

Now, I would bet I read something regarding (or similar) this situation a couple of days back, but I am unable to find it again, now that I need it.

Is there a solution for this or am I missing something?

Any help will be greatly appreciate it!

Thanks in advance!

Well, after literally spending hours trying to figure out what the heck is going on, I decided to test the setup with a ESP8266-12 NodeMcu, which is essentially the same but more resembling to an Arduino in that it has more in/out pins and it's better for testing.

On this platform I got a different behavior. I was able to send an Email by the push of the button but... only once. So apparently, contrary to what I believed, something was wrong with the code.

In the code there is this method, which essentially initiates the WiFi connection:

void initializeWifi(){

  WiFi.begin(WIFI, PASSWORD);

  // allow time to make connection
 while (WiFi.status() != WL_CONNECTED)  delay(5000);

  }

Somehow the delay(5000); didn't seem right as delay usually freezes the whole thing. When I commented out the line, everything worked as expected. With the NodeMcu as well as with the ESP8266-01.

However, I still have to figure out how to give time to the WiFi to connect without freezing out all together. Probably it's the time for millis();

I hope this becomes useful to somebody else in the future.


Notoriously unstable ESP8266 MQTT-client I am doing a project where an ESP8266 receives data from an Arduino Uno and publishes it via MQTT. After a random amount of time, it will stop sending data to my MQTT broker. It might be an hour, it might be a day or two.

It's set up to send data every second, and I made a debug output telling me the WiFi signal quality as well. Seems like that's not it.

I have tried making checks that will reconnect to MQTT if it looses connection, and that it resets itself if it looses WiFi connection. I'm out of ideas right now, any help appreciated!

Here's my MQTT reconnnect function

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("pressure/debug", "ESP8266: reconnected!");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

and here's where it checks for WiFi

void checkWifiConnection() {
  if (WiFi.status() != WL_CONNECTED)
  {
    int countdown = millis() + 15000;
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      if (countdown > millis()) {
      delay(500);
      Serial.println("Connecting to WiFi..");
      } else {
        Serial.println("Timed out! Restarting...");
        ESP.reset();
      }
  }
  }
}

Both are run every loop.

The arduino sends the data like it's supposed to, and I've lowered the connection speed to 19200bps in order to ensure a more stable connection, using SoftwareSerial. Any more things i could monitor? I tried it with two different ESP8266MOD/"ESP07" boards with the same result.

Here's a debug output:

09:13:05.039 -> unpub data 0/ AP:Akvasafe/ RSSI:-69 dB / Vcc:3519mV / free heap:49440 / fragmentation:1%

I use adafruit mqtt library. After a few fixes, it is running very stable.

Tips:

1) Make sure you put subscribe line BEFORE connecting to mqtt (you can put it in setup and connect to mqtt in loop)

Like:

Setup: mqtt.subscribe(&motor);

Loop: MQTT_connect();

Yes, you can both publish and subscribe at the same time.

2) IN THE LINE: Adafruit_MQTT_Client(server,port,user,pass)

CHANGE TO THIS: Adafruit_MQTT(server,port,clientid,user,pass)

Use this with client id (MUST BE UNIQUE (EG: Different for all clients))
or your client will be kicked off when other client with same id connects.

3) Convert value.lastread from char* to int : int val = atoi((char *)sensor.lastread);

More about ESP8266 & ESP32 : http://github.com/ajaybnl


Having 3 buttons with only 2 input pins for the purpose of learning, I'm trying to have a kind of digital/binary input where I'm using 3 buttons but only 2 input pins.

I thought of

01 = Button 1
10 = Button 2
11 = Button 3

My first attempt was like this:

I left the resistors out right now. The problem here is of course, that it doesn't matter what button I press, both LEDs are lighting up.

I used 2 Diodes in my second attempt:

This time, S1 and S2 work as expected, but S3 brings only one LED up.

Now I was wondering how I can wire things up correctly, using as little components as possible and having in mind, that I'm going to use an Arduino instead of the LEDs.

Thank you for any help!

The logic of your second attempt is perfectly correct.

If you put resistors in series with the LEDs you may get more joy out of it. Having two LEDs in parallel without resistors often results in one LED lighting and the other not.


LED Blink in assembly with timer1 output compare interrupt not working I was trying to have some fun with avr-assembly on my arduino and I tried the following codes to blink my LED
first I tried the ISR approach and when It didn't work I tried the CTC mode one,
both codes are listed respectively. on the first one the LED lightsup and stay that way (no blinking) on the second one it just stays off
one more thing to note is on trying to load OCR1AL first The led would blink nicely if my hand got near PORTD pins for some reason,
I guessed it's some grounding problem and It's fixed when I pulled high all PORTD pins and it disappeared completely when I figured out that I need to load (the high byte) OCR1AH first
.nolist
.include "m328Pdef.inc"
.list

.org    0x0000
jmp     Init

.org    0x0016
jmp     TIMER1_COMPA

.EQU    LED_PIN = PB1

Init:
    ;ldi    r16, 255
    ;out        DDRD, r16
    ;out    PORTD, r16

    ;First configure The led pin as output and initilize it to high
    sbi     DDRB, LED_PIN
    sbi     PORTB, LED_PIN

    ;Second Enable Global Interrupts
    sei

    ;Enable the Output compare Interrupt in the TIMSK1 Register
    ldi     r16, 0b00000010
    sts     TIMSK1, r16

    ; Reset the TCCR1A
    ldi     r16, 0b00000000
    sts     TCCR1A, r16

    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16

    ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
    ldi     r16, 0b00111101
    ldi     r17, 0b00001001
    sts     OCR1AH, r16
    sts     OCR1AL, r17

LOOP:

    rjmp    LOOP

TIMER1_COMPA:
    ;First Reset the coutner
    ldi     r16, 0
    sts     TCNT1H, r16
    sts     TCNT1L, r16

    ;Second Toggle the Pin (LED) state
    sbi     PINB, LED_PIN

    reti

CTC:
.nolist
.include "m328Pdef.inc"
.list

.org    0x0000
jmp     Init

.org    0x0016
jmp     TIMER1_COMPA

.EQU    LED_PIN = PB1

Init:
    ;ldi    r16, 255
    ;out        DDRD, r16
    ;out    PORTD, r16

    ;First configure The led pin as output and initilize it to high
    sbi     DDRB, LED_PIN
    sbi     PORTB, LED_PIN

    ;Second Enable Global Interrupts
    sei

    ;Enable the Output compare Interrupt in the TIMSK1 Register
    ldi     r16, 0b00000010
    sts     TIMSK1, r16

    ; Reset the TCCR1A
    ldi     r16, 0b01000000
    sts     TCCR1A, r16

    ; Set the prescalar to 256 in the Timer Control 1 registers
    ldi     r16, 0b00001111
    sts     TCCR1B, r16

    ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
    ldi     r16, 0b00111101
    ldi     r17, 0b00001001
    sts     OCR1AH, r16
    sts     OCR1AL, r17

LOOP:
    rjmp    LOOP

TIMER1_COMPA:
    ;First Reset the coutner
    ;ldi    r16, 0
    ;sts    TCNT1H, r16
    ;sts    TCNT1L, r16

    ;;Second Toggle the Pin (LED) state
    ;sbi        PINB, LED_PIN

    reti

I am not set up to test your code right now, perhaps later.  But:
    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16

When set to ones, the low order three bits of TCCR1B, select an external clock source at the T1 pin, for clocking on a rising edge.  Probably what's happening is that when you finger is near enough the T1 pin you are capacitively coupling mains frequency to it causing it to tick.
/256 prescaler would have 100 in the lower three bits.
If I manage to get a proper environment up to test your code, I'll look into it a bit more thoroughly.


How can I clear the memory of my Arduino in this case? I have made a code using involving HID control. But it seems that I messed up, but I can't upload a new sketch(nor edit the wrong code), because my Arduino is constantly doing things like Ctrl+Alt+Delete, Alt+F4... etc.
It seems that the only way is erasing the code in the memory, but how can I do so?

Do the "button dance" - hold the Arduino in reset, releasing just you see the download start in the IDE. This may (will!) take a little practice to get just the right timing.

or

Use an external programmer connected to the ICSP connector. This could be a commercially made one, a DIY, or another Uno programmed and connected as an ICSP programmer. How-to's abound on the web.


How to ssh via USB Ethernet adapter For a few days now, I have been connecting to my board which is hooked up to my router through a clutter of wires, over Wi-Fi. To spare my family from the risk of tripping, or hogging the extension cords all to myself, I'm looking for a way to establish an ssh connection directly from my computer (either via a USB Ethernet or a Thunderbolt Ethernet adapter).
My question is what address will I be looking for? Is it something like arduinoname.local?

ssh root@[arduinoname].local

does the trick. Just replace [arduinoname] with your board's name: ssh root@myboard.local
Seems to take a minute or two to initialize, so if it doesn't work immediately don't give up right away!
This however won't allow you to access your internet, so I'll still have to connect to my router if I'm going to be downloading anything.


How to establish a connection between an Arduino and a web server via ESP8266 I'm working on a IOT project where three or more IOT device communicates with a web server. The IoT device will have Arduino UNO which is connected to a ESP8266 so internet access is available. Arduino UNO reads current sensor data and post it to a website that I built and I also want to control a single relay switch from the same website. I am a beginner and most project I find is only single directional communication or making ESP8266 as web server. Please point me to right Direction.

I was able to post sensor data to thingspeak.com. I was also able to control The relay switch from a website but only separately. I was not able to make it work when I combined the two.

Directions:

How to build web APIS to send and receive data to Arduino UNO via esp8266?
How to send data and check the received data in Arduino UNO VIA esp8266?
Can I send and receive data in JSON format Arduino UNO?
How can the Arduino UNO filter required data from the received json?
Is this project possible without Arduino and just by programming the ESP8266 module?

I know basic HTML, Basic CSS, Basic JavaScript, Basic Nodejs, json and a tiny bit of JQuery.

Is this project possible without Arduino and just by programming the
  ESP8266 module?

Yes if you use ESP-12 or an esp8266 dev board like Wemos or NodeMCU. The problem could be the current sensor. I would recommend to read it with I2C ADC module, because the esp8266 A0 can read only to 1 V and is shared with WiFi functions. Wemos boards use a circuit to read analog until 3.3 V, but it doesn't help much.

  How to build web APIS to send and receive data to Arduino UNO via
  esp8266?

Run your Web server in Internet and let the esp8266 and clients communicate over it. But think about security.

For accessing a Web server from Arduino or esp8266 see the WebClient example of networking libraries.

  How to send data and check the received data in Arduino UNO VIA
  esp8266?

For Arduino with esp8266 as network adapter connected to Serial you can use AT firmware in esp8266 and WiFiEsp library in Arduino. Or you can have a sketch for the esp8266 with Arduino esp8266 core package and your own protocol over Serial to communicate between esp8266 and Uno. And there are firmwares for esp8266 written as esp8266 sketch, which you can use with corresponding Arduino library (WiFiLink, WiFiSpi).

  Can I send and receive data in JSON format Arduino UNO?
  How can the Arduino UNO filter required data from the received json?

ArduinoJson library helps with processing the JSON format. Amount of RAM could be a problem on Uno.