Arduino Nano with Mac OS Yosemite 10.10 I have an Arduino Nano and I’m trying to use it with Mac OS Yosemite (10.10). However, I’m having issues with the data transfer between the computer and the device. The Arduino is powered (LED is illuminated), however, I can’t upload anything to it. The serial port is not recognised and after installing a multitude of drivers, nothing seems to work.

Is there a specific driver or process I need to follow to enable data transfer?

Setting kext-dev-mode=1 allows unsigned kernel extensions to load, which is not recommended, as it lowers OS X security.

Instead, try the signed 64-bit kernel extension from FTDI here: http://www.ftdichip.com/Drivers/VCP.htm , version 2.3, which does require changing OS security permissions.


Nano onboard "test" LED blinks when powered via 5V pin I have a Nano (clone) that I am powering from a regulated supply via the 5V pin; I have checked this at the board and my multimeter reads 4.92V, which seems close enough (?). The main reason I don't use the microUSB jack is a space constraint. In any case, thus far it does work fine.

Except the leftmost (considered with the microUSB jack as "top") of the four onboard LEDs, on the opposite side from the rx/tx lights, blinks at a steady one second interval.  Searching around, the only association I've found for that LED is that it is connected to D13, which I'm not using for anything.

What does this indicate?  I have not tried disabling it (by setting 13 low) but I am hoping to do so if it is a benign issue.

So, as per the comments on the question here's what I think happened:

That "test" LED lights briefly when the board is first powered on, indicating I suppose that it's booted and setup() is either complete or about to run.

It also lights briefly when the reset button is released.

In the sketch I'm using one of the digital pins is connected to RST -- the arduino is being controlled via UART.  I have swapped some of the pin numbers and wiring around, so I tried leaving the one driving RST low instead of high and indeed, this seems to be the issue: It's resetting at ~1s intervals.

(I honestly believe I checked this before by removing all connections, but since I did not note that in the question, perhaps I never did...)


difference between output pin high and 5v pin So this might be a total noob question (which admittedly I am) I have a Motor, if I connect it to GND and the 5V output it runs. Ok so far. But if I connect it to GND and a pin set to OUTPUT and HIGH nothing happens. My multimeter reads 5V for both setups, so if 5V come to the motor one way or the other why does one work and one not?

That's probably caused by the motor's current consumption. The 5V pin can deliver much more current than the output pin in high state. If you want to switch the motor on/off by software, you need a "hardware driver" for the motor, in the simplest case a power transistor.


Use Arduino Mega to program Arduino Duemilanove I hava an Arduino Duemilanove but I think that its FTDI chip is crashed.

I have an Arduino Mega too, so can I use it to program my Duemilanove?

Yes, this is not an uncommon activity.  This is called using an Arduino as an In-System Programmer (ISP)

This page has the information and Arduino program you need.  You'll need to adjust for the Arduino Mega pin differences, but that's fairly easy.
http://arduino.cc/en/Tutorial/ArduinoISP

Where the ArduinoISP page references pin 13, on the Mega it's pin 52.
Where the ArduinoISP page references pin 12, on the Mega it's pin 50.
Where the ArduinoISP page references pin 11, on the Mega it's pin 51.
Where the ArduinoISP page references pin 10, on the Mega it's pin 53.

