Is it possible to extract a hex file via UART from an Arduino? Right now I am tinkering on my 3D printer that has an Arduino mega as a brain. I need to update the Marlin firmware but in case of an error I want to create an backup of the firmware. And because it is assembled using a shield on top have no access to the ICSP interface. And I was curious if you can extract all the flash and EEPROM via USB (UART). If yes than what software should I use to do that.

AVRDUDE which is used by the IDE to send the content of HEX file from your computer, as a feature letting it to get back the data of the flash, in order to compare and see if data are correct.

For a UNO try:

avrdude -patmega328p -carduino -P/dev/cu.usbmodemFD121 -b115200 -U flash:r:"flash.bin":r

I think it would not be very hard to change that for a Mega.

It works fine. I have use that a lot to debut my "Android Updater" which allow the user of my board to update the code themselves.

PS: Just for info, you'll not get back the HEX file as in the flash, you have only some "pieces" of the HEX file.


Problem with tachometer using attachInterrupt and servo So I am creating a tachometer using black/white detector sensor. Here's the code.

unsigned long WaktuOLD;
unsigned long WaktuNOW;
int Detection = HIGH;
int Counter = HIGH;
float HitungWaktu;
float HitungRPM;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
  WaktuNOW = millis();
}

void rpm() {
  Detection = digitalRead(3);
  if (Detection == HIGH && Counter == LOW) {
    WaktuNOW = millis();
    HitungWaktu = WaktuNOW - WaktuOLD;
    HitungRPM = 60 / (HitungWaktu / 1000);
    Counter = HIGH;
  } else if (Detection == HIGH && Counter == HIGH) {
    Counter = LOW;
    WaktuOLD = millis();
  }
}

void loop() {
  Serial.println(HitungRPM);
  delay(5000);
}

The code works well and it can read RPM correctly. And then from the same arduino, I am controlling a servo motor, in this case I am using GWS03N/STD/F, with this code :

#include <Servo.h>

Servo myservo;
int pos = 0;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(90);
}

And this code works well too.

But, when I am trying to combine both codes, only the servo code is working well. The tachometer reading is not correct (the reading must be around 1000-1500rpm, but now it reads 3000-30krpm). I am already trying to change my tachometer interrupt to pin 2 or 3, and servo to 3, 5, 6, and 9 but still the same.

So what is wrong in here. Thank you so much.

This is my code when combining both codes.

#include <Servo.h>

Servo myservo;
int pos = 0;
unsigned long WaktuOLD;
unsigned long WaktuNOW;
int Detection = HIGH;
int Counter = HIGH;
float HitungWaktu;
float HitungRPM;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
  WaktuNOW = millis();
  myservo.attach(9);
}

void rpm() {
  Detection = digitalRead(3);
  if (Detection == HIGH && Counter == LOW) {
    WaktuNOW = millis();
    HitungWaktu = WaktuNOW - WaktuOLD;
    HitungRPM = 60 / (HitungWaktu / 1000);
    Counter = HIGH;
  } else if (Detection == HIGH && Counter == HIGH) {
    Counter = LOW;
    WaktuOLD = millis();
  }
}

void loop() {
  Serial.println(HitungRPM);
  myservo.write(90);
  delay(5000);
}

Your problem is probably that of interrupt conflicts.

The 8-bit Arduinos don't have any concept of interrupt priorities. When one interrupt routine is running it is impossible for any other interrupt routine to run until that first one has finished.

Interrupts have a "natural call priority" in that lower numbered pending interrupts will be called in preference to higher numbered ones, however that doesn't mean that they can interrupt each other.

The problem here is that the servo library uses a timer (and its associated interrupt) to generate the waveform.  That uses a lot of interrupt calls running all the time - and while they are running your external interrupt can't be called - at least not until the currently executing timer interrupt completes, at which point your external interrupt handler will be called since it is the highest priority.

So the results you get with all that delaying are pretty meaningless.

So what can you do?  Well, there's a number of options - all of which involve not using interrupts.

You could not use the Servo.h library and instead reconfigure the hardware PWM to the right frequency and use that for the servo
You could use one of the timers with an external clock source to count your tacho pulses (I think Timer 1 has that ability on the Uno)

Or even better: do both.  That would give you the most efficient system whereby the main CPU is only involved in getting the count from the timer periodically, and adjusting the PWM value for your servo. The rest is then done by hardware completely asynchronously.

Of course, for this you will want to study the datasheet so you know how to configure the various hardware modules.


How many interrupt pins can an Uno handle? I am looking at using a 7 channel RC receiver with the Arduino Uno R3. In the documentation, there are mentions of a maximum of 2 interrupt pins, whereas on certain other blogs I have seen mentions of using upto 20 pins as interrupts, with PinChangeInt library. So, how many interrupts can the Arduino handle natively? And is this different from  how many can be handled with software support such as PinChangeInt?

There are two types of "pin change" type interrupts. The external interrupts, of which there are two on the Uno. They are called 0 and 1, however they refer to digital pins 2 and 3 on the board. These can be configured to detect rising, falling, change (rising or falling) or LOW.

In addition to that are "pin change" interrupts, which detect a change to the pin state in any of the 20 pins (A0 to A5, and D0 to D13). These pin change interrupts are also hardware based so, in themselves, will be as fast as the external interrupts.

Both types are slightly fiddly to use at the register level, but the standard IDE includes attachInterrupt(n) and detachInterrupt(n) which simplifies the interface to external interrupts. You can also use the Pin Change Library to simplify the pin change interrupts.

However, steering clear of the library for a minute, we can establish that pin change interrupts can be as fast, or faster, than external interrupts. For one thing, although pin change interrupts work on batches of pins, you don't have to enable the whole batch. For example, if you want to detect changes on pin D4, this will suffice:

Example sketch:

ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 if (PIND & bit (4))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D4)
  PCMSK2 |= bit (PCINT20);  // want pin 4
  PCIFR  |= bit (PCIF2);    // clear any outstanding interrupts
  PCICR  |= bit (PCIE2);    // enable pin change interrupts for D0 to D7
  pinMode (4, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

My testing indicates that it took 1.6 µs for the "test" pin (pin 5) to react to a change on the interrupt pin (pin 4).

Now if you take the simple (lazy?) approach and use attachInterrupt() you will find the results are slower, not faster.

Example code:

void myInterrupt ()
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of myInterrupt

void setup ()
  {
  attachInterrupt (0, myInterrupt, CHANGE);
  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

This takes 3.7 µs to change the test pin, a lot more than the 1.6 µs above. Why? Because the code the compiler has to generate for the "generic" interrupt handler has to save every conceivable register (push them) on entry to the ISR, and then restore them (pop them) before returning. Plus there is the overhead of another function call.

Now we can work around that by avoiding attachInterrupt() and doing it ourselves:

ISR (INT0_vect)
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of INT0_vect

void setup ()
  {
  // activate external interrupt 0

  EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
  EICRA |=  bit (ISC00);    // set wanted flags (any change interrupt)
  EIFR   =  bit (INTF0);    // clear flag for interrupt 0
  EIMSK |=  bit (INT0);     // enable it

  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

That is the fastest of them all at 1.52 µs - it looks like one clock cycle got saved somewhere.

There is one caveat though, for pin-change interrupts. They are batched, so if you want to have interrupts on lots of pins, you need to test inside the interrupt which one changed. You could do that by saving the previous pin status, and comparing it to the new pin status. This is not necessarily particularly slow, but the more pins you need to check, the slower it would be.

The batches are:

A0 to A5
D0 to D7
D8 to D13

If you just want a couple more interrupt pins, you could avoid any testing by just choosing to use pins from different batches (eg. D4 and D8).

More details at http://www.gammon.com.au/interrupts


Max current through an Arduino Mega? How much current can I put through the pins of an Arduino Mega at the same time?

The situation: I am building a 7x7x7 LED cube, and my plan was to multiplex in 7 layers of 49 pins, lighting each layer, one at a time. This would mean each pin on the Arduino Mega would only have to supply max. 1 LED at a time.
However, if all 49 LEDs in one layer were on, it would presumably draw 49*20mA (from the LED specs sheet), which is 980mA. This seems like quite a lot of current to put through an ATMega chip, so I was wondering if I could do it, either continuing like this, or using transistors to control the lighting of each layer, or what?
Any help or advice is appreciated!

EDIT: Using ATMega2560, not ATMega328 or alternate.

You're on the right track here. In the datasheet for the ATmega1280 I find this box:

What you want to look at is DC Current Vcc and GND Pins  ....  200.0 mA

This is the total limit of all the current going through the chip (because everything must come through Vcc), and it is the absolute maximum. Don't go near it. You need to boost this with some transistors.


From transfer function to arduino This question might seem stupid, but I have been curious about it for a long time.

So I am a new engineering student, and we learned a lot about "designing a controller". For example, design controller for a car steering system and so on. All the "controllers" we designed are in the Laplace domain aka s-domain. And most of the times it will be just a transfer function. So how do real control system engineers use these transfer functions in arduino and other microcontrollers? I mean you cannot just put the function in there right?

Do you have to convert the transfer function to some other form and write the code for the microcontroller or is there a simpler way to do it?

Thanks for your time!

Let's assume you have an Arduino that you have arranged to sample a signal with a sample rate of 1/T that is then processed by your controller. Let's also assume that the processing time for your controller is small compared to T e.g. 0.1/T

Firstly, you need to convert the controller transfer function to discrete time. There are lots of ways to do this. Matlab has a convenient c2d() function. One way you can do it on paper (not the best way), is to use Euler's Method.

s=(z-1)/T   where T is the sampling period.

Converting a transfer function then: (s+a)/(s+b) => (z-(1-aT))/(z-(1-bT))

So now you have a TF in z such as : Y(z)/X(z)=(z-c)/(z-d)  where Y is the output and X is the input.

To implement this in a controller you need this as a difference equation in terms of delays. So convert the equation to a function of (z^-1) which is a delay:

Y(z)/X(z) = (1-cz^-1)/(1-dz^-1)

and re-write as:
Y(Z)(1-dz^-1) = X(z)(1-cz^-1)

Y(Z)-d.Y(z).z^-1 = X(z)-c.X(z).z^-1

and change to sample time treating z^-1 as a delay:
y(n) - d.y(n-1) = x(n) - c.x(n-1)

rearranging:
y(n) = d.y(n-1) + x(n) - c.x(n-1)

You can implement this easily in the Arduino by realising that y(n-1) is the previous value of y(n) and similarly for x(n), and x(n) is the value input to the controller; i.e. the reference minus the output from the ADC.


Simplifying code, getting invalid conversion from 'const char*' to 'char*' I have a program that does 4 times the same thing with different parapmeters; and was trying to simplify my code to take one parameter as a variable.

Example (what was):

const char MQTT_PUB_IRRIGATION_TANK_VALVE[]      = "ArgyleCourt/Property/Hub/IrrigationTank/Valve";
const char MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE[] = "ArgyleCourt/Property/Hub/HouseBoreWaterTank/Valve";

publishTankValveStatusIrrigation(false);

void publishTankValveStatusIrrigation(bool demandStatus) {
  if (demandStatus) {
    mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "ON");
  } else {
    mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "OFF");
  }
}

publishTankValveStatusHouse(false);

void publishTankValveStatusHouse(bool demandStatus) {
  if (demandStatus) {
    mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "ON");
  } else {
    mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "OFF");
  }
}

to one function now passing the topic also inot the function, thus needing only one function:

publishTankValveStatus(false, MQTT_PUB_IRRIGATION_TANK_VALVE);
publishTankValveStatus(false, MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE);

void publishTankValveStatus(bool demandStatus, char topicToPublishTo) {
  if (demandStatus) {
    mqttClient.publish(topicToPublishTo, "ON");
  } else {
    mqttClient.publish(topicToPublishTo, "OFF");
  }
}

when I compile the simplified function, I get "warning: invalid conversion from 'const char*' to 'char' [-fpermissive]", but do neither understand why or how to fix it.

The function declaration

void publishTankValveStatus(bool demandStatus, char topicToPublishTo)

declares topicToPublishTo as a char, that is, as a single character instead of as an array of characters that is constant.

Change char to const char * to say that  topicToPublishTo is an array of characters that is constant.


Question different ways of connecting L298N motor driver board to arduino and motors and powering them I read few posts and tutorials on this topic but none of them kind of answered my questions.  I bought this L298N motor board and i have two motors that are rated 3V

Now i am trying to understand how to connect it to arduino and power the motors.
For example i have a 12V (8x 1.5v AA batteries) I can connect to VCC and GND then enable ENA with a jumper and connect PWN port from arduino to INA. This way i can control the voltage that is coming out from OUTA and OUTB  I can bring down the 12V to 3V.
Now the question is can i use the +5 (regulated voltage) on the driver board and connect it to arduino Vin and GND to ground to power the arduino? Is that viable solution.  I actually tried it and it works.  I am worried that it is not enough voltage to properly power the arduino.  It's suggested to connect 7v - 12v to Vin.  I am also going to connect a red lab ble shield on top of arduino that is powered by 5v

Another question is if i use 12 volts battery and step it down to 3v with PWN is that going to heat up the L298N chip?

Another option is connecting 9V battery to arduino and then using Vin and GND to power the motor shield and the motors.  The problem there if motor draws more then 1Amp that wouldn't be good for the arduino.  Also if i would switch to 9v+ motors then it wouldn't work.

The third option is to have two separate power sources. 9V for arduino and 5v+ for powering the motors.  Does it make sense to use two power sources?

This project seems like a good way to learn about arduino and electronics

Update

NEOMART Brand New Original High Quality Chips L298N
http://www.amazon.com/gp/product/B00E58EA90/ref=oh_aui_detailpage_o04_s00?ie=UTF8&psc=1
Product Details
1. driver chip: L298N Dual H-Bridge Motor Driver IC

drive section terminal supply area Vs: +5V ~ +35V; such as the need to take power within the board, the supply area Vs: +7V ~ +35V
drive section peak current Io: 2A
logical part of the terminal supply area Vss: +5V ~ +7V(can take power within the board +5V)
logical part of the operating current range: 0 ~ 36mA
Control signal input voltage range:
Low:-0.3V ≤ Vin ≤ 1.5V
High: 2.3V ≤ Vin ≤ Vss
enable signal input voltage range:
Low: -0.3 ≤ Vin ≤ 1.5V (control signal is invalid)
High: 2.3V ≤ Vin ≤ Vss (control signal active)
Maximum power consumption: 20W (when the temperature T = 75℃)
Storage temperature: -25℃ ~ +130℃
Driver Board Size: 48mm*43mm*33mm (with fixed copper pillar and the heat sink height)
Other Extensions: control of direction indicators, the logic part of the plate to take power interface.

Update 2:

I wanted to clarify regarding using 12 volt battery and having 2 motors that I think max voltage is 3 volts.  If i use PWN and step down the voltage to 3 volts will L298N produce a lot more heat to step the voltage down?
Probably in this case would be the best just to get two separate power supplies 9 volts for arduino and 4.5 volts for the motor drive to supply 3 volts for each motor.  Unless i get better motors that support 6v - 9v then i can use the 12 volts battery for both arduino and motors.

As far as the motor drivers, I thought they are used to prevent the noise and power spikes from motors?  I guess you still have to consider it either way.

Thanks in advance!

Here is a link to a robotoid page which describes a way to use it.
Here is a link to funnyrobotics which explains how to use it.

I am confident that you could use a search engine to find more examples.

One trick is to use image search. Then look for pictures which look like your photo, and which have extra writing on them. Most people who add labels and writing to the photo are writing to help beginners understand how to use something.

Edit:
That L298N board claims to have a 5V regulator for powering the Arduino, in which case you could use a single power supply, and let the motor board feed the Arduino.

There are two schools of thought on powering the Arduino and motors:

Use two separate power supplies, one for the motor and one for the Arduino.
Use one supply for both the motor, and Arduino.

Using one supply is simple overall. One concern is electric motors can create a lot of electrical noise. If this is not adequately filtered, it might get injected into the Arduino and maybe cause the microcontroller to reset, or become temporarily unstable. The single supply advocates say the power supply to the Arduino should be properly filtered using capacitors and a proper voltage regulator usually, and the problem is solved.

I agree in principle. However, I have seen situations where the transient failure was so brief it looked 'mysterious'. It took time and effort to track it down. Sometimes it was because the motor power supply was underpowered. When the motor 'stalled', for example when changing direction, taking maximum current, the power supply voltage might dip enough to cause the Arduino supply to dip, and reset the chip.

Summary, if you are going to use a single power source for both motor and Arduino, ensure it has plenty of electrical noise filtering, and is a bit over-engineered to cope with the motor stalling. Specifically, it should be able to supply the motors stall current without dipping too low for the Arduino. The 'professional' approach is to have the Arduino monitor the main power supply, and detect that voltage dip. However, that is more complexity, and I suggest you avoid that.

Edit: If you are concerned you might have weird, hard to trace problems, using a single supply, try to design the system so that the Arduino can be 'unplugged' and given its own supply. That should be easy to do with that L298N board as the connections are screw terminals.

Using two separate power supplies should reduce the chances of electrical noise from the motors getting into the Arduino. In some circumstances is it useful to be able to change the motor power supply, or switch it off, without powering the Arduino off.

When the motor voltage is a lot higher than the 5V needed by the arduino, simple techniques to step down the voltage (linear regulators, like the part on that L298N board) convert the excess power to heat, which is quite inefficient. Much above, about, 18V it can generate enough heat to reach quite a high temperature (i.e. 100C) unless it has a good heatsink.

In that case, a simple, cheap solution is to use a second small power supply for the Arduino. An Arduino is likely using under 100mA, so a PP3 would be okay for, maybe, a few hours. A longer term approach is to step the motor voltage down efficiently.

If you use two power supplies, connect the two 'ground' (i.e. or most negative battery connections) together so that they have a common 'ground' reference. That way the Arduino signals will control the motor driver reliably.

Edit:
PWM does not step down voltage. It gives the illusion of less power because the full voltage is only applied for a fraction of each millisecond. When it is on, it is providing (very close to) the full 'motor' voltage. If the 'motor voltage' connected to that L298N board is 12V, then the motor will see 12V.

However, even if the motor is rated at only 3volts, it is unlikely to break only because 12V is applied across it. A 3V motor is as likely to break because it gets too hot, or spun too fast (e.g. the bearings get damaged).

It will likely get too hot under load, or spin too fast if the PWM signal is on for more than, WAG 50% of the time (but there is no warranty with WAG = Wild-A$$-Guess).

If, and only if, your software doesn't run PWM more than 50%, then those motors may be okay. That is a risk I might be prepared to take if the motors are cheap, and replacements easy to get.

Skimming the datasheet, the L298N needs an absolute minimum motor supply of 2.3V+2.5V = 4.8V.
Also, the output switches which control the motor appear to 'drop' a minimum of 1.8volts.
So I think it would be okay with 6V or 7.2V (maybe upto 9V) motor voltage.

IIRC the arduino will work okay with 7.2V upwards, i.e. 6 x NiMh batteries. A higher voltage is just converted to heat by the on-board voltage regulator. I might be tempted to experiment with the L298N boards 5V output, unless you have seen complaints about it.

I am assuming the motors are brushed DC motors (and not steppers or something exotic)

The motor driver will handle switching the current that the motor needs. However, each time the current is switched on or off, the motor will draw current, or generate current (remember it is a motor and also a generator). That could cause the power rail to dip, or even feed current into power or ground. There are diodes on the board to prevent those spikes doing anything awful to the chip, but there is still current flowing through wires.

Further, every rev of the motor, the brushes will break one connection, and make a different connection with the commutator, typically 6 times. (The commutator is the mechanical system that directs the current to flow the correct way round in the motors spinning electromagnet). That creates electrical noise. In some cases so much that you can hear it on an old fashioned radio receiver or analogue TV.

So noise may be a problem. People typically put a 10nF-100nF, relatively high voltage (say 50V), capacitor directly across the motors power connections, at the motor end.

If things get bad, I did a quick search and this blog looked okay, it illustrates ways to use capacitors and inductors to reduce motor noise.

I wouldn't worry too much. Put 10nF-100nF across the motor wires, and see what happens.


Serial monitor when port is being used by another application I am controlling some LEDs via the USB serial port using a Tkinter/Python3x script to debug what I suspect is a hardware problem.

from tkinter import *
import serial

usbport = 'COM3'
ser = serial.Serial(usbport, 9600, timeout=1)

def init():
    print("Started")

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()
        self.scale1 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(1), bd=5, bigincrement=2, length=360, width=30, label='RED')
        self.scale1.set(128)
        self.scale1.pack(side=LEFT)
        self.scale2 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(2), bd=5, bigincrement=2, length=360, width=30, label='GREEN')
        self.scale2.set(128)
        self.scale2.pack(side=LEFT)
        self.scale3 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(3), bd=5, bigincrement=2, length=360, width=30, label='BLUE')
        self.scale3.set(128)
        self.scale3.pack(side=LEFT)
        self.centre = Button(frame, text="Centre All", command=self.centre)
        self.centre.pack(side=TOP)

    def getBright(self, slider):

        if slider==1:
            brt = self.scale1.get()

        if slider==2:
            brt = self.scale2.get()

        if slider==3:
            brt = self.scale3.get()

        ser.write(255)
        ser.write(slider)
        ser.write(brt)

    def centre(self):

        for LED in range(0, 4):

            ser.write(255)
            ser.write(LED)
            ser.write(128)

        self.scale1.set(128)
        self.scale2.set(128)
        self.scale3.set(128)

init()
root = Tk()
app = App(root)
root.mainloop()

On the Arduino Mega 2560 side I read in from serial a start byte, LED label & a brightness value...

int user_input[3];
int start_byte;
int LED;           // which LED to pulse? r=1 g=2 b=3
int brightness;
int i;