Otherwise you should be able to connect the Mega to the patient in the same way as described, load the ArduinoISP sketch into the Mega, preferably from the GitHub repository linked in the article (https://github.com/rsbohn/arduinoisp).


serial.write() five sensors and Processing To all of this, hope to formulate the question right.

In my project I have 5 sensors connected to Arduino, which I want to interpret via Seria.write() --> Processing.

Arduino:

firstSens = 100 + (155 * digitalRead(8));
secondSens = analogRead(A1)/4;
thirdSens = analogRead(A2)/4;
fourthSens = humData;
fifthSens = tempData;
int sensData[6] = {firstSens, secondSens, thirdSens, fourthSens, fifthSens};

int i;
for (i = 0; i < 5; i = i + 1) {
  Serial.write(sensData[i]);
}

Processing:

serialInArray[serialCount] = inByte;
    serialCount++;

if (serialCount > 4 ) {
  firstSens = serialInArray[0];
  secondSens = serialInArray[1];
  thirdSens = serialInArray[2];
  fourthSens = serialInArray[3];
  fifthSens = serialInArray[4];

  // print the values (for debugging purposes only):
  println(firstSens + "\t" + secondSens + "\t" + thirdSens + "\t" + fourthSens + "\t" + fifthSens);

  // Send a capital A to request new sensor readings:
  myPort.write('A');
  // Reset serialCount:
  serialCount = 0;

My problem is that sensors find their place in Processing's array randomly, so for example arduino's firstSens could be Processing's secondSens or fifthSens

Why is this happening and how can I control it?

What is happening is you are just spewing out a list of numbers:

4132
132
1928
3240
1239
238
3048
391
... etc ...

There is nothing anywhere to say what anything is.

You need to add that kind of information. Either as a "start of data" tag before each block, or with each line.  For instance:

---START OF DATA---
4132
132
1928
3240
1239
---START OF DATA---
238
3048
391
... etc ...

Or:

0:4132
1:132
2:1928
3:3240
4:1239
0:238
1:3048
2:391

It is then up to your processing application to interpret the data and work out what is what.

Personally I like using the second method since it means you don't have to send all the data every time - you can send different values at different speeds of update and maintain a "current value" at the Processing end. For instance if you have one value that updates frequently and others that don't:

3:4132
1:132
3:1928
3:3240
3:1239
2:238
3:3048
0:391

You don't even have to use numbers, you could use words:

pressure:4132
temperature:132
pressure:1928
pressure:3240
pressure:1239
humidity:238
pressure:3048
rainfall:391


First Serial.print voltage is wrong, way too low. Ruins average calculation The first Serial.print voltage reading is so far off it really screws up the moving average calculation. For example, the first reading is like 0.00014981, which is wrong. From the second line on it prints the correct voltage, like 0.00475721. I don't know where this first line is coming from. How can I keep that first line from being used in the average calculation? Here are links to the sketch and adc.

https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf

For the average calculation I added:

count = count + 1;

volt_mV = ((count-1)/count)*volt_mV + (1/count)*volt_V;

The code at the link is mediocre – it has dozens of unnecessary casts or declarations, dozens of superfluous statements, and numerous unused or unnecessary variables.  Also, the code shown there has nothing about any averages, so evidently does not show whatever code you actually are running.  You could revise your question and include the actual sketch within it.

Nevertheless, the code at the link looks like it will take a reading ok.  Possibly your modifications, whatever they are, incorrectly initialize variables for the running average calculation, or incorrectly initialize some other variable not shown.  Or there may be some hardware glitch that spoils the first reading.

Several fixes are possible.  You could discard the first reading.   You could discard the first reading of each set of readings.  You could take readings in sets of three or five and only keep the median reading.  You could take sets of readings and discard the highest and lowest readings.  You could apply exponential smoothing or some other form of smoothing to the readings.

Note, the formula you show for averaging – ((count-1)/count)*volt_mV + (1/count)*volt_V – has a number of problems.  First, if count is an integer, both of ((count-1)/count) and (1/count) will compute to zero values.  Secondly, as count becomes large, you will be adding a tiny value to a much larger value, which is ill-conditioned arithmetic.  Third, although the formula computes a running average, it does not compute a moving average.  That is, your formula computes the average of all readings taken so far, with all readings equally weighted.  A moving average, on the other hand, typically will weight recent readings more heavily than old readings, for example via a window technique or via an exponential smoothing formula like movingAverage = (15*movingAverage + newReading)/16.


Do You Put a Break after the Last case in a Switch? The Arduino Switch Case Reference has a switch structure written two different ways:

First in the Syntax as:

switch (var) {
  case label1:
    // statements
    break;
  case label2:
    // statements
    break;
  default:
    // statements
}

and then in the Example code as:

  switch (var) {
    case 1:
      //do something when var equals 1
      break;
    case 2:
      //do something when var equals 2
      break;
    default:
      // if nothing else matches, do the default
      // default is optional
      break;
  }

Is there any reason to (or not to) add a break; in the default: case? Does the need for 'break;' change if the final case is not default:?

You can, but you don't have to.

Should you? That's up to you.

I do. That's because it's then simple to add another case at the end of the structure in the future if you want, and you don't have to remember to add the break to the existing last case.


pin going high not allowing analog read to change I have the following problem:

My arduino takes analogRead(A0) from a potentiometer whose position I can't adjust directly.

When analogRead(AO) goes to a value X,  I want pin 8 to go HIGH, this causes the circuit to open. and stop A0 getting higher . so I do an if statement:

if(analogRead(AO)> X) {

digitalWrite(pin, HIGH)  \\opens the circuit}

else {
digitalWrite(pin, LOW)  \close the circuit
 }

The issue I have here, is when then circuit is open,  I would like to change the value of the potentiometer (A0) which is controlled by a motor which is also in the circuit: but doesnt depend on the arduino board.  Given I can't control A(0) then the circuit will remain on A(0) >X forever.

The system going to LOW pin or close circuit, after it reaches HIGH pin for 2 seconds would be great, but then the program goes to the beginning and realizes that still A(0)> X , and goes back to a open circuit state, therefore not allowing me to have the close circuit anymore in order to make A(0) < X  and leave the circuit closed . Maybe something that cyclically turns pin on an off for t mseconds? but this is not ideal as it would cause high wear on the system

Edited the post to be more precise. I hope now its clearer
thanks

thank you for your answers, but after playing for a while with your codes, and the ideas behind it, still cannot get it to work.

for instance, Chrisl with your first:

when potentiometer is at > X, It cuts the circuit which is good, but still doesn't go off until both potentiometer goes to < X and 3 seconds lapse , but this is not going to be possible to achieve anyways    because the value of the potentiometer is fixed on X

THis is what Id need-

if (PinState == HIGH)

after 3 seconds go low,

and not turn HIGH until at least these two conditions are met; analogRead has gone to < X and then analogRead > X ,and in that moment we are back at
PinState HIGH
is  even possible to achieve something like this?

the circuit is something like this:

simulate this circuit – Schematic created using CircuitLab

UPDATE:
I have using this code, which does almost what I want:
         if(analogRead(A0) > X) {
      unsigned long currentMillis = millis();

if ((unsigned long)(currentMillis - previousMillis) >= interval) {

   pinState = !pinState;
   digitalWrite(pin, pinState)
   // save the "current" time
   previousMillis = millis();
}}

When it gets to analogRead(A0)> X the problem of this code is that it switches the pin On and OFF continuosly,

but instead of switching it off/on after the interval time , I want it to be LOW always. Of course as long as time  is more than interval,and not get to a HIGH, until It has gone back to  analogRead(A0)> X and time is less than interval. And repeat the process... When time is more than interval it will go from where it was digitalWrite(pin, HIGH) to the new state digitalWrite(pin, LOW)

I made this table to be more clear

Table: analogRead(A0) > X?

1-yes -->now check if time in this state is less than interval = 3000:

1.1-YES, ---> digitalWrite(pin, HIGH)
   1.2- if no ( time is more than interval ) --->  digitalWrite(pin, LOW)

2-  No, analogRead(A0) < X . So -->  keep  digitalWrite(pin, LOW)

NEW UPDATE:

The state diagram for the new ranges should be something like this. I hope it is clear. I also removed the delays and replaced  (V < X ) for (V < Y )  , it works great. Thank you Edgar.

Z in the diagram being the variable for the new range, Z << X

LAST UPDATE:

Question Solved by Edgar Bonet

The description you give for the desired behavior is very unclear and
hard to follow. I am going to rephrase what I think I understood in
terms of a finite state machine, which is the correct way of
describing this kind of systems. Please, review the description below,
as chances are I did not completely understand what you really want.

Let's say the system can be in any of these three states:

In the V_LOW state, the input voltage is below the threshold X and
the output is LOW. If the input raises above X, we set the output
to HIGH and transition to the V_HIGH state.
In the V_HIGH state, the input is above the threshold X and the
output is HIGH. If the input falls below X we go back to the
V_LOW state. If we remain in V_HIGH for three seconds, we switch
the output to LOW and go to the TIMEOUT state.
In the TIMEOUT state, the input is above the threshold, yet the
output is LOW. When the input falls below X we go to the V_LOW
state.

Below is a state graph for this machine. The states with a gray
background have the output LOW, whereas the state with a white
background has the output HIGH. Each possible transition is drawn as
an arrow, labeled by the condition that triggers the transition:

Is this the behavior you have in mind? If no, try to describe the
behavior you want in terms of a finite state machine, as I have done
here. If yes, then I suggest you follow chrisl's advice and implement
some hysteresis, by having different thresholds for going into and out
of V_LOW.

Anyhow, below is a translation of the FSM above in C++. It may not be
the most efficient way to write it, but I believe it is straightforward
enough to not require any additional explanation:

void update_output()
{
    static enum { V_LOW, V_HIGH, TIMEOUT } state;
    static uint32_t time_entered_v_high;
    int V = analogRead(A0);

    switch (state) {
    case V_LOW:
        if (V >= X) {
            digitalWrite(pin, HIGH);
            state = V_HIGH;
            time_entered_v_high = millis();
        }
        break;
    case V_HIGH:
        if (V < X) {
            digitalWrite(pin, LOW);
            state = V_LOW;
        } else if (millis() - time_entered_v_high >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V < X) {
            state = V_LOW;
        }
        break;
    }
}

Edit 1: Here is how to implement the hysteresis: you need to choose a
second, lower threshold, for going back to the state V_LOW. Let's call
it Y, which is smaller than X. Then, both on the diagram and the
code, replace every instance of “V < X” by “V < Y”. That's it. There is
absolutely nothing more to change.

Edit 2: Addressing the updated question. Now the output should go
HIGH when the input is out of a defined range. I'll add hysteresis
right away by using four thresholds
V0 < V1 < V2 < V3:

the input is in range if it is within
[V1, V2)
the input is out of range if it is not within
[V0, V3)
the ranges [V0, V1)
and [V2, V3) provide hysteresis.

Note that for consistency I like to have all the intervals closed on the
same side. I will also rename the states V_LOW and V_HIGH to
IN_RANGE and OUT_OF_RANGE respectively. Here is the updated code:

void update_output()
{
    static enum { IN_RANGE, OUT_OF_RANGE, TIMEOUT } state;
    static uint32_t time_exited_range;
    int V = analogRead(A0);

    switch (state) {
    case IN_RANGE:
        if (V < V0 || V >= V3) {
            digitalWrite(pin, HIGH);
            state = OUT_OF_RANGE;
            time_exited_range = millis();
        }
        break;
    case OUT_OF_RANGE:
        if (V >= V1 && V < V2) {
            digitalWrite(pin, LOW);
            state = IN_RANGE;
        } else if (millis() - time_exited_range >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V >= V1 && V < V2) {
            state = IN_RANGE;
        }
        break;
    }
}


Help with coding Arduino Nano to run fan through slide switch at specific intervals I’m trying to use Arduino Nano to run my 5 V PC fan, which, I know it sounds crazy, it’ll be mounted on a piece of Tupperware that’ll control the airflow through it via the fan. However I have no idea how to code the Arduino, but I do know how to code other things when I’ve done it in class. The setup is a 5 V rechargeable lithium ion portable battery connected to the switch which would be connected to the Arduino, and when the switch is triggered/flipped it would allow power to the Arduino, boot it up, and trigger the code that would tell the fan to run at specific intervals. The idea for intervals is a result of the battery only having 23 hrs and 10 minutes of continuous battery life while powering the fan. The pseudocode would look something like:

  Press bump switch, it turns on the Nano with the ensuing program. Twice an hour, the Nano starts the fan. The fan runs for 20 seconds to 30 seconds each time the fan is started. After a set of 48 on/off cycles have completed (24 hours), the Nano is set to sleep mode in order to save power. In order to restart cycles, user must press bump switch again.

I’m pretty sure I have the hardware side of things down but if I don’t please do inform me.

I’ve attached a picture of what it’ll approximately look like, with the battery at the left, switch in the middle, then the Arduino (not seen in picture), then the fan.

I know this is asking a lot when I don’t even know where to get started with the coding, but I’d be sincerely eternally grateful.

You can't run the fan directly from an Arduino pin. The fan will require to much current for that to work. Instead connect the fan, via a transistor/mosfet to the Arduino.

Also add a (flyback-)diode to the fan, as turning of the fan can create huge (but short) voltage spikes, which can damage the transistor/mosfet.

Pseudo code would be something like:

for( byte i=0; i<48; i++ )
{
  digitalWrite(fanPin, HIGH);
  delay(20000);
  digitalWrite(fanPin, LOW);
  delay(1780000);
}

You could also put the Arduino in sleep mode, during those half hours, as well. You could use the LowPowerSleep library. Then replace the delay(ms) with LowPower.sleep(ms).

Lastly, some powerbank will automatically shut down, if the detect nothing is using power. The Arduino, without the fan on, will use so little current (compared to charging a phone) that such a powerbank would shut of.


Trying to turn off fading RGB LED after 30 secs I am trying to get something to work so that an RGB LED fades through the color spectrum, and when a button is pressed some music plays.
That is not the problem.
Assume I am using any loop that functions can be called at any time in.
I am trying to make it so that if the button is not pressed for a certain amount of time, say 30 seconds, the light stops fading through the color spectrum and when the button is pressed in this 'sleep mode', first the light starts fading, and then the next press plays the music.
I am aware this could be done somehow with millis();, but how would I approach this?
I am using an Arduino Uno.

Here is a little snippet of logic that you can implement in your code :

if(millis() - getOutOfSleepTime >= 30000) {
    activateSleepMode();
    while(!buttonPress);
    getOutOfSleepMode();
    getOutOfSleepTime = millis();
}

if(buttonPress)
    activateSleepMode();


Multiple LED on arduino I am currently trying to control multiple LEDs with one Arduino Mega 2560 board. However, since each LED needs 3.6 volts and the board only supplies 5V I cannot make more than one light up.

Is there a way to increase to output voltage of the Arduino board ? Or perhaps of using arduino to turn on or off a battery that has a high enough voltage to power multiple LED ?

Thanks for your help

Each pin on any Arduino (with some exceptions) can only handle 40mA MAX. Even the 5V and similar output sources can't handle more than 600mA, So I suggest you use them to power a MOSFET or Darlington to connect them in appropriate series and parallel connection counts.

Both the above transistors can handle high voltage, but you need to choose ones that correspond to a voltage that an Arduino can provide.

This is the most robust method if you want all the LEDs to light up at the same time. However for array addressable LEDs you might need extra BJTs coupled with resistors for each led, maybe along with two decided that would be appropriate for your application.


XL335B accelerometer reports false readings I'm using an XL335B accelerometer in a GY-61 breakout board. I'm powering the device using the UNO's built-in 3.3V power supply. The following code should convert the readings to m/s² (SI); however, it returns (-0.43|-0.52|-5.83) instead of the expected (0|0|-9.81) when lying untouched.

Code:

const float CYCLE_LENGHT_MILLIS = 1000;

// REFERENCE_VOLTAGE 5 & STEP_COUNT 1024
// => VOLTAGE_STEP 0.0048828125
// MAX_ACC_VOLTAGE 3.3
// => MAX_ACC_VOLTAGE_STEP 675.84
// MIN_ACC_VOLTAGE 1.65 = 0.5 MAX_ACC_VOLTAGE
// => MIN_ACC_VOLTAGE_STEP 337.92
// MAX_ACC_MEASUREMENT 29.43 = 3g

// acceleration = (read()-MIN_ACC_VOLTAGE_STEP) * MAX_ACC_MEASUREMENT/(MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
//This can be simplified to: acceleration = read()*j - k
// => j = MAX_ACC_MEASUREMENT / (MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
// => k = MIN_ACC_VOLTAGE_STEP * j

const float j = 29.43/(675.84-337.92);
const float k = 337.92*j;

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

void loop(){
  Serial.print("(");
  Serial.print(analogRead(0) * j - k);  //X-AXIS
  Serial.print("|");
  Serial.print(analogRead(1) * j - k);  //Y-AXIS
  Serial.print("|");
  Serial.print(analogRead(2) * j - k);  //Z-AXIS
  Serial.println(")");
  delay(CYCLE_LENGHT_MILLIS);
}

You are assuming here that 3g will result in the maximum voltage of 3.3v. This is not correct. The datasheet says it's 0.3v/g so; 0g-voltage + 3 x 0.3v => 1.65 + 3*0.3 = 2.55volt.

To get the g value use (analogRead(0)-337.92)/61.44 (337.92 is the 0g voltage in steps; 61.44 is 0.3V is steps).

To get the acceleration is m/s² just multiply by 9.81; so (analogRead(0)-337.92)/61.44*9.81

Like you stated in the comments, the result isn't that accurate. Just have a look at the datasheet. e.g. Volt per G is typically 300, but can be anything from 270 to 330. Same thing goes for the 0g voltage; 1.35V to 1.65V. So quite a bit of difference can occur between one chip and the next. Even between the 3 axis inside one chip.

So the best thing is to calibrate all 3 axis. For the Z axis; just lay the sensor flat, and get the analogRead value (-1g value). Flip the sensor upside down and get the analogRead value (+1g value). Optionally place the sensor on it's side to get 0g value or just calculate the value in the middle of the above two value. The steps-per-g will be the difference between the two divided by 2 (+1g - -1g = 2g). Put this value and the 0g step-value into the formula. Repeat the procedure for the other 2 axis.


Remote controlled lights I have a fixed roof light in my room that came with a remote control that can be fully taken apart. The remote control can switch the lights on or off using a radio system. I was wondering if there was any way to use my Arduino to control the remote control (through wires) to control the lights. I do not have any Arduino radio components so it would still need to go through the original remote. I have taken the remote apart and this is what it looks like:

http://go.hma-uk.org/dlt

The buttons are as follows: the top two (K1 & K2) buttons is to turn on/off a coloured LED but these are not important to me. The button K3 is to turn on/off the main light (I want the effect of this button being pressed to be created using the Arduino) and the button K4 is to turn all lights on/off.

I used to use gamepads as input device for USB many years ago. I simply soldered wires paralel to buttons and shortcut them to "simulate" the button press - it worked nice and reliable.

With Arduino - I would measure the voltage on the button in question with Voltmeter - if the voltage is less then Vcc of Arduino (5Volts), I would simply connect Arduino ground to lower side (negative) of the button and output pin to the high side of the button. Then I would set that pin for Input to have the button released (from Arduino side) and to LOW + Output to have it pressed. (maybe I would first shortcut the button with Ampermeter to see, that no more, than 100mA is sinking there).

If the sink is more, or the voltage is more, then I would use relay and shortcut the button with the relay, switching the relay with Arduino.

( something like this http://www.instructables.com/id/Home-Automation-How-to-Add-Relays-to-Arduino/?ALLSTEPS )


How can BMP180 measure a temperature too? I got the following device

(sorry for imperfect focus)

and found, that it can measure not only pressure, but also a temperature too. The code was taken from common sketches for Adafruit BMP085 and they were working. I checked, that temperature value rises if I touch sensor with finger.

Simultaneously, on Bosch site for BMP180 I can't find any notes it can measure temperature, only pressure.

How can it be?

1) Bosch's BMP180 has undocumented feature to measure a temperature

2) The device on picture has additional component to measure temperature

3) The device on picture has completely different sensor, which has the name of "BMP180" just by coincidence.