// LED pins
#define REDPIN 7
#define GREENPIN 8
#define BLUEPIN 9

void setup()
{

  // LED outputs
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);

  Serial.begin(9600);
}

void loop()
{
  if (Serial.available() > 2) {

    start_byte = Serial.read();
    if (start_byte == 255) {

      for (i = 0; i < 2 ; i++) {
        user_input[i] = Serial.read();
      }

      LED = userInput[0];
      brightness = user_input[1];

      switch (LED) {

        case 1:
          analogWrite(REDPIN, brightness);
          break;

        case 2:
          analogWrite(GREENPIN, brightness);
          break;

        case 3:
          analogWrite(BLUEPIN, brightness);
          break;

      }
    }
  }
}

Now I would like to see what is actually being sent via the serial port to the Arduino using the serial monitor (yes I know I can just print the values in the Python terminal that's not what I'm asking).

The problem is that the Arduino Serial Monitor is locked out. I'm guessing this is a Windows thing (Win10 x64)? Has anybody here come across this?

Serial data can only go to one place at a time. Either your Python program can receive the data, or the Serial Monitor can receive the data. Similarly the serial port can only receive data from one place at a time.

So Windows prevents you doing something invalid by locking you out of the serial port when something else is using it.

This is normal, and entirely desired functionality.

Your simplest option is to just print what you receive in your Python program.


Arduino resets when I call network.begin() I have included the RF24Network library in my project. I tried to use the Simple Transmit/Receive example from here but when it calls the network.begin() my arduino restarts. I placed some Serial.println() in order to understand where is the problem. This problem appears only in my Arduino Mega 1280. I tried the same code on my Arduino Pro mini and it works like a charm. What causes this? How to fix that? It is very important to use the specific library. Thanks in advance.

The problem was that the RF24Network library is not compatible with the version of Arduino IDE I have. I downloaded Arduino IDE v1.0 and now it works like a charm. I will send an email to maniacbug to tell him about the problem.


Can I connect 220V AC supply to Node MCU (or any arduino)pin D1 and D3 while node MCDU is power off? Can I connect 220V AC supply to node MCU pin D1 and D3 while node MCDU is power off?

No, never! 220V is way way way too much for a microcontroller. The Uno runs on 5V, the ESP8266 on 3.3V. You should never connect any more voltage than that to the microcontroller. Also you must not connect a negative voltage to the microcontroller pins.

Besides the voltage difference: You should also not connect a voltage to the pins of a microcontroller, while the microcontroller itself is turned off (meaning that it does not have the necessary supply voltage). In that case a parasite current would run through the clamping diodes, which powers the microncontroller, until the diodes get blown.

As an important side note: Don't do anything with mains power (like 220V AC), until you really know, what you are doing!!! One error and it can kill you !!!


How to send SMS from an Ethernet shield via SMS Gateway? How do I send SMS from an Ethernet shield via SMS Gateway?

The site Clickatell provides free SMS.

Does anyone know how to do this or is there some other way to do it?

First contact Clickatel's support and ask them how to use their API, make yourself familiar with it.

Then when you know that you connect your Arduino to your ethernet shield, I'm just gonna assume you got Arduino's original shield, because you want to support the arduino foundation.

http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the standalone board.
http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the shield board.


Compile problem when using keyword 'new' on Raspberry Pi I have the following line of code in my Arduino sketch:

static double *temps = new double[arraySize];  //Declare array to hold tempratures, place the array on the heap where it will not be deleted and keep the pointer as a static
//double temps[arraySize];

When I compile with the Arduino IDE on Ubuntu it compiles just fine. However, when I compile on the Raspberry Pi, it throws up the following error:

xxx.cpp.o: In function `last Function in file()':
xxx.cpp:[last line in file]: undefined referance to `operator new[] (unsigned int)'
collect2: error: ld returned 1 exit status

Is this a bug? If so, how do I report it? If not, why is it throwing this error or how else can I declare a static array of doubles (needs to be static, I calculate an average of some incoming data over several function calls)?

The Arduino uses AVR libc which does not provide a complete C++ environment.

Among other things AVR libc does not support new and delete. See the FAQ for more information.

Some versions of the Arduino libraries may provide new and delete but they are just wrappers around malloc and free. I suggest not using new and delete on arduino because they do not have the same behavior as C++. For example destructors will not be called on the arduino when delete is called.


Arduino variables loaded from SD card I am trying to load some variables from an SD card on the start up of my arduino Uno. I have been given some advice but am unable to communicate at the same hours. Using this advice, I have the following edited code, but it doesn't work and I believe that it's my implementation that is the problem. All help would be greatly appreciated.

myFile = SD.open("test.txt", FILE_READ);
    if (myFile) {
        while (myFile.available()) {
            myFile.read();

            km = myFile.parseInt();
            kmTemp = myFile.parseFloat();
            kmrevs = myFile.parseInt();
            miles = myFile.parseInt();
            milesTemp = myFile.parseFloat();
            milesrevs = myFile.parseInt();

            }
        myFile.close();
        }
    else {
        Serial.println("Read Error");
    }

in you previous question, where I answered, you had no commas or new-lines in the example file content. the parseInt and parseFloat ignores only spaces by default.

remove the commas or read them or ignore them with parseInt parameter SKIP_ALL

km = myFile.parseInt(SKIP_ALL);


Arduino clone CH340G (ATmega328P), MIDI over USB I just bought my first Arduino compatible device, and I am greatly enjoying it. I finally could not resist the urge after going to an Arduino meetup, where someone showed me their Teensy connected to their laptop and reacting to MIDI signals over USB.

Not knowing anything, I bought my clone and soon learned about the whole CH340G limitation where it doesn't "just work" (I cannot simply use the USBMIDI Arduino library), and instead I need to run a software MIDI-serial converter command (ttymidi) in order to send the signals to my Arduino clone.

I've been reading up a bit (the amount of information out there is perhaps too vast and often outdated or simply doesn't exactly solve my problem) and have learned of V-USB and the project V-USB-MIDI but I am really out of my element here and do not know how to approach this to get it all working (since it is not just an Arduino sketch and .h header). Or even if this is a solution to my problem. I've read about some solutions which require using an AVR via some of the pins (as opposed to over USB) since you have to reprogram the chip in such a way that it no longer is programmable over USB once the sketch is uploaded, but if I understood it correctly, you can't do even this on the CH340G.

In any case, are there any examples of getting this working? A sketch or something? I downloaded the latest V-USB release, but I really don't want to make a mistake that will brick or otherwise ruin my device.

Basically: I want to just upload my MIDI sketch (with whatever necessary modifications or code) such that I do not need ttymidi to have the device recognized as a MIDI device (over USB) that I can just "plug 'n' play".

V-USB bit bangs some GPIO pins so that they speak the low-speed USB protocol.
This does not use the 'normal' USB connection through the CH340; you would have to solder a separate USB cable to those GPIO pins.

Programming would be no problem; the V-USB code is just normal code that runs on the MCU. (Programming through ISP pins would be required on hardware where USB communication and programming is handled with a second AVR MCU; in that case, the USB/MIDI code would run on that second MCU.)

Low-speed USB is not supposed to be used for MIDI, and as a software emulation, V-USB does not work very well, or efficiently.
If you want to create a USB device, you should use an MCU that actually supports USB in hardware, such as the ATmega32U4 or AT90USB646 used on some Teensies.


Recording and storing Midi data with arduino and midi shield i need help getting started on writing a sketch that would let me record and store midi data from a midi controller connected to a arduino mega through a midi shield. are there any functions in the midi library that will aid in this task?

The Arduino MIDI Library allows you to read and write MIDI messages, but only in real time.

Storing MIDI data makes sense only with timestamps, so you have to call millis() or micros() when you receive a message.

How to actually store the data is something that you have to design yourself; which data structure to use depends on what you want to do with the data later.


Analog output gives a close range of values I try to get a good range of values from VMA309 sound sensor.

However, when I connect it properly it gives me a range of values  +/-5 like below. The documentation says it should give numbers between 0 and 1024.

I turned the potentiometer both sides all the way and that only changed the number, but it keeps gives number in a range of 5 numbers:

An example:

626
623
624
624
624
624
623
624
624

My code:

int sensorPin = A5;
int sensorValue = 0;
void setup ()

{
  Serial.begin (9600)  ;
}

void loop()
{
  sensorValue = analogRead(sensorPin);
  delay (500);
  Serial.println (sensorValue, DEC);
}

What am I doing wrong here?

An image of the wires:
I also tried the wiring directly without a breadboard. But that gave the same results.

I used the code as given from the VMA 309 documentation.

Arduino is a lot of fun, but you better stay away from such modules.

The module is a resistor and a electret microphone. There is also a comparator for the digital output. When you have an electret microphone, and add a resistor of 4k7 or 10k, then you have the same.

The signal from the microphone is not amplified and the Arduino only gets the analog value of the audio. The module does not measure how loud the audio is.

I think Velleman makes them: www.velleman.eu/products/view/?id=435532
They are so kind to have a schematic available: vma309_scheme.pdf

Can you move on and use the Arduino for something else?
This module with this microphone is probably not going to work.
If you want to measure the sound level, then perhaps you can make a circuit yourself or buy a better module.

The "Sound Pressure" is how loud audio is.
The most used standard is called "Sound Pressure Level" or "SPL" and is measured in dB (deciBell).


ESP8266 MQTT client error #include <PubSubClient.h>
#include <ESP8266WiFi.h>

//EDIT THESE LINES TO MATCH YOUR SETUP
#define MQTT_SERVER "YOUR.MQTT.SERVER.IP"
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

//LED on ESP8266 GPIO2
const int lightPin = 2;

char* lightTopic = "/test/light1";

WiFiClient wifiClient;
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
    //initialize the light as an output and set to LOW (off)
    pinMode(lightPin, OUTPUT);
    digitalWrite(lightPin, LOW);

    //start the serial line for debugging
    Serial.begin(115200);
    delay(100);

    //start wifi subsystem
    WiFi.begin(ssid, password);
    //attempt to connect to the WIFI network and then connect to the MQTT server
    reconnect();

    //wait a bit before starting the main loop
        delay(2000);
}

void loop(){

    //reconnect if connection is lost
    if (!client.connected() && WiFi.status() == 3) {reconnect();}

    //maintain MQTT connection
    client.loop();

    //MUST delay to allow ESP8266 WIFI functions to run
    delay(10);
}

void callback(char* topic, byte* payload, unsigned int length) {

    //convert topic to string to make it easier to work with
    String topicStr = topic;

    //Print out some debugging info
    Serial.println("Callback update.");
    Serial.print("Topic: ");
    Serial.println(topicStr);

    //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
    if(payload[0] == '1'){
        digitalWrite(lightPin, HIGH);
        client.publish("/test/confirm", "Light On");

    }

    //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0'){
        digitalWrite(lightPin, LOW);
        client.publish("/test/confirm", "Light Off");
    }

}

void reconnect() {

    //attempt to connect to the wifi if connection is lost
    if(WiFi.status() != WL_CONNECTED){
        //debug printing
        Serial.print("Connecting to ");
        Serial.println(ssid);

        //loop while we wait for connection
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }

        //print out some more debug once connected
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }

    //make sure we are connected to WIFI before attemping to reconnect to MQTT
    if(WiFi.status() == WL_CONNECTED){
    // Loop until we're reconnected to the MQTT server
        while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");

            // Generate client name based on MAC address and last 8 bits of microsecond counter
            String clientName;
            clientName += "esp8266-";
            uint8_t mac[6];
            WiFi.macAddress(mac);
            clientName += macToStr(mac);

            //if connected, subscribe to the topic(s) we want to be notified about
            if (client.connect((char*) clientName.c_str())) {
                Serial.print("\tMTQQ Connected");
                client.subscribe(lightTopic);
            }

            //otherwise print failed for debugging
            else{Serial.println("\tFailed."); abort();}
        }
    }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

The error is 'callback' was not declared in this scope

In C++, you can't use or reference a function before it is declared, that's not Arduino specific, it's how C++ "works"

Moving the callback function above the client declaration won't help, because the callback function references client

The only solution is to declare the callback function before it is referenced in client initialisation, but have the definition of callback after

i.e. add one line

WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length); // add this in your code
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

Nothing else needs to be changed

Please excuse some terminology mistakes above - it's been a long time since I learned C/C++, while I know how to use it, I don't always know how to describe it :p

  apprently there's some bug in the toolchain - see the comments in the question. However, this is still a valid solution, I guess it works around the bug


Mac OS X Catalina Serial Monitor Problem I have some problems on MacBook Pro running with Catalina. I bought new nodemcu LoLin board. Its clone. It has ch340 adapter to communicate. And writing on bottom side wemos.cc and use ch340g driver.

I succesfully installed drivers and I can see my lolin boards on port list

I upload a code that doing only print hello to serial port. I tried with 9600 and 115200 baud rates. My serial monitor show garbage data. I am using platform io with VSCode to upload code and upload time is too much.When I am uploading code I got this warning :

"Detected crystal freq 156.04MHz is quite different to normalized freq 40MHz. Unsupported crystal in use?"

I am using cheap thundeIrbolt usb converter too. But I connect with this converter to Windows pc, everything looks fine. I can see hello world on serial monitor. But on my Mac, I can see garbage only. I tried some serial monitors, Arduino IDE and platform io ide but still same.

Are there any solution about this problem?

EDIT :

I fixed issue last night. Catalina has ch340 drivers already and I setup oem driver from GitHub. Apples driver and oem drivers conflicting. If you use Mojave and higher os, you dont need any driver for ch340. So if you installed ch340 oem  driver you should delete it.

I am adding the post:
Platformio post


Using an Arduino to rotate a DC motor once a minute (edited) I’m trying to write an arduino sketch that makes a dc motor turns one full rotation every 60s similar to a clock. The arduino will be connected to the gate of a typical mosfet and the dc motor will be connected to the drain of the mofset  such that the arduino controls the speed of the motor. Any suggestions on how I go about this?
I’m using an arduino mega 2560 in case that’s relevant.

The best way would be to check the datasheet: https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf and set an interrupt on one of the timer.
Example code of this application can be found on this stack here : How to make 1 second delay more accurate?
Another way of doing it if you don't need to do anything between rotation would be to wait by just waiting using delay in a for loop. Be aware that this is less precise than interrupts driven wait.
https://www.arduino.cc/reference/en/language/functions/time/delay/
edit : if you want to complete one full rotation every 60s
int i = 0;
while(1) {
  i++;
  delay(1000);
    if( i == 60){
    doFullRotation();
    i = 0;
    }
}


MPU-9250 : How to convert pitch (+90/-90) to 360 degree? I'm using Arduino Uno with MPU-9250 to find roll, pitch and yaw.

Everything works fine but I want to covert pitch from (+90/-90) to 360 degree.

I'm using this code:

vec.setX(atan2(2.0 * (m_data[2] * m_data[3] + m_data[0] * m_data[1]),
        1 - 2.0 * (m_data[1] * m_data[1] + m_data[2] * m_data[2])));

vec.setY(asin(2.0 * (m_data[0] * m_data[2] - m_data[1] * m_data[3])));

vec.setZ(atan2(2.0 * (m_data[1] * m_data[2] + m_data[0] * m_data[3]),
        1 - 2.0 * (m_data[2] * m_data[2] + m_data[3] * m_data[3])));

m_data[0] = scalar;

m_data[1] = x;

m_data[2] = y;

m_data[3] = z;

What should I do?

The equations in you example convert a quaternion representation of rotation into euler angles correctly; The "pitch" euler angle only has a valid range of +90/-90 and changing it will make your angular representation invalid.

Euler angles specify an arbitrary rotation by 3 consecutive turns. You may want "apparent angle with the horizon", which is not the same thing, and does not define a sequential set of turns to get from rotation A to B.

To get pitch and roll with the horizon from a quaternion, I think you want something like:

float x = 2*m_data[1]*m_data[3] - 2*m_data[2]*m_data[0];
float y = 2*m_data[1]*m_data[0] + 2*m_data[2]*m_data[3];
float z = 1 - 2*m_data[2]*m_data[2] - 2*m_data[1]*m_data[1];

float pitch = atan2(y,z);
float roll  = atan2(x,z);

I got this by rotating the vector <0,0,1> by the quaternion and then measuring the angles of the result around x and y axis. This kind of freaks out when one of the angles is close to 90 degrees though; there are probably better equations out there.

"Yaw vs the horizon" doesn't make any sense, and people usually want the same "style" of yaw you are getting from the euler angle equations, so that shouldn't change.


Issue with leOS2 for one-time tasks I'm trying to use the last version of leOS2 scheduler from Leonardo Miliani ( https://github.com/leomil72/leOS2 ) but I have a strange behavior with a very simplistic ONETIME task.

Platform : Arduino Uno clone, so Atmel Atmega 328P CPU.

My code is very straightforward :

#include "leOS2.h"
leOS2 myOS; //create a new istance of the class leOS

bool test = true;

void setup()
{
    myOS.begin(); //initialize the scheduler
}
void loop()
{
    // Do some stuff ...

    if(test)
    {
       DoAndUndo(3000);
       test = false;
    }
}

void DoAndUndo(unsigned long duration)
{
    doSomething();

    myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
}

void doSomething()
{
    Serial.println("thing on");
}

void cancelTheThing()
{
    Serial.println("thing is off");
}

In case it can be some kind of conflict, my code also relies on the following :

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <IRremote.h>

The problem is :
        myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
is supposed to call asynchronously the "cancelTheThing" method 3 seconds later, and for only one time, and then forget it.
But for an unknown reason, it's called after the expected delay, but it loops infinitely on this method ! In the example case above, my serial stream is filled with a lot of "thing is off" messages, and the µc is unresponsive to anything apart a reset.

The call to DoAndUndo() will produce a such like output :

 thing on

And 3s later, in a very fast infinite loop :

 thing is off
 thing is off
 thing is off
 thing is off

If I remove the "ONETIME" flag, the task is called every three seconds (exactly as it's suppose to do, so the scheduler works, but it's not what I want in my use case).

note : As a try of workaround, I've tried some tricks like calling haltScheduler() inside my cancelTheThing() and reenable it with restartScheduler() in DoAndUndo(), and also tried to call removeTask once it has ran, but it didn't help.

Thank you for your help

There appears to be a fault with the library whereby if the only registered task is a one-shot task it doesn't get cancelled when it has executed.

Adding another periodic task in setup() (say to blink an LED every 500ms) so there are now 2 tasks instead of one works around the problem.

The way the system is written it will always try an execute task number 0 even when there are 0 tasks registered because they erroneously used a "do {...} while" construct instead of a "while { ...}" construct.

I  have filed a bug report, corrected the error, and raised a pull request with the fix in it.  Until it gets accepted you can obtain the fixed version here: https://github.com/majenkotech/leOS2


Press On Hold Off Power Switch Hi everyone I am hoping someone here can help me.
I am trying to make an arduino turn my project on and off.Using a relay.
I am looking for it to act like a computer power button.
A short press to turn on and them stay on and a long press (say 5 sec) to turn off and then stay off till button is pressed again.
I would like it so that the project can not be accidentally turned off
Can anyone please help.
Thanks

To clarify the problem, do you want to control ON OFF using Arduino? It is very simple. Please read this simple tutorial, and modify it according to your needs.


How to use two Sonar's I'm using a single sonar, but I want to use two sonar to know another distance.

Here is how I use my single sonar:

    #include <NewPing.h>

    #define TRIGGER_PIN  9
    #define ECHO_PIN  10
    #define MAX_DISTANCE  100 // in CM
    ...
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
    ...
    delay(100);
    unsigned int uS = sonar.ping();
    int cm = uS / US_ROUNDTRIP_CM;

But I Want to use a second one to calculate another distance, how to?

#define TRIGGER_PIN_2  11
#define ECHO_PIN_2  12
...
new NewPing sonar(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE);
...
???

Thanks in advance

EDIT:

Maybe this one, I'll try this when I will get my second sonar

#define SONAR_NUM     2
#define MAX_DISTANCE 200
...
NewPing sonar[SONAR_NUM] = {
  NewPing(9, 10, MAX_DISTANCE),
  NewPing(11, 12, MAX_DISTANCE)
};
...
delay(100);
unsigned int uS1 = sonar[0].ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar[1].ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;

Maybe this one, I'll try this when I will get my second sonar

Ding ding ding! Yeah, this would be one way to do that. That creates an array so you can reference the sonar with sonar[i], where i is either 0 or 1 for the first or second number.

For only two sensors, it might be easier just to do something like this:

NewPing sonar1(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
NewPing sonar2(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Then you can run the other code like this:

delay(100);
unsigned int uS1 = sonar1.ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar2.ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;

A little less code to read, whichever one you want.

The reason you can do this is you can replace the sonar with whatever you wanted (following C++ variable rules like no spaces, etc.). You could call it Arduino_Sonar if you wanted to.

The array is basically a simple way of grouping variables together easily. It's not convenient to declare 500 differently name variables; I can just do int numbers[500]; to declare them. An array might be more useful if you're expanding your circuit, but either is correct.


RX and TX pin in Arduino Uno I have LED Cube Project, and I want to activate the LED with My Android apps (Bluetooth). The LED Cube used A0-A5 and D0-D13 Pins, and the Bluetooth need RX and TX (D0, D1).

Where I can put the RX and TX (for Bluetooth HC-05) while D0, D1, and all analog and digital pins are used by the LED?

You can't magic more pins out of thin air.

Yes you can!

You can have as many output (and even input) pins as you want. I managed to build 8x8x8 LED cube using ATTiny13 with just 6 output pins (using only 5 of them)

All it takes is a little extra coding and "shift registers". (For extending outputs use the one with "latch", but for LEDs normal one is enough)

You can use three (for example CD4094) 8 bit shift registers. You connect three Arduino pins to "DATA" (a.k.a. SERIAL DATA INPUT) pin of each register. Then one Arduino pin to three "CLOCK" pins and one Arduino pin to three "OUTPUT ENABLE" pins.

Then in the code you send a sequence of bits into the registers simulating the clock signal and when that's over just set output enable to make the registers output a value on their 8 output pins each.

This way you use just 5 pins, and when you chain the registers together (last "Q8" pin of one register can go to "DATA" pin of second one) you can theoretically have as many outputs as you need at the cost of output update speed.

This way you can free most of your Arduino pins including TX and RX.


How can i provide enough power on an UNO to use the HC-12 wireless module? Scenario:  The Uno is being powered by USB for programming, and the HC-12 wireless communications module is wired correctly.  But it will not work.

In reading through the web literature, it is mentioned that to use the HC-12 in the high-power (100 mW) mode requires a power supply in excess of what the laptop's USB port will provide.

I am finding nothing on Stackexchange that addresses this issue.

So the question is, how do I get the power to run the Uno with the HC-12?  I need to be able to periodically update the programming and test it while that auxiliary power is applied, and need to know it is safe to do so.

There two options I have found that work well.

First is a simple wall-wart that provides 12 Volts to a barrel connector, like for a CCTV camera.

Or, if I want to run the Uno from a separate higher-amperage USB charging port I have found that there are "USB A Male to CCTV male" cables that work.

Doing the latter means the Uno is running at 5V instead of utilizing the on-board regulator to drop a higher-voltage input, which only matters if your circuit expects to find more than 5 Volts on the Vin pin (although that is not supposed to be an output pin, of course).

Through thorough experimentation I've proven that both methods work.

The best part is that the Uno can easily tolerate having both CCTV-style power and also being plugged into the laptop for programming and testing (like using the serial monitor).

Lesson learned:  The HC-12 simply will not work without auxiliary power, and it is safe to provide such power while also plugging the serial port into a laptop.


Using Arduino IDE as an API I have a project where it would make a lot of sense to generate Arduino compatible source code, compile it and flash it based on some settings in the project software.

Is there any way to do this without having to rely on the user having installed the Arduino IDE/java?

The ideal would be a self-contained library that could be linked to my C/C++ program.

For compiling and uploading Arduino code, you do not need Java, nor the
Arduino IDE: you need avr-gcc, avr-libc, the Arduino core library and
avrdude. With a proper Makefile, your program just needs to

system("make upload");

C.f. the tutorial Compiling Arduino sketches using
Makefile.
On an Ubuntu or other Debian-like OS, you would just
sudo apt-get install arduino-mk make to get everything you need installed.


Using two pins to sum maximum available current I have a theoretical question about using digital pins of arduino. The specification of Arduino Uno (or any other I guess) says, that maximum current from digital pin is 40mA. If I would need more than 40mA and less than 80mA, can I use two pins to supply enough power to the sensor or would it burn the pins in the end?

Thanks

40mA is the absolute maximum current allowed. The recommended steady-state current is 25mA, so you'd need three or four IO pins to remain safe.

Theoretically, yes, that should be possible. However in practice doing such things is problematic.  You have to ensure that there is no point at which the sensor is being powered by less than the required number of IO pins, which means turning them all from off to on at the same time (doing them one at a time means you start with the full load through just one pin then start sharing it around). That means ensuring that all your pins are on the same port and using direct port manipulation to control all the pins at once.

It is far better, more reliable, and simpler to program, to just slip a simple p-channel MOSFET in there with a pullup on the gate to control the 5V power to the sensor. Pull the gate low and the sensor gets all the power it needs.


How to reduce sketch size? How to reduce sketch size?

I got an error that “Sketch uses 30,044 bytes (104%) of program storage space. Maximum is 28,672 bytes.”

I can't reduce function in sketch.I can't change ATmega32u4,now.
The sketch has function of measuring sensor,logging on SD,connection with BLE module.

So please tell me hack.

Or,how to increase flash memory size?

I tried to change type of String to Char.

Some generic techniques you can try:

Remove duplicate code and put it in a function.
If you have duplicate code that is ALMOST duplicate, parameterize it (i.e. add a function, make the difference a parameter(s) of the function and call from various locations with different argument(s).
Use a micro controller with more Flash memory.
Minimize the data storage, limiting array sizes for example (if these are in flash RAM).
If you use precalculated arrays, remove them and create a function calculating them real time (this will be a performance cost of course).
Check for dead code inside functions. A smart compiler will already remove uncalled functions, but do not check inside functions.
Remove or minimize debug/print statements. Each character cost a byte, which adds up quickly with many strings.
Try to remove complete libraries, like removing the Serial for print statements used only for debugging.


ESP8266 EEPROM seems not working, saved data are different when I try to read them I'm working on project which require to save some data into the EEPROM.
As I read online the ESP8266 has no real EEPROM, it use a section of FLASH just after the SPIFFS. Due to this read/write is quite different from standard Arduino, you need to call EEPROM.commit(). You also have to call EEPROM.begin(size) (I used size = 512) before start to use it.

I follow different tutorials online and I made some tests but it seems not working at all. When I try to save a value and then read it, values are different. I tried with

EEPROM.write(..)
...
EEPROM.read(..)

and with

EEPROM.put(..)
...
EEPROM.get(..)

but nothing change.

Is there any configuration on the board I need to set into Arduino IDE/Board Configuration?

EDIT: here's the code

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

    EEPROM.begin(512);
    EEPROM.write(0, 62);
    EEPROM.write(10, 103);
    //EEPROM.commit();
    EEPROM.end();
    Serial.print("Read at 0:"); Serial.println(EEPROM.read(0), DEC);
    Serial.print("Read at 10:"); Serial.println(EEPROM.read(10), DEC);
}

I always read 0 in the output.

You can read the emulated EEPROM only between begin and end. It works with memory image.

begin allocates the in-memory image.
commit writes it to flash.
end commits and deletes the memory image.


LCD Pin Numbering vs I2C Controller Pin Numbering vs Sketch I've been playing with an Arduino Uno, trying to get a 16x2 LCD screen to work with an I2C controller. I've got this LCD screen and this controller. And I've been trying to get the sketch below to work.

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3,POSITIVE);//, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup()
{
    lcd.begin(16,2);
    lcd.backlight();
    lcd.setCursor(0, 0);
    lcd.print("Hello world!");
    lcd.setCursor(0, 1);
    lcd.print("Row number: ");
    lcd.setCursor(12, 1);
    lcd.print("2");
}
void loop()
{

}

I've used an address scanner to verify that the address is correct (39 [0x27]), but it still won't display anything. It lights up, and I've tried adjusting the contrast, but it just won't display any characters.

I'm wondering if the definition of which pins are which is correct, but I can't seem to find anything detailing how the numbers used in the sketch correlate to the pins on the controller, which then correlate to the pins on the LCD screen. If any body can give me some insight I'd appreciate it.

Yes, the pins can be different depending on the LCD and the controller. My favorite solution to this is to run a simple "i2c guesser" sketch that can be downloaded from the following forum thread (download link is at the bottom of the first post):
http://forum.arduino.cc/index.php?topic=260510.0

With that sketch it usually only takes me a couple minutes to find the correct pin numbers.


80 Apple Homebuttons and a steppermotor I am graduating in a month and I want to make an installation with 80 apple homebuttons which are connected to a stepper motor. The idea is that each button that is pressed, turns the stepper motor the same amount of degrees each time. Also, each button is connected to an LED which must stay on, even if the button is pressed again and the motor too must not react. Once all 80 buttons have been pressed, the installation should switch off after a minute or so.

I am not sure how to connect 80 inputs to the arduino. Does anyone have any idea?

I have no idea what an apple homebutton is, but the easiest way to add more GPIO pins is to use something like an MCP23017; it connects over I2C and gives you 16 GPIO pins. Use five of them and you have your solution.


Firmata: how to set a particular pin to high on boot? I'm working on a project that use J5, so is using the standard firmata, this project is using an opto 4 channel relay, when the board is booting the pins state are set to low, so as soon as I power the board my relay goes to a close state and make my motor run... this is a wrong behaviour for my purpose. How can I avoid that? By googleing around I stumble acros this:

A possible solution

but I can't uderstand if this is what I'm looking for.. plus I need only the PIN 7 to be set high on boot, any help please?

EDIT: SCHEMATICS

4 Channel 5V Relay Module

It would seem you are right. If I understood the source correctly,
Firmata initializes all digital pins as OUTPUT LOW. Hard to believe, as
this seems like a silly thing to do... My understanding is that:

setup() calls systemResetCallback() in order to set the initial
pin configuration (line 779)
systemResetCallback() loops over all pins and calls
setPinModeCallback(i, OUTPUT) for every pin i that is not an
analog pin (line 732)
setPinModeCallback() calls pinMode() to set the pin to OUTPUT
(line 325).

If my understanding is correct, then the simplest solution would seem to
patch systemResetCallback() and replace OUTPUT by INPUT on
line 732.


ESP32 - JPEGDecoder from SPIFFS Hello i've try to decode JPG image from FS so, i create and upload spiffs image (using /data directory and Arduino Ide Plugin )

On every jpg i've same error: "pjpeg_decode_init() failed with status 19"

here is my same code:

#include <TFT_eSPI.h> // Hardware-specific library
#include <SPI.h>
#include "GfxUi.h"

TFT_eSPI tft = TFT_eSPI(); // Invoke custom library

#define DEBUG
#define LOAD_SPIFFS

GfxUi ui = GfxUi(&tft);

void writeFile(fs::FS &fs, const char * path, const char * message);
void readFile(fs::FS &fs, const char * path);
void listDir(fs::FS &fs, const char * dirname, uint8_t levels);

void setup(void)
{
  Serial.begin(115200);
  Serial.print("Start");
  SPIFFS.begin(true);
  tft.begin();
  tft.setRotation(3);
  tft.fillScreen(TFT_BLACK);

  listDir(SPIFFS, "/", 0);
  fs::File jpeg = SPIFFS.open("/star.jpg", "r");
  //readFile(SPIFFS, "/star.jpg");
  boolean decoded = JpegDec.decodeFsFile(jpeg);
  Serial.println("===============");
  Serial.println("JPEG image info");
  Serial.println("===============");
  Serial.print  ("Width      :"); Serial.println(JpegDec.width);
  Serial.print  ("Height     :"); Serial.println(JpegDec.height);
  Serial.print  ("Components :"); Serial.println(JpegDec.comps);
  Serial.print  ("MCU / row  :"); Serial.println(JpegDec.MCUSPerRow);
  Serial.print  ("MCU / col  :"); Serial.println(JpegDec.MCUSPerCol);
  Serial.print  ("Scan type  :"); Serial.println(JpegDec.scanType);
  Serial.print  ("MCU width  :"); Serial.println(JpegDec.MCUWidth);
  Serial.print  ("MCU height :"); Serial.println(JpegDec.MCUHeight);
  Serial.println("===============");
  Serial.println("");
}

void listDir(fs::FS &fs, const char * dirname, uint8_t levels){
    Serial.printf("Listing directory: %s\r\n", dirname);

    File root = fs.open(dirname);
    if(!root){
        Serial.println("- failed to open directory");
        return;
    }
    if(!root.isDirectory()){
        Serial.println(" - not a directory");
        return;
    }

    File file = root.openNextFile();
    while(file){
        if(file.isDirectory()){
            Serial.print("  DIR : ");
            Serial.println(file.name());
            if(levels){
                listDir(fs, file.name(), levels -1);
            }
        } else {
            Serial.print("  FILE: ");
            Serial.print(file.name());
            Serial.print("\tSIZE: ");
            Serial.println(file.size());
        }
        file = root.openNextFile();
    }
}

void readFile(fs::FS &fs, const char * path){
    Serial.printf("Reading file: %s\r\n", path);

    File file = fs.open(path);
    if(!file || file.isDirectory()){
        Serial.println("- failed to open file for reading");
        return;
    }

    Serial.println("- read from file:");
    while(file.available()){
        Serial.write(file.read());
    }
}

void writeFile(fs::FS &fs, const char * path, const char * message){
    Serial.printf("Writing file: %s\r\n", path);

    File file = fs.open(path, FILE_WRITE);
    if(!file){
        Serial.println("- failed to open file for writing");
        return;
    }
    if(file.print(message)){
        Serial.println("- file written");
    } else {
        Serial.println("- frite failed");
    }
}

void loop() {

}

Output from serial:

Listing directory: /
  FILE: /logo.jpg       SIZE: 16346
  FILE: /arduino.jpg    SIZE: 8426
  FILE: /star.jpg       SIZE: 3853
pjpeg_decode_init() failed with status 19 <--- here is
===============
JPEG image info
===============
Width      :0
Height     :0
Components :0
MCU / row  :0
MCU / col  :0
Scan type  :0
MCU width  :0
MCU height :0
===============

as far as I can determine uploading to SPIFFS via the Arduino IDE is broken as of the beginning of 2018. The files are uploaded but are corrupted on a read. There are a few fixes reported.  I am using a core from Dec 2017 and that works fine.


Light sensor acting up when used with other code I have a light sensor that works fine and outputs the correct data to the serial monitor when I only upload the following code to the nano:

const int lightSensorPin = A0;
int lightSensorValue = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  lightSensorValue = analogRead(lightSensorPin);
  delay(100);
  Serial.println(lightSensorValue);
}