4) Something else....

If you read the data sheet (on the site you point to) you see plenty of references to temperature:

  The BMP180 is designed to be connected directly to a microcontroller of a mobile device via the I 2 C
  bus. The pressure and temperature data has to be compensated by the calibration data of the
  E 2 PROM of the BMP180.

and

  The BMP180 consists of a piezo-resistive sensor, an analog to digital converter and a control unit with EEPROM and a serial I2C interface. The BMP180 delivers the uncompensated value of pressure and temperature. The E 2 PROM has stored 176 bit of individual calibration data. This is used to
  compensate offset, temperature dependence and other parameters of the sensor.

And many many more.


How do I add additional compiler switches in Visual Studio Using Visual Studio to program my Arduino. I want to add additional compiler switches and include paths.

How can this be done?

Use the ExtraFlags in the project properties. The flags can be specified for the currently selected configuration or for all builds of the current project.

The feature was released in the 15.06 version of the Visual Micro Arduino plugin for Visual Studio.

This guide shows how to access the project properties


How to move from arduino to physical prototype I've been reading a bit about moving from Arduino to PCB and it seems a bit daunting. For now, all I really want to do is take something I've built, and make a few changes so that I can actually create a casing for it and make sure everything stays connected.

I've attached a photo of my project. What I am trying to do is create a box, where 4 pushbuttons sit in a box, with LEDs next to them. I will probably create foamboard cutouts for the spaces where the pushbuttons and leds sit. The wiring for the push buttons and the LEDs need to be hidden below the foam board, along with the arduino itself and the servo motor - which is where I get stuck.

What do I need to do to essentially "lengthen" the wires for the pushbuttons and LEDs, and make sure all the components stay secure in the breadboard (the push buttons in particular like to pop out)? Is there a way to do this without making a PCB? I understand the concept of soldering components into protoboard, but as far as cutting / printing the circuits or whatever, it is really confusing to me.

I'd appreciate any guidance. If you see anything wrong with my wiring setup too, I'd love a learning experience on that as well. Thanks!

The best thing to do is, of course, to use a PCB. But it doesn't need to be a custom PCB; there are plenty of pre-made PCBs that are usable for approximately 98% of designs. Here are just a few:

Adafruit Perma-Proto boards are connected just like breadboards, so direct transfer is possible.
BusBoard proto boards come in a ridiculous variety of configurations, including enclosure kits, and they even have SMD boards if you're up to it.

For switches just use a panel mount form. They come in everything from simple to robust to ridiculous.

LEDs can also be panel mount, or you can use a light pipe to make a LED on the PCB visible from the outside.

For power you can use a USB connection or a separate power jack with a voltage regulator. If you also need a serial connection then you should consider a pre-made serial module, and either use its built-in USB jack or a separate panel mount USB jack.

The servo can be mounted inside the case if appropriate, or can be connected to a PCB mount or panel mount connector instead.

Naturally the MCU itself should also be placed in a socket directly on the PCB. Don't forget the decoupling, the oscillator, and the ISP connector.

As for the circuit itself, you can get rid of the pullup resistors on the switches if you use internal pullups instead. And 100ohm is way too low a value for switch pullups regardless.


Need Help to implement MODBUS TCP Master over Atmega32 MCU I am doing a project where I have to interface with Fronius Solar Inverter with Atmega32 MCU over MODBUS TCP. I want to set the MCU as client and The inverter as Server and I have to implement two MODBUS Function only these are READ_HOLDING_REGISTER and WRITE_SIGLE_REGISTER and Function Code are 0x03 and 0x06 respectively.  I am newbie in this field and dont know about networking. Please anybody help me How can I develop the Software in C for this purpose??

The Document of Fronius Inverter for MODBUS TCP is Fronius MODBUS TCP Datamanger

So if you want to the atmega as client this means it will start the conection and made the request for values, so translating into modbus words your atmega will be a modbus master and the solar will be a modbus slave.

first you need a way to interface the micocontroller to the tcp/ip stack. you can use an ic or arduino shield which has this ic like a w5100 or enc28j60.

then you can write a library over tcp sockets to start the comunication or change some from the arduino.

https://www.google.com.br/url?sa=t&source=web&rct=j&url=http://myarduinoprojects.com/modbus.html&ved=0ahUKEwj9zMvjiYDTAhXJkpAKHfsNBz0QFggpMAE&usg=AFQjCNEfRhDgPGJNK-IUqrUw1FXEnBcxwQ&sig2=Xs0JNEWi_F_XiPgkTQdy-w


Arduino Yun RFID-RC522 module not working I have tried to use Arduino Uno with RFID-RC522 module. It is good work[1] and read rfid cards. But Arduino Yun doesn't work with RFID-RC522 module.

What is diffrent Uno and Yun?

1- http://www.grantgibson.co.uk/2012/04/how-to-get-started-with-the-mifare-mf522-an-and-arduino/

According to the link you provided, we can see that the RFID-RC522 uses SPI to communicate with Arduino.

On Arduino UNO, the SPI pins are located as follows:

pin 11: MOSI,
pin 12: MISO,
pin 13: SCK

On the Arduino YUN, this is different though; as stated there (bold highlight is mine):

  SPI: on the ICSP header. These pins support SPI communication using
  the SPI library. Note that the SPI pins are not connected to any of
  the digital I/O pins as they are on the Uno, They are only available
  on the ICSP connector. This means that if you have a shield that uses
  SPI, but does NOT have a 6-pin ICSP connector that connects to the
  Yún's 6-pin ICSP header, the shield will not work.

Hence you can not wire the RFID-RC522 module the same on UNO and Yun.
For the Yun, you'll have to follow this wiring picture:

Pin 1 in image above is the pin that is marked with a dot on the Yun PCB.

Also see the ISP-header layout, at the lower-right corner of the yun_by_pighi Yun pinout diagram.


How to get a button state change within a for loop? I have a for loop inside my void loop() that triggers a piezo.

What I want to happen is when I press a button, it breaks the loop of the piezo, but right now, it's as if it isn't detecting the button press inside my for loop.

Here's my code:

#include <Adafruit_NeoPixel.h>

#define PIN 6
#define TONE 8
const int buttonPin = 2;

long fadeTime = 5 * 1000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int switchState = 0;         // variable for reading the pushbutton status

Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, PIN, NEO_RGB);

void setup() {
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input

  strip.begin();
  strip.show();
}

void loop() {
  // read the state of the pushbutton value:
  switchState = digitalRead(buttonPin);

  // Fade in light
  for(int i = 1; i<colorStops; i++){
    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(i,i,0));
    }
    strip.show();
    delay(delaySpeed);
  }

  // Play tone after light fully bright
  for(int i = 1; i<100; i++){
    // Turn off tone on button press
    if (switchState == HIGH) {
      noTone(TONE);
      break;
    }
    tone(TONE, notes[random(0,3)]);
    delay(100);
  }
}

Does switchState = digitalRead(buttonPin); only get called at the start of the void loop and so it can't detect the button change until then? Something else?

Also, in case it's useful, here's my hardware set up...

You aren't reading the state of the button within your loop.

You only read it the once at the top of your loop():