Now when I upload it with all of my other code, which includes lighting up about 6 LED's at one time and getting readings from two rangefinder sensors, the light sensors no longer output expected data, instead spewing out a bunch of random numbers, 0 to over 3000.

Could sharing the ground with all the LED's and rangefinders be causing interference for the light sensor? Or could it be a code optimization issue? Here's my entire code if it helps at all:

int trigPin1 = 5;
int echoPin1 = 6;
int blue1 =  7;
int green1 = 8;

int trigPin2 = A3;
int echoPin2 = A4;
int blue2 =  A2;
int green2 = A1;

int redLED = 10;
int greenLED = 3;
int yellowLED = 9;
int blueLED = 4;

const int lightSensorPin = A0;
int lightSensorValue = 0;

int securityLength1 = 28;
int securityLength2 = 28;

int frontEyes(11);
int backEyes(12);

const char* front = "front";
const char* back = "back";

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

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(blue1, OUTPUT);
  pinMode(green1, OUTPUT);
  pinMode(blue2, OUTPUT);
  pinMode(green2, OUTPUT);

  pinMode(frontEyes, OUTPUT);
  pinMode(backEyes, OUTPUT);

  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);

}//end setup

void loop(){

  digitalWrite(redLED, HIGH);
  digitalWrite(greenLED, HIGH);
  digitalWrite(yellowLED, HIGH);
  digitalWrite(blueLED, HIGH);

eyeballs(trigPin1, echoPin1, securityLength1, green1, blue1, front);
eyeballs(trigPin2, echoPin2, securityLength2, green2, blue2, back);

  lightSensorValue = analogRead(lightSensorPin);
  delay(100);
  Serial.println(lightSensorValue);

}//end loop

void eyeballs(int trigPin, int echoPin, int securityLength, int green, int blue, const char* frontOrBack){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  long distance = (duration/2) / 29.1;

  Serial.println(distance);

 if (distance >= securityLength || distance <= 0) {
  digitalWrite(green,HIGH);
  digitalWrite(blue,LOW);
  if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);
  }//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);
  }//end else
  }//end if

  else if(distance < securityLength) {
  digitalWrite(blue,HIGH);
  digitalWrite(green,LOW);

  if (frontOrBack == "front") {
    digitalWrite(frontEyes, HIGH);
  }//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, HIGH);
  }//end else

 }//end else if

}//end function

I'd prefer to delete this question because I'm so embarrassed by the answer. I didn't notice I had Serial.println(distance); in my function. The odd numbers were coming from my rangefinders and being printed in between my light readings.


Issue with IF statement condition I am using 2 accelerometers connected to an arduino. The code below does not work.

> if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <=40)) //If acc1 is between 20 and 40 AND if acc2 is between 20 and 40
>     {
>         digitalWrite(13, HIGH);
>     }

But, the following code does:

> if((acc1 >= 20 && acc1 <= 40)) //If acc1 is between 20 and 40
>     {
>         digitalWrite(13, HIGH);
>     }

Can anyone tell me why please?
Edit with full code:

const int acc1_xPin = 0; //X Pin on acc1
const int acc1_yPin = 1; //Y Pin on acc1
const int acc2_xPin = 2; //X Pin on acc2
const int acc2_yPin = 3; //Y Pin on acc2

int xAcc1_maxVal = 409; //Maximum value for X-axis Acc1
int xAcc1_minVal = 269; //Minimum value for X-axis Acc1
int yAcc1_maxVal = 410; //Maximum value for Y-axis Acc1
int yAcc1_minVal = 270; //Minimum value for Y-axis Acc1

int xAcc2_maxVal = 411; //Maximum value for X-axis Acc2
int xAcc2_minVal = 268; //Minimum value for X-axis Acc2
int yAcc2_maxVal = 402; //Maximum value for Y-axis Acc2
int yAcc2_minVal = 263; //Minimum value for Y-axis Acc2

//Hold Calculated Values
double acc1; //acc1 angle
double acc2; //acc2 angle

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

// the loop function runs over and over again forever
void loop() {

  int acc1_xRead = analogRead(acc1_xPin); //acc1 X-axis
  int acc1_yRead = analogRead(acc1_yPin); //acc1 Y-axis
  int acc2_xRead = analogRead(acc2_xPin); //acc2 X-axis
  int acc2_yRead = analogRead(acc2_yPin); //acc2 Y-axis

  //convert read values to degrees -90 to 90 - Needed for atan2
  int acc1_xAng = map(acc1_xRead, xAcc1_minVal, xAcc1_maxVal, -90, 90);
  int acc1_yAng = map(acc1_yRead, yAcc1_minVal, yAcc1_maxVal, -90, 90);
  int acc2_xAng = map(acc2_xRead, xAcc2_minVal, xAcc2_maxVal, -90, 90);
  int acc2_yAng = map(acc2_yRead, yAcc2_minVal, yAcc2_maxVal, -90, 90);

  //Caculate 360deg values like so: atan2(-yAng, -zAng)
  //atan2 outputs the value of -π to π (radians)
  //We are then converting the radians to degrees
  acc1 = RAD_TO_DEG * (atan2(-acc1_yAng, -acc1_xAng) + PI); //acc1 in degrees
  acc2 = RAD_TO_DEG * (atan2(-acc2_yAng, acc2_xAng) + PI); //acc2 in degrees

  if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <= 40))
  {
    digitalWrite(13, HIGH);
    Serial.println("HIGH");
  }
  else if ((acc1 >= 41 && acc1 <= 60) && (acc2 >= 41 && acc2 <= 60))
  {
    digitalWrite(13, LOW);
    Serial.println("LOW");
  }

  Serial.print("Acc1: ");
  Serial.print(acc1);
  Serial.print(" Acc2: ");
  Serial.print(acc2);
  delay(1000);

}

I'd really appreciate any input as to way the if statements are not working when I have 2 conditions in them but will work when I have 1 condition.

Edit:
I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially.
The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.

I think this is your problem (from the full code snapshot)

(acc2 >= 20 && acc2 >= 40))

I believe it should be (like your first snapshot)

(acc2 >= 20 && acc2 <= 40))

Note that the first is greater than or equal to 40 rather than less than or equal to. Also note you've done this when determining whether or not acc2 is between 41 and 60 in the else if part of that same if statement.

I have no idea why the code differs between your first and third snapshot. Potentially you have spotted this already and failed to update the full code being run?


Receiver xbee receiving data even if the Transmitter is not sending? TX code:

#include <SoftwareSerial.h>

const int MAX_LENGTH = 2;
char buffer[MAX_LENGTH];
char lineFeed = 2;

SoftwareSerial   Xbee(10, 11);

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

void loop() {
  int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
  int i = 0;
  while( i < length )
  {
    Serial.print(buffer[i]-48);
    Xbee.print(buffer[i]-48);
    i++;
  }
}

RX code:

const int MAX_LENGTH = 2;
char buffer[MAX_LENGTH];
char lineFeed = 2;

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

void loop() {
  int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
  int i = 0;

  while( i < length )
  {
    Serial.print(buffer[i]-48);
    i++;
  }
}

NOTE :

1- The Rx xbee is receiving data even if am not sending and even if the TX xbee is powered off

2- When i send data from the TX xbee id didn't get revived by the RX xbee

I need to solve both problems.

*** What i need exactly is to send serial data from my pc to arduino and send it wireless through xbee and then receive to the other arduino connected to my circuit

The reason that it is printing characters with no input is that the readBytesUntil function has a timeout. If no new characters are received for a certain amount of time, "Serail.setTimeout()" seconds, it will just continue with the code. the default timeout is 1 second.

The reason you are not receiving what you transmit (or at least a reason) is that the RX code does not read from an xbee, but reads from regular "serial".

I recommend you try something simple first to test the xbee's configuration, like having TX run this:

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

and RX run something to echo serial like this:

 void loop(){
     if(xbee.available()){
         Serial.print((char)xbee.read());
     }
}

And make sure you set up an xbee object an the receiving side first.


Is it possible to connect a 36 pin 4 digit 7 segment display on an Arduino Uno R3? First of all,here's the datasheet of the 4 digit 7 segment display that I'm using:
http://www.kingbrightusa.com/images/catalog/SPEC/ca56-11ewa.pdf

How can I make a counter or a clock out of this particular led display,considering the fact that I don't have enough digital pins to manipulate led's pins?

Only need 4, or 5 pins; SCK (D13), MOSI (D11), slave select (D10).
Maybe PWM (D9) for brightness.
D12 not used, but is tied up as part of SPI bus.

Connect the Anodes to +5.

Connect the cathodes, with a current limit resistor per cathode, to the outputs of 4 TPIC6C595, or TPIC6B595.

For the resistor, assume worst case voltage drop of 2V and 20mA current draw:
(5V - 2V)/.02A = 150 phm.

Use a PWM output pin to drive the OE/ pin of the '595s for brightness control.

Then shift data into the daisychained shift registers as an update is needed.

byte dataMap[] = {
0b00111111, // 0 with bits representing DP,g,f,e,d,c,b,a
0b00000110, // 1
0b01011011, // 2
// etc
};

where segments are layed at as

   a
f     b
   g
e     c
   d      DP or colon

then call the array in loop(), make it a function if you want.

digitalWrite (ssPin, LOW); // D10 on Uno, used as Latch signal
for (x = 0; x <4; x=x+1){
SPI.transfer (mapArray[digit0]); // digit0 value mapped to segments
SPI.transfer (mapArray[digit1]);
SPI.transfer (mapArray[digit2]);
SPI.transfer (mapArray[digit3]);
}
digitalWrite (ssPin, LOW); // outputs update on this rising edge

I wonder where DP5, DP6, which make the colon, are? I don't see them in the pinout.


Arduino ESC controlled motor has issues I have a brushless motor what is hooked up to a external power supply and I'm using an arduino with a potentiometer to control it. I know that the motor has power but whenever I turn the potentiometer nothing happens. I'm wondering if my wiring is wrong. Here's the wires is connected:

First pin of the potentometer to arduino GND
Second pin of the potentometer to arduino A0
Third pin of the potentiometer to arduino 5V

Black wire of the ESC to arduino GND
Red wire of the ESC to VIN
White wire of the ESC to D8

I'm also using a switch to give both the arduino and motor power and they both seem to turn on fine.

Motor has external power and does twitch very slightly when powered on with this circuit but I can't get is to actually move substantially using the potentiometer.

Here's my code:

#include <Servo.h>//Using servo library to control ESC
Servo esc; //Creating a servo class with name as esc
void setup()
{
esc.attach(8); //Specify the esc signal pin,Here as D8
esc.writeMicroseconds(1000); //initialize the signal to 1000
Serial.begin(9600);
}
void loop()
{
int val; //Creating a variable val
val= analogRead(A0); //Read input from analog pin a0 and store in val
val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(Change if needed)
esc.writeMicroseconds(val); //using val as the signal to esc
}

It would seem you are attempting to power the motor's coils from VIN of the Arduino. If you are powering the whole system from USB or from the barrel connector on the Arduino, then it's likely that the small voltage regulator on the Arduino cannot supply sufficient current to the motor.

You should connect the black and red wires of the ESC directly to a high-current power supply, and ensure the black (GND) wires of the ESC, power supply, and Arduino are tied together.


How can you speed up the ADC on an ATtiny85? I'm reading input from a camera and trying to reach a fast frame rate. Problem is my ATtiny85 has a pretty slow conversion time (65 - 260 µs Conversion Time). Is there any way to make this faster? I heard that you can set-up a prescaler for the analogRead() method by doing the following:

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

void setup()
{
  #if FASTADC
   // set prescale to 16
   sbi(ADCSRA,ADPS2) ;
   cbi(ADCSRA,ADPS1) ;
   cbi(ADCSRA,ADPS0) ;
  #endif

  /*Rest of the code goes here.*/
}

I can't really make sense of the code and I found it on a less then reliable website so I was wondering if any of the gurus on here could let me know if what I'm attempting is possible and if this is the proper way of achieving my goal.

Also, would this also work for the Arduino Mega? I'm currently using it to test and debug my project since the ATtiny84 doesn't have serial output.

Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

The ADCs in the ATtiny85 and ATmega2560 (the chip powering the Arduino
Mega 2560) are pretty similar, except for the Mega having more inputs.
In particular, the way you set the clock prescaler is the same, namely
the bits ADPS2:0 in the register ADCSRA. You could use the same code to
set the prescaler on both chips, but you probably don't want to unless
your ATtiny is clocked at 16 MHz, like your Mega. I would normally
just set the control register to the value I want, rather than
touching only a few bits, but that is a matter of personal preference.
So, to set the ADC clock of the Mega to 1 MHz, I would

ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS2);  // clock at F_CPU / 16 = 1 MHz

The same code would do the same thing on an ATtiny clocked at
16 MHz. If the ATtiny runs at 8 MHz, I would instead

ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS1)   // clock at
       | _BV(ADPS0);  //     F_CPU / 8 = 1 MHz

If you want to be generic:

#if F_CPU >= 12000000
# define ADPS_SETTING _BV(ADPS2)                 // F_CPU / 16
#else
# define ADPS_SETTING (_BV(ADPS1) | _BV(ADPS0))  // F_CPU / 8
#endif

ADCSRA = _BV(ADEN)      // enable the ADC
       | ADPS_SETTING;  // clock somewhere near 1 MHz

As bigjosh explained in comments, the prescaler setting is a trade-off
between speed and accuracy. I recommend you read the article on the
Arduino ADC by Nick Gammon. He did some tests at various speeds
which showed that you can get decent results with clock speeds up to
1 MHz, then it becomes pretty bad at 2 MHz and mostly
useless beyond. You may want to run the same tests with your particular
setup.

Except for the very first conversion, which takes longer, an ADC
conversion takes 13 cycles of the ADC clock. If you run that clock
at 1 MHz, that is 13 µs per reading. If you get the readings
with analogRead(), you won't get one reading every 13 µs, because
the CPU needs extra time to execute the code you have between successive
calls of analogRead(). You can save time by having the CPU and the ADC
work in parallel, maybe along these lines:

ADCSRA |= ADSC;     // start the first conversion
for (int i = 0; i < NB_READINGS; i++) {
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait for the ADC
    uint16_t reading = ADC;     // get the reading
    ADCSRA |= ADSC;             // start the next conversion
    process(reading);           // process the reading we have
}

This way you process one reading while the ADC is taking the next one.
Or you can set the ADC to “free running mode” (where it takes one
reading after another without ever stopping) and get the readings in an
interrupt service routine. Whichever method works best depends on your
particular application: the amount of works your CPU has to do while
reading the ADC and whether you can afford to do the whole series of
readings with interrupts disabled.


Arduino does not boot when SPI lines are loaded i connected an Arduino Nano to an external SPI Flash using THIS tutorial (russian) and the SPIMemory library. While accessing the Flash works well, i have encountered the following issue:
The Problem: When the SPI MISO line is pulled high by the flash while the Arduino boots, it does not start, for example because it was rebooted while accessing the flash. I have to power down the Flash before it boots again. But even then, it takes unusually long to boot.
I know that the Atmega328p allows reprogramming via SPI, but to my knowledge this should not cause this behavior since the SPI lines do not change (starting the programming mode would require a command to be sent immediately after restart). Is there any way to prevent this behavior? (Except disabling SPI programming via fuse bits, this would be my last choice)
EDIT
Programming the Arduino via ISP does work, however i added some series resistors to the flash to prevent accidentally driving the SPI lines from multiple sources.
The problem seems to come from the MISO line, when it is pulled to VCC the Arduino does not start. This is not mentioned in the data sheets anywhere and i am not sure how to prevent this (sketch below to show the wiring).

I honestly can't imagine why a sketch like that would hang in this scenario. But I'm confident that my answer can solve the issue.
My guess is that the following happens:
The flash is selected (CS pulled low by atmega) at the moment at which the reset happens. At this moment, the master will stop generating a clock signal and CS will be floating.
Thus, the flash will not be deselected reliably due to the floating CS and MISO will remain in the state it was before the reset occured (HIGH if it was transmitting a logic 1, LOW for 0). Basically, the SPI communication of the flash will be stuck with MISO being actively pulled to logic high or low.
IDK why this causes the sketch to freeze, but if you add a pullup resistor to the flash's CS, it should be deactivated by default (and also after a reset of the atmega as pins will be inputs/floating by default). As a result, the flash can not actively pull MISO and should therefore barely affect the atmega at all.
I suggest you add the mentioned pullup and see if that makes any difference. If it doesn't I'm going to delete this answer, but it was a bit too long for a comment ;).
Edit: I also just saw that you are missing the pullup resistor on the reset pin. That could well be the actual problem.


Shift Register 74HC595 not working I am trying to learn how to make a shift register work. I have been working off of the Arduino ShiftOut tutorial.

My issue is that the shift register isn't working when the circuit is powered and I am not sure what is wrong. I suspect the issue is with pins 10-13 on the 74HC595?

I have done this with an actual board and the 123d.circuits.io simulator with the same result:

http://123d.circuits.io/circuits/444111-shift-register

The code is very simple and taken from the tutorial:

// SH_CP; 11
const int clockPin = 9;
// DS; 15
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 10;

void setup() {
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  Serial.begin(9600);
  Serial.println("reset");
}

void loop() {
  for (int number = 0; number < 256; number++) {
    Serial.println(number);
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, number);
    digitalWrite(latchPin, HIGH);
    delay(500);
  }
}

Solution: Remove ground from Q0 as Gerben correctly pointed out in comments.

Also: rotate LEDs 90 degrees so that the anode and cathode are on different rows.

What was tripping me up is in the Arduino tutorial diagram is a little unclear on this (I now understand why their way is correct and my way (in the question) was wrong:


Why doesn't my LEDs turn on? i have just started learning Arduino, so please be patient to me :)

Why doesnt my circuit below doesn't work?

Here's the code:

#define led_green 2
#define led_yellow 8
#define led_red 13

void setup() {
  pinMode(led_green, OUTPUT);
  pinMode(led_yellow, OUTPUT);
  pinMode(led_red, OUTPUT);

  // Strarting all turned off
  digitalWrite(led_green, LOW);
  digitalWrite(led_yellow, LOW);
  digitalWrite(led_red, LOW);
}

void loop() {
digitalWrite(led_red, HIGH);

delay(1000);

digitalWrite(led_red, LOW);
digitalWrite(led_green, HIGH);

delay(1000);

digitalWrite(led_green, LOW);
digitalWrite(led_yellow, HIGH);

delay(1000);

digitalWrite(led_yellow, LOW);

}

I'm trying to reproduce this circuit that I saw in a tutorial:

Thank you.

If you are doing what is in the first picture then you're doing it wrong.

You have to make sure the led is horizontal, not vertical. The signal is going through the led and not making it into ground. And your ground is in the same lane as your signal.

I think you should learn how breadboards work and then move on from there. Its pretty simple and I think you'll learn it quickly.

For your code part, instead of defining the variables, you could just use int.
 Refer to this as a starter tutorial, https://www.arduino.cc/en/Tutorial/.

This is how your wiring should look like if you followed the tutorial,


Serial communication between nodemcu and Arduino Uno For the last days, I am trying to establish serial communication between nodemcu and Arduino Uno but I failed to do this. Currently, I am working on a Home Automation project. I receive data from nodemcu and send it to Arduino Uno, but some dummy data also receive with original data. Please help.
Nodemcu code:
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

#define Automated   D0
#define Led         D1
#define Fan         D2

#define WLAN_SSID       "JioFi2_1EAFF8"
#define WLAN_PASS       "Ode9c@,1S%31ja$1xANkeL"

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
#define AIO_USERNAME    "_inishu"
#define AIO_KEY        "aio_HZUG00TupkcsC2dvraQM7HLHrCd4"

WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

Adafruit_MQTT_Subscribe speed = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Fan");
Adafruit_MQTT_Subscribe inten = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Led");
Adafruit_MQTT_Subscribe autom = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Automate");

void MQTT_connect();
void datatransfer(int);

int on_off;
int sliderval1;
int sliderval2;
void setup(){
    Serial.begin(9600);
    pinMode(Automated, OUTPUT);
    pinMode(Led, OUTPUT);
    pinMode(Fan, OUTPUT);

    WiFi.begin(WLAN_SSID, WLAN_PASS);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
    }

    mqtt.subscribe(&autom);
    mqtt.subscribe(&speed);
    mqtt.subscribe(&inten);
}