void loop() {
  // read the state of the pushbutton value:
  switchState = digitalRead(buttonPin);

You need to replicate that every time you want a new reading from the button - so in your loop you need to add that digitalRead line:

// Play tone after light fully bright
for(int i = 1; i<100; i++){
  // Turn off tone on button press
  switchState = digitalRead(buttonPin);
  if (switchState == HIGH) {
    noTone(TONE);
    break;
  }
  tone(TONE, notes[random(0,3)]);
  delay(100);
}

Or you can do away with the variable altogether and just test the return value of the digitalRead:

// Play tone after light fully bright
for(int i = 1; i<100; i++){
  // Turn off tone on button press
  if (digitalRead(buttonPin) == HIGH) {
    noTone(TONE);
    break;
  }
  tone(TONE, notes[random(0,3)]);
  delay(100);
}


Include Git tag (or SVN revision) in Arduino sketch? Is there any way to get the current Git tag/commit identifier into an Arduino sketch binary?

For normal desktop program development, you can pull some tricks with the Makefile (as pointed out in this StackExchange answer). However, there is no Makefile for an Arduino sketch. Right?

I could make a batch file that I run before every compile, but there is the very real possibility I will forget to run it, and incorrect version information is worse than no version information.

At the moment, I am using the preprocessor macros __DATE__ and __TIME__ to try and identify what version is running on the board. This works, but tracking backwards from a compile date/time to a source control commit is more guesswork than anything.

I struggled with Arduino (ESP32) versioning also.
To make it somewhat more practical and less error prone I made some scripts to assist this process.

Using these scripts is as easy as adding them to your sketch folder and adding

#include "gitTagVersion.h"
...
Serial.println( sketchVersion );

to your Arduino sketch.
That is all that is needed.

The output in the example above will be something like v1.0.0-3-gab3fb04.
That breaks down to tag v1.0.0, we had 3 commits since that tag, at commit ab3fb04.

HOW TO INSTALL AND USE?

There are 2 scripts involved, the first script is a replacement for the Arduino  Verify button.
Save it as verify.sh:

echo "const char * sketchVersion = \"$(git describe --tags --always --dirty)\";" > gitTagVersion.h
~/arduino-1.8.5/arduino --verify test.ino
rm gitTagVersion.h

And the second script replaces the Upload button.
Save it as upload.sh:

echo "const char * sketchVersion = \"$(git describe --tags --always --dirty)\";" > gitTagVersion.h
~/arduino-1.8.5/arduino --upload test.ino --pref custom_DebugLevel=esp32_none
rm gitTagVersion.h

Some things to note about these scripts:

The scripts REPLACE the buttons.
You won’t be able to use the buttons anymore, as these buttons don’t
generate the necessary version info from git.

Using them will result in this error:

  fatal error: gitTagVersion.h:    No such file or directory

The scripts are hardcoded to use Arduino 1.8.5 and have to be updated
if you update your Arduino IDE.
These script only work in Linux with a vanilla Arduino install.
If you use Windows, or are on a Mac the scripts will not work.
To change the debug output (using the LOGx_ESP macros) on ESP32
builds, change the custom_DebugLevel in the Upload script to
esp32_xxxx, where xxxx is none, info, error, debug or verbose.

I posted this also on my blog and esp32.com


Delay stops execution forever sometimes I have an arduino to control an irrigation system, consisting on one pump (called "bomba" on the code) and 5 12V water valves.

Each valve controls one irrigation circuit and the idea is to open each one sequentially during one minute and then move on to the next one.

The code is this:

const int TIEMPO_RIEGO = 64; // seconds

const int TRIGGER = 5;

const int BOMBA = 6;
const int CIRCUITO_1 = 8;
const int CIRCUITO_2 = 9;
const int CIRCUITO_3 = 10;
const int CIRCUITO_4 = 11;
const int CIRCUITO_5 = 12;

const int CIRCUITOS_ACTIVOS[] = {
  CIRCUITO_1,
  CIRCUITO_2,
  CIRCUITO_3,
  CIRCUITO_4,
  CIRCUITO_5,
};

void _abrirValvula(int circuito, int t) {
    digitalWrite(circuito, HIGH);
    digitalWrite(BOMBA, HIGH);
    unsigned long waitTime = t * 1000L;
    delay(waitTime);
    digitalWrite(BOMBA, LOW);
    digitalWrite(circuito, LOW);
}

void cicloRiegoCompleto() {
  int numeroDeCircuitos = sizeof(CIRCUITOS_ACTIVOS) / sizeof(CIRCUITOS_ACTIVOS[0]);
  for (int i=0; i<numeroDeCircuitos; i++){
    _abrirValvula(CIRCUITOS_ACTIVOS[i], TIEMPO_RIEGO);
  }
}

void setup() {
  pinMode(BOMBA, OUTPUT);
  pinMode(CIRCUITO_1, OUTPUT);
  pinMode(CIRCUITO_2, OUTPUT);
  pinMode(CIRCUITO_3, OUTPUT);
  pinMode(CIRCUITO_4, OUTPUT);
  pinMode(CIRCUITO_5, OUTPUT);
  pinMode(TRIGGER, INPUT);
}

void loop() {
  if (digitalRead(TRIGGER) == HIGH) {
   cicloRiegoCompleto();
  }
}

On the pin 5 (TRIGGER) I have a raspberry pi connected that is connected to the internet also, so, when I send it a message from mi phone, it puts 3.3V on that pin and starts the process.

It has been working great for like a month or so but, a few days ago, the pump didn't stop when it should, and was still working hours after it started.

I pull the plug and, when I turn it on again, it worked correctly again for another 2 or 3 days.

But today it hasn't stop again. I have check that the pump has been working for around 15 minutes until I pulled the plug, and the first valve (CIRCUITO_1) has been opened the whole time, looks like the for loop is stuck in the first iteration.

So can it be some problem with the delay function?

For some reason it is waiting way more than it should?

It works sometimes and sometimes it doesn't so it makes me think: can it be some weird overflow issue?

Based on your experience with the system and the source of the Nanos, the best and quickest test I can think of is to swap in a another Nano to find out whether if the problem remains or disappears.


Do ultrasonic sensors sense through transparent materials? Do ultrasonic sensors sense through transparent materials?

In my case, I have to read if there's something inside a transparent acrylic bottle.

I'm assuming you mean a "normal" sensor, like this:

Ultrasonic sensors work by sending out sound waves. Obviously, sound waves don't care whether a material is transparent or opaque, so they are blocked just as easily by acrylic as by a brick wall.

Side note: If you look on the front of an ultrasonic sensor, you will notice that it is covered by a screen, not glass or plastic. This is why.


Adafruit Music Maker Shield - Retrieve song names from SD Card I am currently working on a project that plays music for you. My question for this thread is, is it possible to retrieve the names of the songs within the micro SD card that is inserted into the shield?

Currently I am renaming the song files to track001, track002, track003, etc. As can be seen in the following code:

const int arraySize = 5;
char songs[arraySize][15] =
{
  {"track001.mp3"},
  {"track002.mp3"},
  {"track003.mp3"},
  {"track004.mp3"},
  {"track005.mp3"}
};

That is how am I currently playing music with this shield. I am not too happy with this as I would like to be able to insert different micro SD cards into the shield without having to rename them to track00X or without having to change the code every time to match the song names.

So, is it possible to code it to retrieve the song names from the SD card instead of having to specify their name in the code?

Below you can see my full code:

#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)

#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

#define CARDCS 4     // Card chip select pin
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

int volume = 20;
const int arraySize = 5;
char songs[arraySize][15] =
{
  {"track001.mp3"},
  {"track002.mp3"},
  {"track003.mp3"},
  {"track004.mp3"},
  {"track005.mp3"}
};

int songNumber = 0;

void setup()
{
  Serial.begin(9600);
  musicPlayer.begin();
  SD.begin(CARDCS);
  musicPlayer.setVolume(volume, volume);
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);
}

void loop()
{
  // Lower Volume
  if (musicPlayer.GPIO_digitalRead(7) == HIGH)
  {
    if (volume < 70)
    {
      volume = volume + 1;
      musicPlayer.setVolume(volume, volume);
      delay(50);
    }
  }

  // Increase Volume
  if (musicPlayer.GPIO_digitalRead(6) == HIGH)
  {
    if (volume > 0)
    {
      volume = volume - 1;
      musicPlayer.setVolume(volume, volume);
      delay(50);
    }
  }

  // Start Music Player
  if (musicPlayer.GPIO_digitalRead(5) == HIGH)
  {
    if (! musicPlayer.playingMusic)
    {
      musicPlayer.startPlayingFile(songs[songNumber]);
    }
  }

  // Pause / Resume
  if (musicPlayer.GPIO_digitalRead(4) == HIGH)
  {
    if (! musicPlayer.paused())
    {
      musicPlayer.pausePlaying(true);
    }
    else
    {
      musicPlayer.pausePlaying(false);
    }
    delay(500);
  }

  // Prev Song
  if (musicPlayer.GPIO_digitalRead(3) == HIGH)
  {
    if (songNumber - 1 >= 0)
    {
      songNumber = songNumber - 1;
    }
    else
    {
      songNumber = arraySize - 1;
    }
    Serial.println(songNumber);
    musicPlayer.startPlayingFile(songs[songNumber]);

    delay(500);
  }

  // Next Song
  if (musicPlayer.GPIO_digitalRead(2) == HIGH)
  {
    if (songNumber + 1 < arraySize)
    {
      songNumber = songNumber + 1;
    }
    else
    {
      songNumber = 0;
    }
    Serial.println(songNumber);
    musicPlayer.startPlayingFile(songs[songNumber]);
    delay(500);
  }
}

If this is possible and someone reading this knows how to do so, I would truly appreciate it if you explained it to me and even provided an example or even edit my own code if you want. Thank you! :)

The adafruit library was is similar to the prior SFEMP3shield library (disclosure I am the main author of that). That said either library can work on either Adafruit or SFE shield or breakout board. AdaFruit's library is cleaner re-write. But in doing so it is minimal in its functions. The SFE library demonstrates many more features of the VS1053 chip.

That said; the ./Example/fileplayer.ino does exactly what you are asking. The directory command lists out the files with an enumerating number. Entering 0[number] plays that file. This is how I broke away from "track###.mp3", without having to implement a command prompt parser. And it also allows other file formats.

The bulk of this feature is in the LOOP() and not in the constrained to the library. So one can cut and paste it into a sketch using the Adafruit library in place of the SFEMP3 or any sketch with an SdCard. That said it would actually be easier to replace the play file calls and include in the FilePlayer.ino example. Or just use it straight up.

The SFEmp3 library is bit overwhelming because it supports so many features of the VS1053. And uses a different SdCard library, which is more upto date than the IDE's SD". While the Adafruit library is a very nice re-write and cleans much hte confusing #define's making it much easier code to read, it is not as feature rich. But most feature beyond play and stop are not really needed.

Good luck.


Powering an Arduino Uno using 2 (or as few as possible) AAA batteries [Background] I'm constructing a water bottle rocket which is going to use apogee detection and a mechanism for the parachute release.

Connected to the Uno will be an accelerometer and a servo, now due to the need to minimise the dry mass of the rocket I want to use as few and as light batteries as feasible. Would it be possible to power this setup with 2 AAAs? If not how many would be necessary? Would other types of Arduino such as a micro work on fewer batteries?

Thanks for the help

I've got a page about power saving.

My first suggestion would be to not use a Uno, which is quite heavy (because of its size) but a smaller Arduino like a Mini. Second, I think you'll find that LiPo batteries are quite light, and come in various sizes (and thus, weights). A single cell will output around 3.7V which is fine for driving an Atmega328P. Possibly you could drop the clock to 8 MHz because of the voltage.

If you don't need it to be "awake" all the time consider using the techniques described in my link above to make it sleep for (say) 4 seconds at a time and then take a measurement.


How do i send data from a Master to another Master? I am using an ESP32 to receive data from web.
However in an I2C communication, the EPS32 does not work as a Slave and i already have an Atmega as the Master.

i have seen sites saying Master-Master I2C Connection is possible however, how do i do this? or are there other solutions to have the ESP32 communicate to the ATMega?

Both your master devices must support Multimaster mode, i.e. Arbitration and Synchronization. See I2C Spec here for a description of the arbitration process.
It's up to you to handle a lost arbitration in your software.

  or are there other solutions to have the ESP32 communicate to the
  ATMega?

Of course. As you considered I2C to be sufficient, UART and SPI are feasible alternatives supported by almost all microcontrollers.


Sounds like your pots are not connected correctly and you pick up noise. The waveform you are seeing could be from the mains, or another source. Stray magnetic fields from transformers etc. can couple and be picked up by your circuit and you will notice them if your input is of high impedance. The atmosphere is also full of electromagnetic radiation from human sources and from space, that you can also pick up. The longer wires that are connected to your high impedance input, the more noise you will pick up.

Your pots should be wired 1.2V-AIN-GND, with the 1.2V source being low impedance, coming from a power supply/regulator and not eg. a voltage divider. If your potentiometer is high impedance (say 100 kOhm), and it is connected with wires from eg. a breadboard, you might want to add a decoupling capacitor between AIN and GND. 0.1 uF would be a typical value. It will short out AC waveforms(noise) to ground.


loop() either stops working, or lcd stops working | buttons don't work I'm using a Let's Start Coding Ultimate Kit 1 (it was a christmas present, don't ask) and I'm trying to use this as a typing sort of thing. I haven't implemented the actual letters though.

#include <MakerScreenXVI.h>;

MakerScreenXVI lcd;

int currentNumber = 1;
int ms = 0;
int totalMS = 0;
bool first = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, INPUT);
  pinMode(A3, INPUT);

  lcd.begin();
  lcd.print("Success");
  lcd.setCursor(0,1);
  lcd.print(currentNumber);

}

void loop() {
  delay(200);
  changeNumber();
  delay(200);
}

void clearLCDLine(int line) {
        lcd.setCursor(0,line);
        for(int n = 0; n < 16; n++) // 20 indicates symbols in line. For 2x16 LCD write - 16
        {
                lcd.print(" ");
        }
}

void changeNumber() {
  if (digitalRead(A0) == LOW) {
    if (first == false) {
      clearLCDLine(1);
      first = true;
    } else {
      first = false;
    }
    currentNumber++;
    if (currentNumber == 27) {currentNumber = 1;}

    lcd.print(currentNumber);
  } else if (digitalRead(A3) == LOW) {
    currentNumber = currentNumber - 1;
    if (currentNumber == 0) {currentNumber = 26;}
    //clearLCDLine(1);
    lcd.print(currentNumber);
  }
}

For some reason, after it deletes the 1, it stops. Nothing is printed onto the screen, and nothing is cleared from it. How can I fix this?
Also, the buttons always return the LOW value. How can I fix this?

The buttons will send a LOW signal when pressed if they are set with pinMode INPUT_PULLUP.

The issue with currentNumber not displaying is that after you clear the screen with the 'for' loop, you need to reset the cursor to position 0,1 with lcd.setCursor(0,1); . Otherwise, the numbers are printing out of view.

If I add lcd.setCursor(0,1); just above each line with lcd.print(currentNumber); , I think the code has the behavior you're looking for.

Edit from the person who asked the question:
 You also have to add a delay of around 150-200, or else one push will count as many.


How do you remove dependencies from a library? I'm writing a library for a project i created, but it depends on the Neopixel library from adafruit. I want to remove this dependency and have my library be a stand-alone library.

Is there a way to run a ws2811 chip without the neopixel or similar library?

The Adafruit Neopixel library is licensed under GPL v3. You can fork a copy of this library into your own code and modify it to suit your own requirements, but if you distribute your code, your compiled project, or a product containing the library or any portion of it, you must ensure you follow the rules of the license by which the library is governed. Those terms of license may include release of the source code if you use any portion of the licensed library in a product. Opinions differ on the exact meaning of GPL v3 with libraries.

You should be able to copy the library into your own codebase and strip out the color-specific routines, put in your own application-specific data-setting routines, but use the same underlying protocol implementation.


Serial data showing up weird I have a simple sketch that prints out "Hello World" to the serial, but I'm getting a bunch of gibberish instead.

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

void loop() {
    Serial.println("Hello World");
    delay(1000);
}

Why isn't it printing "Hello World" like the code says?

The board and terminal are probably not using the same baud rate. Check the bottom right corner of the Arduino Serial Terminal and make sure it is set to 9600.

Serial Data

Serial communication works by sending the entire data stream one bit at a time. This is in contrast to the standard parallel port which sends one byte at a time. Both devices need to know at what speed the data is being sent. Furthermore, both devices need to be operating at the same speed. This is called the baud rate.

Baud Rate

Baud really just means pulses per second. In the context of serial communication, it means how many bits are transmitted per second. One of the most common values is 9600, but there are other common ones which are factors or multiples of 9600. It doesn't really matter, though, as long as both devices operate at the same speed.

If I'm sending you messages faster than you are getting them, you lose data. If I am sending you messages slower than you are receiving them, you get nonsense mixed in with what I sent you.

Data, Parity, Stop bits

If you look at the documentation for begin(), you'll see it can take two parameters:

Serial.begin(speed)
Serial.begin(speed, config)

Hopefully you understand speed now, it is the bits per second at which the Arduino will communicate.

The second parameter, config, lets you configure some other things about the serial data transmission. These are the Data, Parity, and Stop bits. You'll see on the page it has values like 5N1, 6N1 and SERIAL_8N1 (the default)

The first number represents how many data bits. The second character tells you what kind of parity bit there is. E for even parity, O for odd parity, or N for no parity. The third number tells you how many stop bits.

So really, with 8N1, we have 10 bits being sent for each 8 bits of "your" data. 1 start bit, 8 data bits, and 1 stop bit.

Anyway, both sides need to agree on this information as well as the speed. The Arduino Serial Terminal doesn't give you the option of changing these settings, but others do, so you'll need to be sure all of these configuration settings are the same.

More info on wiki: Asynchronous serial communication


How to upload already compiled code when no changes were made? How do I use the Arduino IDE to upload the last compiled code? I don't want to have to wait 2 minutes to upload compiled code when there are no changes. It's a big codebase where I frequently make one or two small changes and have some issue with my MCU or USB cables. Frequently the controller on my boards are damaged due to some overcurrent issue because of the high-heat nature of 3d printing. So having to wait an extra 2-5 minutes every time I experiment with this unacceptable.

Obviously, there is a keyboard shortcut to do this that I'm unaware of. Because otherwise this would add hours to development.

Please tell me how I can get Arduino-IDE to just 'upload without compiling' my sketch.

You can upload hex file to your board from command line without Arduino IDE.

To get the hex file, use in Arduino IDE in menu the command "Export compiled binary". It will save the hex file next to the ino file.

I assume your board in printer has AVR MCU. Then you can use avrdude from command line to upload the hex file again and again without any compilation.