void loop (){
    MQTT_connect();

    Adafruit_MQTT_Subscribe *subscription;
    while ((subscription = mqtt.readSubscription(5000))){
        if (subscription == &autom){
            on_off = atoi((char *)autom.lastread);
            if (on_off == 1)   digitalWrite(Automated,HIGH);
            if (on_off == 0)   digitalWrite(Automated,LOW);
        }

        if (subscription == &speed){
            sliderval1 = atoi((char *)speed.lastread);
            analogWrite(Fan, sliderval1);
        }

        if (subscription == &inten){
            sliderval2 = atoi((char *)inten.lastread);
            analogWrite(Led, sliderval2);
        }
    }
    datatransfer(on_off);
    datatransfer(sliderval1);
    datatransfer(sliderval2);
}

void MQTT_connect() {
    if (mqtt.connected()) {
         return;
    }

    while (mqtt.connect() != 0) {
        mqtt.disconnect();
        delay(2000);
    }
}

void datatransfer(int value){
    Serial.println(value);
    delay(500);
}

Arduino Uno code:
int x = A0, y = A1, z = 1;
int fan = 11, led = 10;
float temp, lux;
int autom = 1;
int inten = 0;
int speed = 0;
int fanspeed, light;

int datareceive(){
    int receiver = 0;
    while(Serial.available()==0 );
    String s = Serial.readStringUntil('\r');
    receiver = s.toInt();
    Serial.println(receiver);
    delay(1000);
    return receiver;
}

void setup(){
    Serial.begin(9600);
    pinMode(fan,OUTPUT);
    pinMode(led,OUTPUT);
    pinMode(x,INPUT);
    pinMode(y,INPUT);
    pinMode(z,INPUT);
}

void loop(){
    autom = datareceive();
    speed = datareceive();
    inten = datareceive();
    if(autom == 1){
        fanspeed = 255 - speed;
        light = 255 - inten;
        analogWrite(fan,fanspeed);
        analogWrite(led,light);
    }
    else {
        temp = analogRead(x);
        if (temp >= 52 && temp <= 104){
            int fanspeed = -4.90384615*temp + 510;
            analogWrite(fan, fanspeed);
        }
        else if(temp > 104)  digitalWrite(fan,LOW);
        else digitalWrite(fan,HIGH);
        lux = analogRead(y);
        if (lux >= 430 && lux <= 594){
            int light = 1.342657*lux-577.342657;
            analogWrite(led,light);
        }
        else if (lux < 430) digitalWrite(led, LOW);
        else digitalWrite(led,HIGH);
    }
}

Arduino UNO is 5v logic and esp8266 is 3.3v logic.  You need a level shifter for them to be able to have bidirectional serial link.


How to use the additional SPIs on Arduino Due According to the following image it is possible to use a second SPI bus on the Arduino Due by using Serial1 and SCL1 as SCK0 for SPI (or Serial2 and SCK1).

source

However I did not find the code necessary to set up the additional SPI interfaces. I would prefer using these SPI interfaces as they are accessible on the stacking headers in contrast to the default SPI.

Additionally can a SD-Card be accessed using these SPI buses while still using the corresponding Arduino Library?

I think the information you are looking for can be found at https://www.arduino.cc/en/Reference/DueExtendedSPI

There are two other alternatives that I can see: if your device supports slave select (which I think they are supposed to), then you can use a different pin to select either device 1 or device 2 (or 3...).

The other options is that if you can connect the clock to only one slave at a time (again, with another pin), you should get the same result - you should be able to use a MOSFET between the Arduino's clock-out and the slave's clock-in, and hook the MOSFET's gate to a spare pin; repeat the procedure, using a separate MOSFET, connected to a different spare pin, to the second slave; then bring one or the other "spare pin" high, to select which way the clock goes. If a slave does not receive a clock, it will not listen for incoming signal. This last one I dreamed up; I don't know if it will work.


Why won't my iMac recognize my Mega32u4 Arduino Pro Micro board (I've tried several cables)? I bought this Pro Micro on eBay a while back, and I never really got around to using it. But now that I do my iMac won't recognize the board. I plug it into my iMac and open Arduino and go to the board tab, and it doesn't even have a Pro Micro choice, so I just choose Micro.

In ports it isn't showing up like my other boards do. Is it my computer, because my Chinese clone Uno and Mega weren't being recognized a while ago? I downloaded the CH340 chip driver for them because they used the CH340 chip and now they are recognized and work perfectly!

The thing is the Pro Micro does not use that chip so is there something else I have to do like another driver to download? It is not the cable because I have tried 5 cables and some had the symbol with the circle triangle and square connected on them, which is the usb serial symbol I think, so they aren't just power cables. If anyone knows what the problem is, that would be awesome! Here is the error it gives me when I try to upload it.

 Arduino: 1.6.9 (Mac OS X), Board: "Arduino/Genuino Micro"

failed MSpanList_Insert 0x31dea0 0x29ab70fa1fa 0x0
fatal error: MSpanList_Insert

runtime stack:
runtime.MSpanList_Insert(0x2c70d0, 0x31dea0)
/usr/local/go/src/runtime/mheap.c:692 +0x8f
runtime.MHeap_Alloc(0x2c6d20, 0x6, 0x10000000034, 0xf989)
runtime.MCentral_CacheSpan(0x2d10d8, 0x30c270)
/usr/local/go/src/runtime/mcentral.c:85 +0x167
runtime.MCache_Refill(0x308000, 0xc200000034, 0x30c270)
/usr/local/go/src/runtime/mcache.c:90 +0xa0

 goroutine 1 [running]:
 runtime.switchtoM()
/usr/local/go/src/runtime/asm_amd64.s:198 fp=0xc2082b7468          sp=0xc2082b7460
 runtime.mallocgc(0x2200, 0x19ff80, 0x0, 0xc2080d68e9)
/usr/local/go/src/runtime/malloc.go:178 +0x849 fp=0xc2082b7518     sp=0xc2082b7468
 runtime.newarray(0x19ff80, 0x20, 0xa5ca)
/usr/local/go/src/runtime/malloc.go:365 +0xc1 fp=0xc2082b7550    sp=0xc2082b7518
 runtime.hashGrow(0x1b4300, 0xc2080dc150)
/usr/local/go/src/runtime/hashmap.go:744 +0x86 fp=0xc2082b7580    sp=0xc2082b7550
 runtime.mapassign1(0x1b4300, 0xc2080dc150, 0xc2082b7698, 0xc2082b7688)
/usr/local/go/src/runtime/hashmap.go:456 +0x568 fp=0xc2082b7620  sp=0xc2082b7580
  arduino.cc/builder/props.PropertiesMap.Merge(0xc2080dc150,      0xc2082b7748, 0x1, 0x1, 0x3)
/Users/jenkins/jenkins/workspace/arduino-builder-     macosx/src/arduino.cc/builder/props/properties.go:162 +0x153     fp=0xc2082b7718 sp=0xc2082b7620
 arduino.cc/builder/props.PropertiesMap.Clone(0xc20803ce40, 0xb2f5f)
/Users/jenkins/jenkins/workspace/arduino-builder-    macosx/src/arduino.cc/builder/props/properties.go:170 +0xad fp=0xc2082b7770     sp=0xc2082b7718
 arduino.cc/builder.(*RecipeByPrefixSuffixRunner).Run(0xc20801e300,     0xc208068000, 0x0, 0x0)
/Users/jenkins/jenkins/workspace/arduino-builder-    macosx/src/arduino.cc/builder/recipe_runner.go:53 +0x2c4 fp=0xc2082b78e8    sp=0xc2082b7770
arduino.cc/builder.runCommands(0xc208068000, 0xc2082b7af8, 0x1c, 0x1c,     0xc208038001, 0x0, 0x0)
/Users/jenkins/jenkins/workspace/arduino-builder-   macosx/src/arduino.cc/builder/builder.go:181 +0x139 fp=0xc2082b7978    sp=0xc2082b78e8
 arduino.cc/builder.(*Builder).Run(0xc2082b7ce0, 0xc208068000, 0x0,   0x0)
/Users/jenkins/jenkins/workspace/arduino-builder-  macosx/src/arduino.cc/builder/builder.go:116 +0xe8e fp=0xc2082b7cc0   sp=0xc2082b7978
 arduino.cc/builder.RunBuilder(0xc208068000, 0x0, 0x0)
/Users/jenkins/jenkins/workspace/arduino-builder- macosx/src/arduino.cc/builder/builder.go:212 +0x49 fp=0xc2082b7ce8  sp=0xc2082b7cc0
 main.main()
/Users/jenkins/jenkins/workspace/arduino-builder-   macosx/src/arduino.cc/arduino-builder/main.go:316 +0x171b fp=0xc2082b7f98    sp=0xc2082b7ce8
 runtime.main()
/usr/local/go/src/runtime/proc.go:63 +0xf3 fp=0xc2082b7fe0   sp=0xc2082b7f98
 runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1 fp=0xc2082b7fe8    sp=0xc2082b7fe0
arduino-builder returned 2
Error compiling for board Arduino/Genuino Micro.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

From what you say here:

  I plug it into my iMac and open Arduino and go to the board tab, and it doesn't even have a Pro Micro choice, so i just choose Micro.

and from the dump you provide:

  Arduino: 1.6.9 (Mac OS X), Board: "Arduino/Genuino Micro"

It looks to me like you're selecting the wrong board. Instead of just picking a "similar" board from the Tools menu, what you should do is add the Sparkfun board manager package and then select the Pro Micro from it.

Here you can find the procedure step by step. Follow it and you should be all set.

EDIT:

If you tried to upload a sketch with a wrong board selection, then your your Pro Micro may have become "bricked". In order to unbrick it, follow this procedure (same link as above, different section).

Once you unbrick it, upload the specific blink example code for Pro Micro that you can find in another section of the same link.

If it keeps not working, READ THE ENTIRE ARTICLE linked and try out all troubleshooting instructions before anything else.