The avrdude command on Windows is (if started from the sketch's folder):

%LOCALAPPDATA%\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -C%LOCALAPPDATA%\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -PCOM11 -b115200 -D -Uflash:w:Blink.ino.hex:i

The command line is for the Blink sketch and for AVC boards package 1.6.21


Adapt a differently pin-interspaced chip to be used with an Arduino Happy new year to everyone!

This is how my chip looks like:

Those numbers are millimeters. Both the pin spacing and pin width are different from what Arduino uses.

Is there any quick (or less quick) and reliable way to connect this chip to an Arduino Uno ?

Adapters from 2mm to 2.54mm (0.1") spacing exist.

Here is
an example and another example.

Alternatively you could make up a little PCB or, as suggested by @jfpoilpret, solder wires on.

A further option is to cut a piece of stripboard, score down the middle to break the tracks, stick your chip on, and run wires from the 2mm-spaced pins to the 2.54mm-spaced pins.  Off-cut resistor legs work fairly well, in my experience.  Here's one I made (fairly clumsily) earlier.  Your soldering skill may be better than mine. .


How to extract code on one DT-06 board to another board? I have two DT-06 boards DT06 datasheet.

The board stock firmware provides Web UI for wifi/network/serial setup. I've replaced the firmware on one board with other sketch; but now I want to revert it to the stock firmware. I cannot find the stock firmware source code anywhere. The DT-06 manufacturer also won't give it out.
Is it possible to extract the stock firmware from another DT-06 board and put it back into the other DT-06 board?
Thank you.

Okay. I found a way to extract the binary file (stock firmware) from one DT-06 and flash it to another modified DT-06, by using esptool command
/*To extract firmware */:
esptool.py -p COM4 -b 460800 read_flash 0 0x400000 dt06_backup.bin
/*To flash the backup binary file to another DT-06 */
esptool.py -p com4 write_flash -fm dout 0x00000 dt06_backup.bin


Avoiding float math to speed up arduino I read and heard that the floating point math is much slower than int math.

And I saw a converting process in here floath math to integer math

So I want to to convert my floating math calculations to integer math.

Here is the code that include floating math:

float sensval, lpf, lps;
float sensinitial; // used to store the initial sensor data
float x, y, z;
int heigh;
int dA;

void setup() {

  runSensor();
  sensval = readSensorData();
  sensinitial = sensval; // Setting the initial data
  lpf = lps = sensval;
}

void loop() {
  sensval =  readSensorData();
  heigh = (float)44330 * (1 - pow(((float) sensval/sensinitial), 0.190295));
  lpf = lpf + (sensval - lpf) * 0.1;
  lps = lps+ (sensval - lps) * 0.05;
  x = (lps - lpf) * 50;
  y = x+ (z - y) * 0.1;
  z = constrain(y, -500, 500);
  dA += z * 100 + 2000;
}

readSensorData(); returns 7 decimals maximum(752.4543 for example)

There is pow calculation too.

So how can I convert floath math to int math?

Any optimization code are welcome.

What you are asking for is not simple, especially since you have this
power function that can be hard to approximate.

First, you have to figure out the range and the required precision of
each of the floating point numbers you are manipulating. You wrote that
readSensorData() returns 7 decimals. If by that you mean that you
require a relative accuracy of 10−7, then I predict it will
be extremely hard to optimize this as a fixed point calculation. If
you can live with a much lower relative accuracy (say, around
10−3 or 10−4), then it may be worth trying
something.

I would start by writing the expression of height as

height = f(sensval/sensinitial-1)

where

f(x) = 44330 * (1 - pow(1+x, 0.190295))

I would expect sensval and sensinitial to be close to one another,
which would imply that x is small. At this point you should try to
estimate the likely range for x, because the feasibility of what
follows strongly depends on it. Next step is to approximate f() by a
polynomial. A simple Taylor
expansion gives:

f(x) ≈ -x*(8435.78-x*(3415.25-x*2060.2))

You may start by trying this, just to see if it looks kind of OK or
completely hopeless. You will notice that the above approximation is
great when |x| is tiny, but it very quickly degrades as |x|
increases. This is why you don't use Taylor expansions in real
approximations, I showed it to you only to give you an idea of the
feasibility of a polynomial approximation.

To do better than Taylor, you must specify the range of x, then you
can scale that range to [−1, 1] and expand on the basis of the
Chebyshev
polynomials. And
then you could fine-tune to get the optimal
polynomial, but
it's likely to be only marginally better than the Chebyshev expansion.

If all this works with a reasonable polynomial degree (say, no more than
5), then you can start converting to integer math. If it doesn't, you
may try a different type of approximation, like interpolating over
tabulated values. If the problem is the range of x being too large,
you may instead write the power function as

ab = 2b × log2a

and write polynomial approximations to the base-2 exponential and
logarithm (the polynomials only needs to cover one octave). If you try a
rational fraction approximation, beware that divisions are slow on the
AVR platform.

If all the above looks like too complex, or too much work, then just get
a faster CPU, or try to live with your program being slow.


CS5211AGP wireless RF transmitter (433MHZ) address decoding problem I am using CS5211AGP wireless RF transmitter to transmit some data and another side receive this data through nRf905 as receiver. But now problem is how can I decode RF transmitter address (because transmitter and receiver address must be same).

if any one working on this module then please suggest me how can I decode address.

Please show below image where you can see the connection of address and zone.

Now please say about what address should I set at receiver side for communication.

Thanks in advance.

Regards,
rajneesh

I am looking at mine, wich address is 01212012, acording to a sticker in a side. I can see in mine jumpers as follows (starting from A0): -HLHL-HL-H-H where - means no jumper. Based on my sticker I can see that 0 is equivalent to NO-JUMPER, 1 is H and 2 is L. By watching yours I can tell that your code is 21111002.
The other 4 jumpers is what I don-t understand, but if I change any of them, my alarm no longer detects any change.
Hope this helps...
Regards.


Why do I get "invalid operands of types 'const char*'" error? I am making an Arduino alarm. This is the error:

exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Here is the code that triggers it:

lcd.print("0"+hours+":"+minutes);

This code is similar, but worked before:

String none="00";
lcd.print(none+":"+none+":"+minutes);

I can post the full code if you need it. How can this be fixed?

Your first code took a String object, then added other strings (note lowercase) to it - which are characters enclosed in quotes. It is legal to add strings to String objects.

Your new code doesn't have any String objects at all - and you're not allowed to add strings to strings (both lowercase).

It will work if you change your new code to:

lcd.print(String("0")+hours+":"+minutes);

That turns the original string "0" into a String object, and then adds more strings to it.


Debugger for Code::Blocks + Arduino I am not very experienced in this, but I was wondering if Code::Blocks has a way of getting a debugger that runs for Arduino chips, specifically. I understand there is Arduino IDE for but does it allow debugging specific to those microcontrollers (Amtel and such)?

Answer: Code blocks does not currently have an Arduino debugger. The Arduino IDE does not have a debugger.

There is an Arduino debugger in Atmel Studio using the Visual Micro plugin.

That said, you have to use Ms Windows to use Atmel Studio which might not be available to you.

The Visual Micro debugger is simple and uses usb so does not require additional hardware but as your experience grows you might also like to progress to fully blown hardware debug using the native Atmel Studio Tools

Visual Micro debug in Atmel Studio

Atmel Studio Download


Unable to create a desired periodic signal with Arduino Mega 2560 and DAC0808 I wrote the code to produce the periodic signal by using arduino and DAC0808 where i turned on and off the respectively pins of PORTA by using a logic in iterative manner and created the periodic signal. But even without using delay logic, i couldn't get signal time period as comparable to 50 Hz voltage signal. And what i seek to get is to decrease the time period of generated signal. Pls note, blue signal is reference signal of 50Hz frequency.

float increment = 3.14159 / 500;
float initial = 0;
float value = 0;

void setup() {
  Serial.begin(115200);
  DDRA  = B11111111;
}

void loop() {
  // put your main code here, to run repeatedly:

  PORTA = B00000000;
  while (1)
  {
    initial = initial + increment;
    value = sin(initial)  * 255;
    PORTA = abs(value);
  }

}

I'm interpreting your phrase “even without using delay logic, i couldn't get signal time period as comparable to 50 Hz” as meaning that the code shown runs Too Slow.  At 1000 samples per cycle and 50 Hz on an 8-bit 16-MHz processor, you only have 320 clocks to compute a sin(), which probably is not enough to compute a 32-bit floating sin().

To speed it up, you can either issue fewer samples per cycle or make the loop go faster.

For the “fewer samples per cycle” approach, you would make increment bigger; for example, instead of 3.14159/500, or 1000 samples per cycle, perhaps an interval of 2π/500, or 500 samples per cycle.

For the “make the loop go faster” approach, you could use a lookup table or fixed-point integer arithmetic or both.  Note, the lookup table only needs to cover 90° (or π/2 radians); index in reverse for quadrants 2 and 4, and negate values for quadrants 3 and 4.

Note, after you speed up the code, you will need to set up a time base for issuing samples.  This could use a clock-based interrupt routine that gets and issues the next array value, or that sets a flag so your main loop can get and issue a value.  Or you could spin until micros() exceeds a deadline, at which time you (1) issue a value, (2) set the next deadline, and (3) compute the next value.


Input state is stuck HIGH when function called using input also uses same input to call another function I'm writing a choose-your-own-adventure style project for a class project. My Arduino Uno is set up with a 16-digit LCD display and two pushbuttons with pulldown resistors. I'm wanting each function to display text on the LCD and then take two user inputs, Yes or No, from the pushbuttons, and then call another function respective of which input is pressed. Each successive function will also take the two inputs to then call the next function in the series, and so on.
My issue is that after the first time a pushbutton is pressed, its state does not change. When question1() is called, and the user presses button1, question2 is called. However, the function runs and never waits for user input, and question4 is called right away because the state of button1 seemingly stays HIGH after the first time it is pressed.
What am I missing? Is there a better way to be gathering the user input? My pushbuttons are properly wired with the resistor pulling down to ground so my issue must be with my code.
Thanks in advance for any help.
void loop()
{
  question1();
}

void question1()
{
  button1State = digitalRead(9);
  button2State = digitalRead(8);
  if (q1 == false)
  {
    text1();
  }

  if (button1State == HIGH)
  {
    question2();
  }

  if (button2State == HIGH)
  {
    question3();
  }
}

void question2()
{
  button1State = digitalRead(9);
  button2State = digitalRead(8);
  if (q2 == false)
  {
    text2();
  }

  if (button1State == HIGH)
  {
    question4();
  }

  if (button2State == HIGH)
  {
    question5();
  }
}

There needs to be a delay() after the button state is read to allow time for it to return LOW, dumba**.
You already have enough delay() in your textN() functions, just check the button state after calling that function, not before. Code should be as follows:
void loop()
{
  question1();
}

void question1()
{
  if (q1 == false)
  {
    text1();
  }

  button1State = digitalRead(9);
  button2State = digitalRead(8);

  if (button1State == HIGH)
  {
    question2();
  }

  if (button2State == HIGH)
  {
    question3();
  }
}

void question2()
{
  if (q2 == false)
  {
    text2();
  }

  button1State = digitalRead(9);
  button2State = digitalRead(8);

  if (button1State == HIGH)
  {
    question4();
  }

  if (button2State == HIGH)
  {
    question5();
  }
}

This solves the issue completely.


"undefined reference to" - C++ Hi fellow programmers,

I started to program Arduino a little deeply and popped out the following error when I was writing a class to read the pulses of a Hall effect flow rate sensor:

SensorDeVazao.cpp.o: In function `SensorDeVazao::Resetar()':
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp.o:SensorDeVazao.cpp:141: more undefined references to `SensorDeVazao::SensorHandle' follow
collect2: error: ld returned 1 exit status

The code is divided in two files, a *.h and a *.cpp, so it is uncircumstantial to paste the code here (pos-edited: the codes are the following: *.h: codepad.org/UyLfik6W *.cpp: codepad.org/5KJmraCC). But I will explain the context:

SensorHandle is a static object of the own class SensorDeVazao (Brazilian Portuguese to FlowRateSensor) and it is used in an glue function used by the attachinterrupt to read the pulses I've mentioned previously. The function claimed in the error log ("Resetar", Brazilian Portuguese for reset) don't use the variable "SensorHandle". Last but not least, the message shown in the second line appears subsequently multiple times in the error window.

I hope, I provided all the informations to help you solve this issue.
Thank you for the attention.

PS.: Sorry if this is a duplicated post. If yes, please forward it in the comments below.

Without seeing the actual code (BTW why can't you add it? Is it top-secret?) I can't be sure, but usually this happens when you don't define a variable but just declare it. Example:

// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
void myfunc() {
    A::i = 0;
}

If you actually declare it the error should go away:

// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
int A::i = 0;

void myfunc() {
    A::i = 0;
}

Remember that the class definition (so the class {}) can go in a header file, but the variables definition MUST go in a source file (so the .cpp one) AND if you have multiple source files you have to put this in ONLY ONE file (usually the file where you implement the functions).

This only applies to static variables.

EDIT: Further explanation.

You should understand the difference between declaration and definition of a variable.

Definition is just stating "there exist a variable called i, which is an integer"; for instance the statement extern int i; defines a variable. All the variables listed in a class are only defined there.

Declaring a variable is one more step: it tells the compiler to reserve the space in memory (this operation is called allocation) and so to physically create the variable. Always keep this in mind.

Little example. Let's say you have a library, using files lib.h and lib.cpp, and files A.cpp and B.cpp both referencing the library (they have a statement saying #include "lib.h"). When writing a library without a class you usually write global variables in this way:

// header file: lib.h
extern int i;

// source file: lib.cpp
int i;

(note: it is better to always define an initialization value, so for instance int i = 0;). The two files (A and B) both have the line extern int i; in they, which means "there exist a variable called i, and someone else is allocating the space for it. Result: the compiler will link all those definitions to the same memory location, thus actually sharing the variable. If you wrote int i; in the header file each cpp file would have its i variable allocated, so each would point to a different block of memory.

Now, for the classes. If you write

class A {
public:
    int a;
    static int b;
}

you have two variables. A gets instantiated when you instantiate an object, so does not have any problems. But b... well, b is just defined, never declared. So there is no place in memory where b actually resides (the reference is undefined).

To deal with this, you have to manually declare it in a cpp file, with the syntax int A::b;. This way you are reserving some space for that variable


Detect closed shutter I want to controll some ambient lights in my living room.

Therefore, I got some 433mhz outlets which can be turned on or off with an remote, a 433mhz transmitter and receiver on the arduino.

The arduino receives the remotes signals and knows which lamp has which state and will turn any lamp off at specific times.

Now I want to turn on the lights automatically when I close the shutter, but I have no idea how I could do this.

A light sensor behind the window won't do the job. I don't want to turn on the lights when it get's dark, but when the shuhtter get's closed.

Edit:
What came to my mind first was an light sensor inside the window, facing outside, and a IR LED. I'd attach some tinfoil to the inside of the shutter to return the IR light, which the sensor will notice. But maybe the're are some simpler solutions? Also, the tinfoil would fall off quickly...

I would go for a normally open read switch (should cost >$0.1) and a magnet on the shutter (again should cost >$0.1).  There are formulas to work out the distance that the reed switch will operate at, and it depends on the magnet, but the common ones are about 40mm.
(If you can wait 2 weeks for delivery you can get the parts off AliExpress.com)


LED blinking count with LDR sensor How to count +1 all the time if LED blinks with LDR sensor

Image:

If i turn on led it must count into serial monitor 1 and if i turn off led and turn on again then it counts 2.

To turn on led I must put my hand into LDR sensor.

It also looping text in serial monitor "First LDR sensor is Dark".

int ledPin1 = 7;
int ledPin2 = 8;
int ledPin3 = 9;
int ldrPin1 = A0;
int ldrPin2 = A1;
int ledTest = 200;
int ldrStatus1 = 0;
int ldrStatus2 = 0;
int ledCheck1 = 0;
int ledCheck2 = 0;
int Count = 0;

void setup() {

  Serial.begin(9600);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);

  pinMode(ldrPin1, INPUT);
  pinMode(ldrPin2, INPUT);
}

void loop() {

  ldrStatus1 = analogRead(ldrPin1);
  ldrStatus2 = analogRead(ldrPin2);

   if (ldrStatus1 <= ledTest) {
    digitalWrite(ledPin1, HIGH);
    Serial.println("First LDR is Dark");
    ledCheck1 = 1;
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin1, LOW);
    ledCheck1 = 0;
   }

   if (ldrStatus2 <= ledTest) {
    digitalWrite(ledPin3, HIGH);
    Serial.println("Second LDR is Dark");
    ledCheck2 = 1;
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin3, LOW);
    ledCheck2 = 0;
   }

   if ((ledCheck1 == 1) && (ledCheck2 == 1)) {
    digitalWrite(ledPin2, HIGH);
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin2, LOW);
   }

}

At the moment it counts when it is turned on, like seconds..
How to fix or make it work correctly?

Use state change detection and hysteresis for counting pulses in an analog signal.

const int lowerThreshold = 150;
const int upperThreshold = 200;

const uint8_t analogPin = A0;
const uint8_t ledPin = LED_BUILTIN;

void setup() {
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  static bool state = LOW;
  static unsigned int counter = 0;

  int analogValue = analogRead(analogPin);
  if (state == HIGH) {
    if (analogValue < lowerThreshold) {
      state = LOW;
      counter++;
      Serial.println(counter);
      digitalWrite(ledPin, LOW);
    }
  } else { // state == LOW
    if (analogValue > upperThreshold) {
      state = HIGH;
      digitalWrite(ledPin, HIGH);
    }
  }
}

This sketch basically applies a software Schmitt trigger to the analog input signal, and increments the counter on each falling edge. (Rising edge of light intensity, because your LDR configuration inverts the signal.)

The red waveform is the analog input from the LDR. The gray rectangular wave is the state (and the state of the LED). The counter is incremented at each black, vertical dashed line.


Water pump controlled by soil moisture sensor I'm just learning to code in Arduino.

The purpose is that first the sensor measures the moist level (I mapped the reading values from 0 to 100). If the value is less than threshold 70, then it will turn on a water pump. As soon as the value goes beyond 70, the pump stops pumping water.

The problem is that even when the value is less than 70, the pump doesn't work.

I tried replacing the pump with a LED, it turns on a the right moment. I tested the pump itself, and it also works perfectly.

//for mapping values
int mostMoist = 100;
int leastMoist = 600;
int percent;

//direct value from sensor
int raw;

//threshold for minimum percentage to turn on pump
const int threshold = 70;

//initial state of water pump
bool dosomething = false;

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

void loop() {
  //if it's not pumping water:
  while (dosomething == false){
  //check sensor value, map out of 100, and display on monitor
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);
  if (percent < 0){
    percent = 0;
  }
  Serial.println(percent);
  Serial.println("dosomething is set to false");

  //check if percentage moist is less than threshold. if so, set dosomething true, orelse, loop dosomething false
  if (percent<threshold){
    dosomething = true;
  } else{
    dosomething = false;
  }
  delay(2);
  }

  //if it's pumping water:
  while (dosomething==true){
  //check sensor value, map out of 100, and display on monitor
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);
  if (percent < 0){
    percent = 0;
  }
  //turn on pump
  digitalWrite(13,HIGH);
  Serial.println("dosomething is set to true");
  //check if percent moist is less than threshold value, if so, loop dosomething true, orelse, set dosomething false
    if (percent<threshold){
    dosomething = true;
  } else{
    dosomething = false;
  }
    Serial.println(percent);
  delay(2);
  }

}

I don't see a second power-supply in your photo. If you're trying to run the pump directly from an Arduino pin, it is highly likely that the pump needs way more current than the pin can supply.

It may be possible to power the motor from the USB but 1) the Uno board doesn't make that readily available, 2) it puts your PC at some risk (of back-EMF or of over-drawing the port's capability. But the ideal would be a separate power supply (don't forget to connect that supply's ground to the Uno's ground).

Also, if you tested the pump while dry it may have been able to run, yet with water in it, have been unable pull enough starting current to get going.


Programming AT24C16 EEPROM with Arduino Nano I have been trying to program an AT24C16 EEPROM and have set up a circuit as per the attached image.

I have been using the following Arduino code:
#include <Wire.h>

#define disk1 0x50    //Address of 24LC256 eeprom chip

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

  unsigned int address = 10;

  writeEEPROM(disk1, address, 72);
  Serial.println(readEEPROM(disk1, address), DEC);
}

void loop(){}

void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data )
{
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(data);
  Serial.println(Wire.endTransmission());

  delay(5);
}

byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{
  byte rdata = 0xFF;

  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Serial.println(Wire.endTransmission());

  Wire.requestFrom(deviceaddress,1);

  if (Wire.available()) rdata = Wire.read();

  return rdata;
}

Unfortunately I only ever receive '255' in the serial monitor suggesting that no data has been written.
The code was from this tutorial which explains how the wiring on pins 1-3 governs the address of the chip.

In response to the answer from @timemage I updated my code which now allows me to read and write to the EEPROM chip as intended. Here is the code just in case anyone else wants it quickly:
#include <Wire.h>

#define disk1 0x50    //Address of eeprom chip

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

  unsigned int address0 = 0;

  writeEEPROM(disk1, address0, 1);

  Serial.println(readEEPROM(disk1, address0), DEC);
}

void loop() {}

void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data )
{

  const uint8_t i2c_base_address = 0x50;
  const uint8_t upper_three_eeprom_adress_bits = (eeaddress >> 8) & 0x7;
  const uint8_t i2c_address = i2c_base_address | upper_three_eeprom_adress_bits;
  Wire.beginTransmission(i2c_address);
  Wire.write(eeaddress & 0xFF); // address LSB

  Wire.write(data);
  Wire.endTransmission();

  delay(5);
}

byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{
  byte rdata = 0xFF;

  const uint8_t i2c_base_address = 0x50;
  const uint8_t upper_three_eeprom_adress_bits = (eeaddress >> 8) & 0x7;
  const uint8_t i2c_address = i2c_base_address | upper_three_eeprom_adress_bits;
  Wire.beginTransmission(i2c_address);
  Wire.write(eeaddress & 0xFF); // address LSB

  Wire.endTransmission();

  Wire.requestFrom(deviceaddress, 1);

  if (Wire.available()) rdata = Wire.read();

  return rdata;
}


Powering the attiny85 with a separate power source I have an LED project for which i'm using a 9v power supply. For part of the project I'm using an off the shelf LED driver that is compatible with 9v however I have one LED component that I want to drive with the attiny85 (random blinking pattern), which is not compatible with 9v.

Does it make any sense to power the attiny85 separately with say a 3v coin cell, while allowing my LEDs to draw from 9v? The attiny85 would only be tripping transistors. I assume the attiny85 itself doesn't consume much power so hopefully I wouldn't be changing out the coin cell too often.

I have a couple 5v buck converters on hand but they take up more space than a coin cell would.

P.S. It's a Guy Manuel Daft Punk Helmet.

Does it make any sense...

Well, actually it does make sense and you already rationalize it in your question: less space consumed, expected life time of the coin cell is ok for your intended use case (though you could/should confirm the assumption about power consumption with the AVR's data sheet).

There is nothing wrong in powering the microcontroller with a different voltage than the "power" circuitry, assuming the ground lines are connected and the transistors mentioned are operated in a suitable mode, e.g. open collector/open drain type.


Writing data from multiple sensors in burst mode to an Arduino Due I need help developing a simple sketch that can read data simultaneously from 3 analog accelerometers and send it in 'burst mode' to be stored on an SD card, to reduce the effect of latency.

I used this library to get my accelerometers to work properly, but I'm just having difficulty coming up with a sketch in the code to getting all the acceleration data out in bursts.

Your help will be much appreciated.

What I meant by 'burst mode' is that all acceleration data from all three sensors connected to the Arduino should be saved at once to the file on the SD card (a temporary measure, as I'll have to send this data via Bluetooth to a base station as I build the system up to be able to receive more data from multiple Arduinos).

Although there would be a delay of about 1/10th of a second between each reading from the three sensors, the idea behind it is to be able to read and write off the data in this said simultaneous burst mode at a high sample rate (this will be adjusted with an oscilloscope at a later stage) to prevent data from being lost or chunked up.

Here is a link to the datasheet as requested.

What you need to do instead is to declare an array buffer of the data type you need to send, and send it through Serial. The array buffer could be of any length of your choosing, then you reiterate through on a for loop till all the contents of the buffer are read out which is essentially the burst mode you require.


How to convert my Arduino setup to a PIC setup? I have an arduino setup with LCD, RTC, EEPROM, Reed Switch, AC/DC Buck Converter, 4X4 Keypad.
What PIC IC will let me connect with all these(40 Pins), and yet accept Arduino Code.
I don't want to rewrite the code. I learn Arduino only recently, So shifting to another coding language is near impossible, since am not a coder.

The PIC32 has full (or nearly full) support for the Arduino API through the chipKIT project.  If you want to use one of the smaller PIC chips (PIC16 / PIC18 etc) then you're out of luck. There just isn't a freely available C++ compiler for those chips, so the Arduino API can never really be ported to them.
I have, in the past, cobbled together an Arduino-style API layer for a handful of selected PIC18s which uses structs to emulate a couple of the Arduino C++ objects, but it only worked in a very basic way with no function overloading for things like Serial.print().
One of the problems from a low-end user's perspective is that the PIC32 only comes in harder to use TQFP and QFN etc packages in anything larger than 28 pins. That means you can't breadboard without a development board. Fortunately there are some breadboard friendly options in the chipKIT ecosystem, such as the Fubarino series of boards. For more pins though you'd be wanting one of the bigger boards, such as the MAX32 which is in a Mega footprint (but with even more pins).
It's important to note though that the PIC32 is a 3.3V device and, owing to physical differences in the way that some of the internals work, there are incompatibilities in some of the libraries and functionality (such as no "LOW" or "CHANGE" interrupt support, only "RISING" and "FALLING").


What sensors to measure grass growth? I would like to make a small project, which would allow me to recognize if the grass has grow enough to lawn. I don't know too much the ecosystem of available sensors for such problem. And I have a lot of grass and some irregular areas to clean once in a while.

Is that something I can do with an arduino and some sensors, or should I need to use more processing power and cameras/AI?

TIA!

My idea: Two light sensors on a short stick embedded in the ground. If the top sensor detects light, but the bottom one does not it means that it's daytime, and grass is long enough that it covered the bottom sensor. You will probably need several of those, because there is no guarantee that grass will actually cover the bottom sensor, and you will need to filter out random elements by testing if values don't change to much.


How fast should I be able to write to AT45DB321D flash memory? I checked the AT45DB321D datasheet and it says it operates at either 66 MHz oder 33 MHz. Both of these speeds are higher than what an Arduino Nano supports (my google fu fails me here, but according to the Arduino SPI doc it's probably on the order of 4 MHz).

According to the datasheet

  Data can be clocked in from the input pin (SI) into either buffer 1 or buffer 2. To load data into the standard DataFlash buffer (528 bytes), a 1-byte opcode, 84H for buffer 1 or 87H for buffer 2, must be clocked into the device, followed by three address bytes comprised of 14 don’t care bits and 10 buffer address bits (BFA9-BFA0). The 10 buffer address bits specify the first byte in the buffer to be written. [...] Data will continue to be loaded into the buffer until a low-to-high transition is detected on the CS pin.

Which means to write a single byte I would need

1 opcode byte
3 address bytes
1 data byte

totaling 5 bytes or 40 bits which at 4 MHz yields 10 µs.

My code, as below, yields roughly 48 µs per byte (outputs a duration of ~12380 µs for transfering 256 bytes). I'm using the DataFlash library.

#include <SPI.h>
#include "DataFlash.h"

static const int csPin    = 10;
static const int resetPin = 8;
static const int wpPin    = 7;

DataFlash dataflash;

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

  SPI.begin();

  dataflash.setup(csPin, resetPin, wpPin);
  dataflash.begin();

  long start = micros();
  dataflash.bufferWrite(0, 0);
  for(int i = 0; i <= 255; i++) {
    SPI.transfer(i);
  }
  long afterBuffer = micros();

  Serial.print("Writing 256 values to buffer: ");
  Serial.println(afterBuffer - start);
}

void loop()
{
  // nothing
}

It's very likely I'm missing something, but especially if I want to transfer larger chunks of data at once I'd like to speed up that process a bit. Creating a 256 byte buffer and writing it all at once

// outside time measurement
uint8_t buffer256[256];
for(int i = 0; i <= 255; i++) {
  buffer256[i] = i;
}
// inside time measurement
SPI.transfer(buffer256, 256);

takes roughly the same time.

tl;dr: Is everything working correctly/what am I doing wrong? How can I speed up writing to a flash chip using an Arduino Nano?

"Data will continue to be loaded into the buffer until a low-to-high
  transition is detected on the CS pin."

The dataflash.bufferWrite command writes the opcode and address bytes and then in the for loop you write 256 data bytes. The data bytes are written at once, without preceding each single one with the opcode and the address. (So it does already what you want to do.)

It doesn't matter whether you write the byte at once or each with a single SPI write. SPI can only send them sequentially. And the initial opcode and address is only send once with the dataflash.bufferWrite command.

BTW: There are two buffers to write to 1 and 2. So I'm curious why the command dataflash.bufferWrite(0, 0); works. IMHO that should be dataflash.bufferWrite(1, 0); or dataflash.bufferWrite(2, 0);.

You also not start the internal writing to the pages. There is no command e.g. dataflash.bufferToPage(1, 7);. The data are only transfered into the flash's buffer.

Because data is not written into a memory page, you'll lose it, if you switch off the power.

UPDATE

I fear I understood your question not completely. As I now see, you wondered why you need 48 µs in average for 256 Bytes when the SPI Bus is driven with 4MHz.

I looked a little in the codes and docs. And that's what I found:

The DataFlash lib selects a different Clock divider:

/* Setup SPI */
SPI.setDataMode(SPI_MODE3);
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV2);

SPI_CLOCK_DIV2 results after some computation to a frequency of Fosc/2. The computation are very difficult to follow, because they use an 8 bit number which is divided into 2 nibbles each of them defines a part of a register content. But I'm quite sure the result is Fosc/2. But that would result in a clock frequency of 8 MHz. That can not explain your observed timings.

BTW: There is also in interesting deprecation note about setting the clock speed this way. ;-)

  // This function is deprecated.  New applications should use
  // beginTransaction() to configure SPI settings.
  inline static void setClockDivider(uint8_t clockDiv) {
    SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK);
    SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK);
  }

But then I saw another thing that could be a problem. There are to single value transfer functions. One for bytes (uint8_t) and one for integers (uint16_t). Your count variable is an integer so the two byte transfer method is used, resulting in two byte per transfer and therefor 512 bytes. But that also no explanation for the observations. And writing buffers works only with uint8_t[] so ??.

What else could have happened?

The MCU could be clocked by a lower frequency then 16MHZ. I think there are fuses that can be configured to reduce the master clock speed for using the MCU with lower voltage (like 3.6 Volt).

The missing beginTransaction / endTransaction (DataFlash doesn't use this) of the SPI bus could have impact on the interrupts which could distort the timing. (But that's a very wild guess ;-))

The observation that, transferring twice the amount of data with the single int transfer method does take roughly the same time than the buffered method gives us a hint, that possibly the SPI speed is not the problem.

In the function dataflash.bufferWrite(0, 0); there is e.g. a wait function
waitUntilReady(); that could cause a long delay of ~12 milli seconds. You can easily try that, by taking the dataflash.bufferWrite(0, 0); out of the timing.

void DataFlash::waitUntilReady()
{
    while(!isReady()) {};
}

uint8_t DataFlash::isReady()
{
    return status() & AT45_READY;
}

uint8_t DataFlash::status()
{
    uint8_t status;
    reEnable();     // Reset command decoder.
    SPI.transfer(DATAFLASH_STATUS_REGISTER_READ);
    status = SPI.transfer(0);
    disable();
    return status;
}


ISP - Wrong direction frying ATmega I tried to flash my ATmega328P-PU not over the Arduino but over a self-made programming board and an USBasp. The problem is, I made the board a while ago and didn't mark which direction the 10-pin connector has to go.

My question is, can I fry the ATmega if I connect the 10-pin connector the wrong way around? Also, can this harm the USBasp in any way?

Connecting it the wrong way around would give me the following connections:

USBasp  ---  ATmega

MOSI    -|
NC      -|-  GND
RST     -|
SCK     -|

MISO    ---  Vcc
Vcc     ---  MISO

         |-  MOSI
GND     -|-  NC
         |-  RST
         |-  SCK

No, connecting it backwards shouldn't do any damage, it just won't work.  The clue is in these two connections:

NC      -|-  GND
GND     -|-  NC

With it backwards the ground connection doesn't go anywhere.  Without that ground connection there's no circuit.  With no circuit, no current flows.

The only possible danger is to the protection diodes in the IO pins when you try and operate the programmer.  The lack of a ground connection could cause some current to flow the wrong way through the circuit (in through the ATMega's MISO pin and out through the MCU's Vcc pin) through the ESD protection diode.  That could cause damage to that diode and maybe the rest of the MISO pin's logic, but it's not that likely since the currents involved would be somewhat limited by the route the power then takes through the MISO pin of the programmer.