Problem Uploading to arduino uno board I have an arduino uno. Whenever I try to upload code to the arduino I get this error.

avrdude: ser_open(): can't open device "/dev/cu.usbserial-AL01EI7I": Device not configured

ioctl("TIOCMGET"): Inappropriate ioctl for device Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

The error message is telling you that avrdude failed to open the device and read the modem status (basically the information about whether a device is present and ready on a serial line). The most likely causes of this are:

Using the wrong serial port (Tools > Port in the Arduino IDE).
The IDE not recognizing the board.
Using a power only USB cable.

The Arduino IDE seems to remember the device that your board was last connected through, but on some Unix flavored OSes the device name depends, in part, on method of connection – which port, hub or no hub, etc. So if you change the board or the port you plug it into, the name changes.

So, the very first thing to do is to look under  Tools > Port in the Arduino IDE to see if there is another device present. Also confirm that you're using a USB cable with data wires. There are "power only" USB cables…

Failing that, check to see if the OS sees the board. On OS X you would go to the Apple menu and choose About this Mac and then look at at the System Report to see what devices have been detected on your USB busses. I'd be surprised if there wasn't something similar on Linux (and Windows too for that matter). If you're comfortable on the command line you could look in /dev for devices with similar names.

If the board is present, but not seen by the Arduino IDE, try restarting the IDE and/or plugging and unplugging the USB cable. Sometimes it helps to plug the cable into a different port.


Guide to code for multitasking and non blocking timers I'm beginning to do kind of sophisticated things (well.. for my entry level skill) and I have to control a display with 3 LED and 4/5 types of events and status.
I'm using the BlinkWithoutDelay example duplicating all the variables for different status/events but the code is really messy, full of puzzling nested if statements.
How to simplify the things? I don't know what to choose, because OOP could be a choice but I think it will hurt the low-memory thing inside the Arduino Uno/Leonardo. Interrupts could be another choice but I think they are like threads, and following the KISS principle I'd like to stay away from them.
So, can someone advice me some article/tutorial/code-to-read/whatever to understand how to use a lot of LEDs and keep a lot internal status without screw my brain?
EDIT:
It is a little bit hard to reproduce a simple skelton of my messy code, but it looks like this (in pseudocode maybe)
void loop() {
    if(state==0) handleState0();
    if(state==1) handleState1();
    if(state==2) handleState2();
    if(state==3) handleState3();
    readButtons();
    readSensors();
    …
}

// this is a block of variables that I have to copy-and-paste
// every time I have to blink a led (hoping that there is
// nothing blocking that can skrew up everything)
unsigned long previousMillis_1 = 0;
const long interval_1 = 1000;
int ledState_1 = LOW;

void handleState1() {
  // Green led blinking, yellow is fixed
  // this is a copy-and-paste code hard to maintain,
  // easily broken from any blocking call (like also I2C)
  // and hard to refactor or isolate
  unsigned long currentMillis_1 = millis();
  if(currentMillis_1 - previousMillis_1 >= interval_1) {
    previousMillis_1 = currentMillis_1;
    if (ledState_1 == LOW) ledState_1 = HIGH;
    else ledState_1 = LOW;
    digitalWrite(pinGreen, ledState_1);
    digitalWrite(pinYellow, LOW);
}

unsigned long previousMillis_2 = 0;
const long interval_2 = 1000;
int ledState_2 = LOW;

void handleState2() {
  // Yellow led blinking, green is fixed
  // same as before
  unsigned long currentMillis_2 = millis();
  if(currentMillis_2 - previousMillis_2 >= interval_2) {
    previousMillis_2 = currentMillis_2;
    if (ledState_2 == LOW) ledState_2 = HIGH;
    else ledState_2 = LOW;
    digitalWrite(pinYellow, ledState_2);
    digitalWrite(pinGreen, LOW);
}

void handleButtonPressed() {
  // this skrew everything and because is blocking
  // and should be inserted in the main loop with
  // some global variables: active/disable, counter,
  // and non-blocking vars like previousMills, interval, etc etc
  Serial.println("\ndisplayAccessDenied");
  for(int i=0; i<3; i++) {
    digitalWrite(pinRed, LOW);
    delay(100);
    digitalWrite(pinRed, HIGH);
    delay(100);
  } digitalWrite(pinRed, LOW);
}

I feel a little bit lost but all the Arduino example arounds are super simple and to make a middle-level LED interface I have to screw my minds with something that is not working as 100% and other than Arduino I find only super-hard articles on microprocessors with low-level C code. But the pasted example is not working at 100% AND super hard to read, maintain, etc.

It is not really clear what you want here...

If you want to execute things in a certain time, then take a look at http://playground.arduino.cc/Code/Scheduler

Or, if you want more than just that (multiple tasks, preemptive multitasking) https://launchpad.net/arduos (arduOS can also just serve to run things in a certain time, but without having to use a function all the time)

While OOP MIGHT take more program memory, an object without virtual functions only takes the RAM the variables in it take (if you have a byte (1 byte) and an int (2 bytes) in an object it would take 3 bytes)

On the AVR-architecture (the one most Arduinos use) the program is directly executed from a flash-memory and only the variables are in the RAM

The if-state-handling you are doing there can be done easier using arrays like:

typedef void(*handler)(void)
handler stateHandlers[STATES] = {&handle1, &handle2, &handle3 ...
// handle? are functions without the () !
void handleState(int state)
{
    if(state >= STATES)
        return;
    stateHandlers[state]();
}

Obviously, you can also use arrays to store the states of the LEDs.

Also note that HIGH is just 1 and LOW is 0, so technically a bit would be enough to store the states.


Save some arduino pins when driving a 4 digits 7 segments display I built a simple clock using a 4 digits 7 segments LCD display. I display one digit at a time, switching on and off very quicky and cycling through digits.

Everything is ok, but I used 8 + 4 = 12 arduino pins. I need 2 more pins for other features and I don't want to use 0 and 1 as I need onboard programming features of Arduino Mini.

I used I2C for RTC clock, I could add some interface here (like a PCF8574) and get some pins from here. But I'd like a different (and more educational, for me) approach.

Is there an IC that sends an HIGH output on one of four output pins driven by 2 input pins? I need this:

IN     OUT
P0 P1  D0 D1 D2 D3
0  0   1  0  0  0
0  1   0  1  0  0
1  0   0  0  1  0
1  1   0  0  0  1

This way I can connect OUT to digit selection and spare 2 pins.

Thanks for your hints.

I know it's not what you asked, but you're using a lot of pins, why not try streamlining them and go to an I2C backpack? This one from adafruit includes a single 4x7 segment display.

given your comment, another option would be an I2C/SPI 7 Segment driver. (datasheet).

new edit: Actually, when I posted the above 7 segment driver, this is the one I was thinking of. I don't know why I didn't find this the first time.

max7219/7221 datasheet and digikey source:


Multiple Stepper Motors in One Shield? I need to construct 4 reactors for an experiment requiring mixing. We want to automate the mixing and at the same time reduce cost. can we connect multiple stepper motors with 5 or 6 wires on one shield version 2?

Depending on the shield you can connect an external powersource through mosfets or transistors (Depending on the size of the steppermotor).

But if it is smaller motors with a 12v powersource, i really don't se why you would do that, since stepper motor controllers cost about $2-$4 each. Being cost effective i think that writing this question would cost more than actually just go and buy 6-8 controllers. (Don't buy the shield ones, they are overly expensive)


Powering Arduino Uno from 5V pin, what exactly is the voltage range/tolerance? I want to bypass the onboard regulator and use the 5V pin to feed arduino with external, regulated source.

Everybody just keeps saying regulated 5V, but how precise does the regulation need to be exactly? Can you state a voltage range and what makes you think so?

10 ways to destroy arduino, Method #5: Apply >5V to the 5V Connector Pin mentions "applying more than 6V", can anyone elaborate how it can be calculated?

Is there a higher spike that arduino can handle for a short period of time?
My concern is that the current draw from arduino might be under 60mA (right after switching power on and before the program initilizes and starts running), which is the lowest draw at which my source guarantees the 5V regulation --- when unloaded it gives out 6.5V. How could I resolve this better than putting a 60mA dummy load between the regulator and arduino itself?

Unfortunately there is no one "clear cut" answer for all you ask.

There are some hard limits, though, which you can get from the main chip's datasheet:

  Operating Voltage: 1.8 - 5.5V

But that's not the whole story. The minimum voltage depends on the clock speed of the chip, as shown in this graph:

But wait, there's more. The Arduino also contains a 3.3V regulator which is fed from the 5V supply. That will have a minimum voltage above 3.3V that it needs to maintain a 3.3V output. So if you want to use the 3.3V regulator then, according to the datasheet for the regulator (LP2985-33DVBR):

  3 Description
  The LP2985-N low noise linear (LDO) regulator delivers up to 150mA output current and only requires 300mV dropout voltage of input to output.

So a minimum of 3.3 + 0.3V, or 3.6V.

That gives you a usable range, clock frequency permitting, of 3.6V to 5.5V.

As to how to protect the Arduino from a power-on spike like you describe - you could:

Add your own extra regulation in the form of a 5.1V zener diode.
Add a dummy load which the Arduino can switch out of the circuit once booted up
Change your source to something with better regulation
Ignore it - the regulation with even a light load will be considerably better than open circuit.  Add a resistor across your supply that would draw much less than 60mA and measure the voltage. See how bad the regulation at low load is.


How to start a block of code after a certain time? I'm using a ATMega328P-PU on a breadboard as an arduino. How do you start a code after say 20 seconds have elapsed since startup?
Example code:-

if(condition)
{
     //Start sending morse code!
}

My current code uses millis() and fails miserably. The speaker does not get activated. I'm using the standard circuit mentioned at the Arduino website
My current code:-

time = millis();
  if(time>=20000)
      txEnable=true;
      val = analogRead(analogPin);
  if(val!=0)
  {
    standby=false;

  }
  else
  standby=true;
  if(txEnable==true && standby==true)
 {

  if(!callsignSender->continueSending())
    {
        callsignSender->startSending();
    }

 }

The following bare-minimum code will switch pin 13 to high after 20 seconds:

void setup() {
  // assuming pin 13 has a LED connected (as on most Arduino boards)
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW); // would also work without this line
}

void loop() {
  unsigned long time = millis();
  if (time >= 20000) {
    digitalWrite(13, HIGH);   // set the LED on
  }
}

Try if this works for you, i.e. if a LED connected to that pin will light up 20 seconds after reboot.

If not you will need to find the problem: Is your ATmega running at the correct speed? Is your code executed at all? Are the peripherals working?


Wiring an IR blaster+receiver board I've salvaged this small IR blaster+receiver board from an old computer toy:

As you can see the board was connected to the main unit via a 4-wire cable labelled like this:

LED (yellow) (I guess this is the IR LED/blaster)
IR (white) (I guess this is the IR receiver)
VCC (red)
GND (black)

I'd like to use this board with an Arduino library like IRremote, but I am not sure about the VCC voltage and whether I need to add more components on the Arduino side.

UPDATE:
I've checked the LED with a multimeter and indeed it is a visible bicolor LED, so there is no IR blaster in this board. At this point, is there any good reason to keep the IR receiver on the board rather than just cutting it and reusing as a standalone component?

You solved your problem.

You said

  I checked the LED with a multimeter and indeed it is a visible bicolor
  LED, so there is no IR blaster in this board.

So, be kind, accept this answer so we can close your question.

I'm posting, not comment, only to get this out of the "unanswered".


Trying to track down macro or #define values, possibly in arduino preprocessor In reading various code I stumble across symbols that seem to be the result
of #define or other macro like symbols that I cannot find just by tracking
through the code ( including its chain, if any, of includes ).

Can someone offer some reasonably simple, but complete, guidance on how the
arduino ide works with especially emphasis on automatically included files
( and their location ) and any other automagically appearing stuff.

It might help to point out the use of -D switches of gcc here.
If you turn on verbose output of the Arduino IDE (I am using a pretty old version):

you will see, when you compile a sketch, that the compiler is not only called with a switch -m (e.g.  -mmcu=atmega328p) which describes the target (i.e. the ATMEL AVR instruction set or MCU type) for which the code is compiled, but also with a number of -D switches.

The -D switches predefine a name as a macro and also that depend on the target.

You might see for example

-DF_CPU=16000000L -DARDUINO=100

where F_CPU is used to pass information about the target's clock speed (16 MHz in this case) to code that depends on this, e.g. the delay function or the Serial library.

3 ways to define macros

In general, the confusion might come from the fact that including files in the Arduino build chain depends a lot on compiler flags, and there are several ways to define these:

#define
using -D switches
from the target specification (compiler built-in, -m)

The last point means that the above mentioned -matmega328p defines the macro __AVR_ATmega328P__ which is e.g. used in io.h to include the appropriate file with pin mappings, RAM sizes etc. (Google for avr-mcus.def to find a full list of these predefined macros for AVR targets.)

Finally, note that the Arduino IDE also sets include paths depending on the target. The appropriate set of pin definitions is selected by passing an include path like this to avr-g++:

-I/usr/share/arduino/hardware/arduino/variants/standard

where standard is replaced by leonardo, micro, mega etc.

Short answer / summary / how to debug

First, to generate a list of the current #define directives, use the -dM option like this (compiling an empty program that is specified to be C with -x c):

echo | avr-gcc -x c -E -dM -mmcu=atmega328p - | sort

Change -mmcu=atmega328p to your needs (you can also leave it out).

Second, you can use the option -g3 to include the macro definitions in the output. Keep the intermediate files by using -save-temps. You can append these to the compiler call by the IDE:

avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega168 -DF_CPU=8000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build5017602110288.tmp/SerialManual.cpp -o/tmp/build5017602110288.tmp/SerialManual.cpp.o -save-temps -g3

which will create a long output file *.ii (here SerialManual.ii) that lists among others the defines and typedefs and, most importantly, from which files they come.

Sample output:

# 1 "/tmp/build501760211028815624.tmp/SerialManual.cpp"
# 1 "/tmp/1//"
# 1 "<built-in>"
#define __STDC__ 1
#define __cplusplus 1
#define __AVR_ATmega168__ 1
#define __CHAR16_TYPE__ short unsigned int
...
# 1 "<command-line>"
#define F_CPU 8000000L
#define ARDUINO 100
...
# 1 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 1 3
# 34 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 3
#define _AVR_IOM168_H_ 1
#define SPM_PAGESIZE 128
#define RAMSTART (0x100)
#define RAMEND 0x4FF
#define XRAMEND RAMEND
#define E2END 0x1FF
#define E2PAGESIZE 4
#define FLASHEND 0x3FFF
...


Sainsmart Omron 12V optocoupled 2 channel relay problem I know that there are plenty of questions related to relays, but I have to ask. I am trying to sort out the issue and spend hours reading but cannot make progress.

I have SainSmart 2-Channel 12V Relay Module for Arduino and wired it according to picture.

Arduino UNO R3 board is powered from 12V plug external power supply. I take that 12V to power JD-VCC on relay (from VIN). Arduino 5V is used to power optocoupler circuitry.

I want to use to power 12/24/220V devices (on picture I wired 6V battery for troubleshooting).

So, when I set PIN7 to LOW i would expect that fan spins up. LED on relay goes RED, so I expect it is sign that relay is activated. However, fan does not power on.
When I bring PIN7 to HIGH, I hear click; LED goes OFF. I assume it deactivated relay. All the time I have 6V on voltmeter.

What I am doing wrong?
I really tried to find answer around, but either I do not see or it is not so obvious.

Thank you,

Lets troubleshoot this circuit:

The circuit diagram you put in your question shows a wire creating a short across the relay coil. Check this, as this will definitely stop your fan from spinning. However, I assume this is an error in the diagram.
The picture on the website shows a jumper link between VCC and JD-VCC. Make sure this is removed.
Check that the fan works when you power it directly from the 6V battery. The fan may work only at a higher voltage or run off of AC voltage. Also, the battery could be flat - measure its voltage when it is under a small load.
Drive the input circuitry directly off of 5V. That is connect VCC to 5V and then directly connect IN1 to GND. Open circuit the IN1 input to turn it off. Check that this direct driving opens and closes the relay contacts.
Check the 12V supply. Does the voltage drop significantly when the relay pulls in or out? Does it have enough current? "Each [relay] needs 15-20mA Driver Current" Measure it using your DMM in ammeter mode.
Check your wiring is correct. It sounds simple, but you will be surprised by how many times the wiring is the cause of the problem.
Measure the resistance of the relay contacts in both the open and closed states. Arcing or poor manufacturing can be causes for the contacts to not function as intended.


Debug-logging without using Serial.print and without WiFi In order to transmit text from the Arduino board to the HC-05 Bluetooth module, I have use Serial.print. However, I don't see a way to debug the code without using Serial.print to test the other features of the software. Is there another way to transmit text from the Arduino to the computer, and from the Arduino to the HC-05, simultaneously (and without WiFi)?

Yes, what version of Arduino are you using?

For Arduino Mega, you can use Serial.println for writing debug data and Serial1.println for communication with HC-05. (See Example: MultiSerial Example)
For other Arduino boards, you can use Serial.println for writing debug data and SoftwareSerial library for communication with HC-05. (See Example: SofwareSerial)


ESP8266 Arduino MQTT callback with dynamic topics I have a program that depending on user input, it creates one or several objects that will publish data to a MQTT broker, each one with a different topic. This is already done. The ESP8266 also has subscribe itself to the same topics it publishes.
Now, the problem is that I have to create a dynamic callback in the ESP8266 to read the all the posible arriving topics to which the ESP8266 has subscribed and I am having trouble with that.

The callback function model is:

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

// handle message arrived

}

The possible topics can be:

ObjectTL/TL_1

ObjectTL/TL_2

ObjectTL/TL_3

...

ObjectTL/TL_X

The number (TL_X) depends of the user input I mention at the beginning.
Thanks!

I think using sscanf may help you

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

  sscanf(data, "ObjectTL/TL_%d", dynamicTopicName);
  // handle message arrived
  your_dynamic_function(dynamicTopicName,byte* payload, unsigned int length)

}


problem using one function to blink different leds I wrote a function to blink an led using millis and want to blink multiple leds with the same function but with different delay intervals. When I call this function thrice to blink 3 different leds, all the leds blink with the shortest delay. As far my understanding is, functions can be reused if you want to perform same task but why doesn't it work in this case? It works incase I rename the function before calling it again.

Is it wrong to call single function more than once to perform same task but on different pins? How would you call a function without renaming it?

const int redLed = 10;
const int yellowLed = 11;
const int greenLed = 12;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(yellowLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
}

void loop() {
blinkLed(redLed, 1000);
blinkLed(yellowLed, 4000);
blinkLed(greenLed, 8000);
}

void blinkLed(int led, unsigned long timePeriod) {
  static unsigned long oldTime = 0;
  unsigned long newTime = millis();
  static boolean ledState = LOW;

  if (newTime - oldTime >= timePeriod) {
    oldTime = newTime;
    ledState = !ledState;
  }
  digitalWrite(led, ledState);
}

Edit: I have modified the function to not have shared variables but it just blinks redLed. why doesn't it work now? Here is the code:

const int redLed = 10;
const int yellowLed = 11;
const int greenLed = 12;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(yellowLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
}

void loop() {

  blinkLed(redLed, 1000);
  blinkLed(yellowLed, 4000);
  blinkLed(greenLed, 8000);
}

void blinkLed(int led, unsigned long timePeriod) {

  switch (led) {
    case 10:
      static unsigned long oldTime1 = 0;
      unsigned long newTime1 = millis();
      static boolean redState = LOW;

      if (newTime1 - oldTime1 >= timePeriod) {
        oldTime1 = newTime1;
        redState = !redState;
      }
      digitalWrite(led, redState);
          break;

    case 11:
      static unsigned long oldTime2 = 0;
      unsigned long newTime2 = millis();
      static boolean yellowState = LOW;

      if (newTime2 - oldTime2 >= timePeriod) {
        oldTime2 = newTime2;
        yellowState = !yellowState;
      }
      digitalWrite(led, yellowState);
          break;

    case 12:
      static unsigned long oldTime3 = 0;
      unsigned long newTime3 = millis();
      static boolean greenState = LOW;

      if (newTime3 - oldTime3 >= timePeriod) {
        oldTime3 = newTime3;
        greenState = !greenState;
      }
      digitalWrite(led, greenState);
      break;
  }
}

You want to let the LEDs blink concurrently.
Your static variables oldTime, and ledState are shared between the three LEDs.
So there is ony ONE ledState in your program but you need that state for each one.
Same applies for oldTime.

Resolve the this issue and your LEDs will blink as expected.

btw. you don't need the ledState as you can read its current state.


COM+ and COM- to RX and TX I want to connect a Hokuyo scanning range finder to an Arduino Mega, the outputs are labeled like this:

COM+
COM-
Input
Output
DC12/24
GND

I want to read its serial output with Arduino, please help me in details.
Thanks

You should specify what model of Hokuyo scanning range finder you have.  Some models are USB-interfaced, in which case  COM+ and COM- could possibly correspond to USB D+ and D- leads.

The Hokuyo URG-04LX has both USB and RS-232 interfacing.  The linked page shows the following pinout on CN1:

Pin No.   Signals                                Colors
1         N.C.                                   Red
2         N.C.                                   White
3         OUTPUT(Synchronous output)             Black
4         GND(5th pin of 9-pin, D-sub connector) Purple
5         RxD(3rd pin of 9-pin, D-sub connector) Yellow
6         TxD(2nd pin of 9-pin, D-sub connector) Green
7         0V                                     Blue
8         DC5V                                   Brown

Given that pinout, you would connect pin 5, RxD, to a TXD output on the Mega, and pin 6, TxD, to an RXD input on the Mega.  Note, before making any such connection, measure the output voltage on pin 6.  An ordinary Mega supports 0 V and 5 V levels for serial data, but standard RS-232 levels are lower and higher than that; for example, ±12 V.  If you connect  ±12 V RS-232 levels to your Mega, you will damage it.  The several Hokuyo documents I've looked at don't say whether they use traditional RS-232 levels (±12 V) or TTL levels (0-5 V).


Using While Loop For Accurate Delays I was trying to get the timing in between events right, (Event time is around 150ms and i need it to be accurate within +-1ms) and came upon this implementation. The actual application will not be affected by the roll over, but would like to see if any of you guys (experts) can point out any flaws in using an empty while loop for time events, besides slightly higher power consumption.

This implementation gave me very accurate time spacings:

unsigned long previousMillis = millis();
Serial.print("ONE: ");
Serial.println(millis());
while(millis() - previousMillis < 1000);
Serial.print("SECOND: ");
Serial.println(millis());

compared with...

Serial.print("ONE: ");
Serial.println(millis());
delay(1000);
Serial.print("SECOND: ");
Serial.println(millis());

Which yields some errors after every step.

There are many options for executing a task periodically. The most
straightforward is to use a slight variation of code given in the Blink
Without Delay[] Arduino tutorial:

const uint32_t PERIOD = 150000;  // 150 ms

void loop() {
    static uint32_t last_time;
    if (micros() - last_time >= PERIOD) {
        last_time += period;
        do_periodic_task();
    }
    do_other_tasks();
}

Note two changes relative to the code in the tutorial:

This is using micros() instead of millis(). This way the timing
resolution is 4 µs instead of 1 to 2 milliseconds.
last_time is updated as last_time += period instead of
last_time = micros(). This way, even if the periodic task got
delayed by the other tasks, these delays don't add up.

The timing will not be perfect: you will have both drift and jitter.
The drift comes from the inaccuracy of the ceramic resonator clocking
the microcontroller. These resonators have typically 0.5% frequency
tolerance, although the typical frequency error is more likely to be
around ±0.1% (i.e. 0.15 ms error in a 150 ms period). Note
that a poorly written code would add it's own drift, e.g. if you do
last_time = micros(), but this does not.

The jitter comes from the fact that the clock is checked only once per
loop iteration, and your periodic task can then be delayed by the other
tasks. The amplitude of the jitter is the maximum time taken by a loop
iteration.

Despite these imperfections, this would be my first choice unless I
really needed better timing accuracy.

If you need lower drift, one option is to calibrate your Arduino clock.
You measure how fast or slow it is, and you tweak the PERIOD constant
accordingly. For example, if you measure the clock to be 700 ppm
slow, you would fix it like this:

const uint32_t NOMINAL_PERIOD = 150000;  // 150 ms

// Adjust the period to account for clock drift.
const float FREQUENCY_OFFSET = -700e-6;  // -700 ppm
const uint32_t PERIOD = NOMINAL_PERIOD * (1 + FREQUENCY_OFFSET);

This technique allows you to tune the frequency with about 6.7 ppm
resolution, for a period of 150 ms. You cannot reasonably expect
anything better, as the frequency of the ceramic resonator is not very
stable anyway.

If you need lower jitter, one option is to perform a blocking wait:
you ask the processor to do nothing but wait until it's time to perform
the periodic task. This is similar to the code you posted in your
question:

void loop() {
    static uint32_t last_time;
    while (micros() - last_time < PERIOD) ;  // busy wait
    last_time += period;
    do_periodic_task();
}

This will not completely suppress the jitter, but it will reduce it to
just the time taken by the while loop. However, there is a big issue
with this way of coding: now your processor does nothing but the
periodic task. It may not be a problem right now, but as your project
grows, it is more than likely that at some point you will want to handle
extra tasks like, e.g. responding to some user input.

If you want to avoid completely blocking the processor on the busy wait,
yet you want the smallest possible jitter, you could try some sort of
compromise: you let the processor take care of other tasks until it is
almost time to perform the periodic task. Then you switch to the
blocking mode where the processor does nothing but wait for the clock.
Here, “almost time” would be defined by the maximum time your loop can
take:

const uint32_t MAX_LOOP_TIME = 2000;  // assume 2 ms

void loop() {
    static uint32_t last_time;
    if (micros() - last_time >= PERIOD - MAX_LOOP_TIME) {
        while (micros() - last_time < PERIOD) ;  // busy wait
        last_time += period;
        do_periodic_task();
    }
    do_other_tasks();
}

Another option, that has been mentioned in comments, is to trigger the
task by a timer. This will work if it is a very short task that can
safely be run with interrupts disabled. You have four 16-bit timers on
your Mega, so you can presumably spare one for timing this task. This
could be done with Timer 1 as follows (warning: untested code):

const int TIMER_PRESCALER = 64;
const float F_TIMER = F_CPU / TIMER_PRESCALER;
const float PERIOD = 150e-3;
const uint16_t TIMER_PERIOD = F_TIMER*PERIOD + 0.5;  // round to nearest

void setup() {
    TCCR1B = 0;            // stop the timer
    OCR1A  = TIMER_PERIOD - 1;
    TIFR1 |= _BV(OCF1A);   // clear TIMER1_COMPA interrupt flag
    TIMSK1 = _BV(OCIE1A);  // enable TIMER1_COMPA interrupt
    TCCR1A = 0;            // no PWM
    TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
           | _BV(CS10)     // clock at F_CPU / 64
           | _BV(CS11);    // ditto
}

ISR(TIMER1_COMPA) {
    do_periodic_task();
}

Note that TIMER_PERIOD will be 37500. If you want to tune it to
account for an inaccurate clock frequency, your tuning resolution will
be about 26.7 ppm.

The interrupt technique should get you sub-microsecond jitter most of
the time. However, every now and then the Timer 0 interrupt (the
one responsible for updating the millis() counter) will delay your
interrupts for a few microseconds. Beware also that some libraries can
delay interrupts for excessive amounts of time. Software Serial is an
infamous offender.


Why does this array have stored values in it even though I have not put any values in it? void alarm() {
  char keypressed4;
  char keypressed5;
  char keypressed6;
  char keypressed7;
  char disarmcode1[5];
  Serial.println("hi2");
  Serial.println(disarmcode1);

The array gets declared here and I print the values in the empty array. In the serial monitor I read this:

hi2
"c

I don't know why or how these values get put into the array. I have code later on that puts values into the array, but from where that point in the code is, no values should be in the array

Also I have an LCD screen hooked up too, and it prints a value of 0 at (2, 0).

The values haven't been "put" in the array. The array has been located in memory where those values (left over from some earlier operation, possibly as part of a function's stack frame) happen to be.

The simple fact that you haven't put anything in there means that what was there before hasn't been changed.


How to use digital pin as ground? I have recently brought an arduino nano. It has only two ground pins but I needed three for my project. Is there a way to use a digital or analog pin as ground pin? Please show me how to do it

There is no need to separate grounds, you can connect all grounds together. In fact they are connected together on the board itself.


How to receive commands to a running arduino program from a raspberry pi? I have looked all over for a solution to this. I'm a noob in the arduino space and am really just getting my feet wet. It's possible that I am interpreting what I am reading wrongly. If so I apologize. Here is my problem/question. I want to create an autonomous driving small land drone. It would connect to some drive sensors, dc motors and do some stuff all by itself. In addition to this I want a raspberry pi with a camera surveying the scenery. Because it is unknown if/when the raspberry PI will see something that is interesting i want this default behavior to occur. The reason I want to do it like this is that I read it is better performance to drive from the Arduino because a linux based computer has so much stuff running on it there could be more lag in the response. In addition the python program will be making HTTP requests, doing image processing, and potentially doing even more. If the image processing software on the PI picks up something interesting then I want this functionality to override the Arduino default program. I was thinking to create a program in Arduino for the basic drive functionality but then be listening to a python process that is running on the PI. If it hears a command to go do something, then of course it will drop the default program, go complete the python generated task and once it is done then it will continue with the arduino default program.
How do I in effect listen to a python process from the Arduino? Or would the proper solution be to not even use the Arduino but drive it all from python on the PI? Any suggestions for how to solve this would be great to hear. I feel like there is an obvious best practice way to do this that I am not aware of. Thanks in advance!

What you are asking for is not completely trivial, and may be ill-suited
for a beginner's project. You will have to create a protocol for the
communication between the Raspberry Pi and the Arduino (your own
“command language” of sorts), and then implement on the Arduino a
command interpreter that understands this protocol and acts accordingly.
I highly recommend you use a text-based protocol, as this will be way
easier to debug than a binary protocol.
For the Arduino side of the project, you first have to learn how to
read the serial port from the Arduino. Then, you can take a
look at this very basic command line interpreter for
inspiration. Or you can search for Arduino libraries that provide
similar interpreters.
On the Python side, you have to open the serial port (/dev/ttyACM0)
and send your commands through it. The details on how to do that
would be a Python question, which is are out of scope here.


Is there a way to reuse an old robot using arduino? I had purchased a simple robot (named Qu-Bot) for a school project a couple of years ago. After the project, it just went into the attic. A few days ago, I purchased an Arduino Uno and started learning the how to operate it. But, before I could purchase LEDs, sensors, LCD, etc, a total lockdown was implemented in my country due to coronavirus.

Is there a way I could program that old robot in Arduino IDE like I program my Uno?

  I'm not sure if this is useful or not, but, when I execute $ lsusb , the bot appears as Bus 001 Device 018: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port

Here's a link to some documentation of the bot:
http://www.technogravity.com/products/qu_bot/qu_bot_downloads.php

Here are photos of all the 3 chips I can see on the board of the bot:

As to your question can I program in ArduinIDE - Yes.

The main chip is from AVR ATMEGA16,
the LCD is a 16x2 (pinout for use with the LCD library is enclosed)
motor driver is (Big thanks to Juraj not a mystery) a ULN2803. Example to work with can be found here.

The circuit diagram enclosed:

How to use in ArduinoIDE:

First install the driver for prolific and makes sure your OS finds the robot  (done)

Then install the MightyCore which supports ATMega16 - there are detailed instructions how to do it
Start with a blink led example (pins from the schematic) compile and upload to test
Then a simple LCD example and so on.

Another posibility would be tor scrap the bot and salvage most parts.

If its feasable the Manual will tell you which parts can be removed without soldering
To get started you need the USB drivers for OS and the original SW to test wether the QBot is still ok from a hardware perspective,
Than you can salvage the parts from it to use with Arduino:

Than you have to make a new base plate (google for pics of 2-wheel robot base plates) and get a motor driver (I recommend for a beginner a cheap motor shield like an Adafruit V2 motor shield clone 5-7$).
As you probably have downloaded ArduinoIDE latest version for your OS, get some example programs and start to play around.


Is there any way for one Arduino board to communicate with multiple sensors? Say a home IoT application to monitor water levels in basement at 4 or 5 different places and transmit that data back to a single Arduino board to be then interfaced with a GUI to do home monitoring?

Yes you can ... however, how you transmit the sensor data? If wireless, you need some RF communication, and possibly a microcontroller like Arduino (or ESP) within each sensor module.

With nRF24L01 (2.4GHz) you can use 6 'slaves' (sensor modules in your case) to send data to the master (monitoring module).

Do things one by one:

First make one sensor module
Than make the master to receive data
Than make the GUI screen
Than make the other five sensor modules


How to read differential TTL signal from encoder using Arduino? I am using Arduino UNO/ MEGA to read the incremental encoder pulses (Baumer encoder EIL580). Currently, I am using it in single-ended mode (reading A,B and Z outputs) as I am not sure how to read the differential signal in Arduino (A, Ainv, B, Binv, Z, Zinv) as it would improve the reliability of the data. Is there any addon shield or circuitry to interface this signal with Arduino?

It looks to me like something similar to RS485 (I have a page about that here).

You could use a chip like the LTC1480 to take the A+ and A- inputs and convert them to TTL levels.

I haven't tried it with your encoder but in principle it should work. (You would need two chips if you want to handle A+/A- and B+/B-. Or three if you want to handle R+/R- as well). Still, it's about a $6 chip.


Rotary encoder using interrupt This is my first time working with a rotary encoder and interrupts.  I am using a Pro Micro which has interrupt pins at pin0 and pin1.  The code below works as expected.

My question: do I need to use an interrupt pin for PinB as well, or can I use any digital pin?

It does not seem to work when I choose PinB = 9, for example.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display

// Used for generating interrupts using CLK signal
const int PinA = 0;

// Used for reading DT signal
const int PinB = 1;

// Used for the push button switch
const int PinSW = 8;

// Keep track of last rotary value
int lastCount = 50;

// Updated by the ISR (Interrupt Service Routine)
volatile int virtualPosition = 50;

// ------------------------------------------------------------------
// INTERRUPT     INTERRUPT     INTERRUPT     INTERRUPT     INTERRUPT
// ------------------------------------------------------------------

void isr ()  {
  static unsigned long lastInterruptTime = 0;
  unsigned long interruptTime = millis();

  // If interrupts come faster than 5ms, assume it's a bounce and ignore
  if (interruptTime - lastInterruptTime > 5) {
    if (digitalRead(PinB) == LOW)
    {
      virtualPosition-- ; // Could be -5 or -10
    }
    else {
      virtualPosition++ ; // Could be +5 or +10
    }

    // Restrict value from 0 to +100
    //virtualPosition = min(100, max(0, virtualPosition));

  }
  // Keep track of when we were here last (no more than every 5ms)
  lastInterruptTime = interruptTime;
}

// ------------------------------------------------------------------
// SETUP    SETUP    SETUP    SETUP    SETUP    SETUP    SETUP
// ------------------------------------------------------------------
void setup() {
  // Just whilst we debug, view output on serial monitor
  //  Serial.begin(9600);

  lcd.init();                      // initialize the lcd

  lcd.backlight();

  // Rotary pulses are INPUTs
  pinMode(PinA, INPUT);
  pinMode(PinB, INPUT);

  // Switch is floating so use the in-built PULLUP so we don't need a resistor
  pinMode(PinSW, INPUT_PULLUP);

  // Attach the routine to service the interrupts
  attachInterrupt(digitalPinToInterrupt(PinA), isr, LOW);

}

// ------------------------------------------------------------------
// MAIN LOOP     MAIN LOOP     MAIN LOOP     MAIN LOOP     MAIN LOOP
// ------------------------------------------------------------------
void loop() {

  // Is someone pressing the rotary switch?
  if ((!digitalRead(PinSW))) {
    virtualPosition = 50;
    while (!digitalRead(PinSW))
      delay(10);
    //    Serial.println("Reset");
  }

  // If the current rotary switch position has changed then update everything
  if (virtualPosition != lastCount) {

    lcd.clear();
    lcd.print(virtualPosition);

    // Keep track of this new value
    lastCount = virtualPosition ;
  }

  //delay(100);
}

Found my error... on the ProMicro, the pins are not arranged 0, 1, 2, 3, 4, 5 etc instead they arranged 1, 0, 2, 3, 4, 5 etc... On the board I misread TXO and RXI as TX0 and RX1 and just didn't notice it on my pinout sheet.... so I had D0 and D1 swapped. All works well now. Learning more everyday! I appreciate your time...


Current difference between pinMode(pin, INPUT_PULLUP) and digitalWrite(pin, HIGH)? Does pin 5 or pin 6 use more power if they're just being used as a signal to an external device?
pinMode(5, INPUT_PULLUP);

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

.
EDIT:  Thanks to some links below, I hopped thru a series of threads until I found the website www.gammon.com.au/power which did tests with a 328 and found the following results with the pins disconnected (which is different than my question but seems relevant nonetheless):
In SLEEP_MODE_PWR_DOWN:

All pins as outputs, and LOW: 0.35 µA.
All pins as outputs, and HIGH: 1.86 µA.
All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

It all depends on the external device. If it has high-impedance inputs,
then it makes no difference. The Arduino itself has high-impedance on
its pins configured as INPUT. If the device draws current from this
signal, then chances are it will draw more current from an OUTOUT
HIGH than from an INPUT_PULLUP. How much more? We cannot say without
knowing the specifics of that device.
If you model the device as a simple resistor to ground (which is almost
certainly overly naive), then the current draw is
I = VCC / (R + Ro)
where R is the value of the resistor and Ro the output
resistance of the Arduino: about 25 Ω for an OUTPUT and
32 kΩ for an INPUT_PULLUP.


Dht 11 sensors give null value void Sensor_value()
{   server.handleClient();
    humidity = dht.readHumidity();
    temperature = dht.readTemperature();
 }

I want to make condition if temperature = null and Humidity= null that means the sensor fails to take reading so I want to return and take value again

The way to do this is:
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);

if (isnan(h) || isnan(t) || isnan(f)) {
  Serial.println("Failed to read from DHT sensor!");
  return;
}

See https://www.hackster.io/MisterBotBreak/how-to-use-temperature-and-humidity-dht-sensors-9e5975 and https://stackoverflow.com/questions/40874880/getting-nan-readings-from-dht-11-sensor.
NULL should only be used with pointers.


Nano: All digital pins do not output anything New user here. Using the examples provided on the Arduino IDE software I could produce melodies with a piezo buzzer, or have a blinking LED.
Not anymore. No digital pin is giving anything. I can see the embedded LED blink if I program the Pin 13, but no impact outside of it.
So I tried connecting an output digital pin (13) to an Analog input pin, or any one that can be put as input (A7, D5, etc.) (with a resistor so not to destroy the little thing).
const char out=13;
const char  in=8;
char         i=0;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);
  pinMode(in,  INPUT);
  digitalWrite(out, LOW);
}
void loop() {
  if(i&1){
    digitalWrite(out,i&2?HIGH:LOW);
  }else{
    Serial.println(analogRead(in));
  }
  i++;
  delay(50);
}

The output has been 0, whichever digital pin it is connected to.
How can I actually find out if, by any chance, I successfully (!) damaged all my digital pins?

I currently use a breadboard
The ground is connected correctly (to GND)
It stopped working between uses, last time I was trying a Tone(out,val) melody
I'm measuring the out-pin value by connecting it to an analog in-pin with a resistor in series
I did set the out-pin as such during setup. (pinMode(out, OUTPUT);)

So! Looks like I didn't understand the codes for the digital pins. I thought we had to use the pin number, but the digital pin number (say 10 for D10) is what it takes to address it. And I was always referring myself back to the schematic for each pin -_-.
As well with the accepted answer, I needed to pull down (or up? still can't figure it out!) the input pin with a resistor to ground.
Thanks everyone!

Your sketch works on a Nano (clone) that I have

I am using a high-brightness white LED with a 10kΩ resistor to bring the brightness down to a bearable level, so the current drawn is about (5v-2.2v)/10kΩ = 0.28mA. This is a low level of current and should be safe for poking around with.

I can see the embedded LED blink if I program the Pin 13, but no impact outside of it.

That suggests that the ATmega328P is essentially undamaged and that at least the IC leg connected to D13 is working as it should.

How can I actually find out if, by any chance, I successfully (!) damaged all my digital pins?

Without a multimeter or other tools,  I would take a LED and resistor that draw less than 5mA, test them between VCC and GND to make sure they work
Then I would use the resistor and LED to check the output of each of the D2 to D13 outputs using your existing sketch.
When the onboard LED blinks, I am able to attach a LED and series resistor to pin D13 and get it to blink.

I wasn't sure what you intended by setting in to 8 so I later changed your program as follows:
const char  in=A1;

and I got this output on the serial monitor after connecting a jump lead from D13 to A1
0
1010
0
1009
0
1009
0
1009
0
1009
0
1009
0
1009
0
1009
0
1008

If I pivot the LED away from pin D13, I can use a jump lead as a test probe

Main points:

pick a high resistor value that minimises current drawn but is still easily visible.
check the LED works! (is right way around etc)
use a jump lead as a probe.

There are more sophisticated test circuits you could build with a FET etc but this would normally be enough for me to decide if an Arduino's outputs are damaged.

Extract from ATmega328 datasheet - note the max current draw per pin is 40mA. Exceeding that is probably the easiest way to damage the IC but if the onboard LED labelled "L" (and connected to D13) works, it means that part of the IC is undamaged.


ESP 12 unusable pins The ESP 12 board has 22 pins

Are all of them usable?

I understand that there is an external flash memory that is accessed through SPI, but I'm not sure what the impact on the pins is.

And if it is so, then why are the pins available?

Is there a sort of a decoder board that receive as an input, let's say 3 SPIOs and outputs 8 GPIOs?

Is there a way to obtain more GPIO pins?

The flash memory is connected to io 6 to io 11 if it is connected in QIO mode. DIO mode lets two of the pins free. According to Arduino core reference the two pins are 9 and 11. The flash pins are labeled SD and most of them are the first SPI interface of the esp8266. You can't use this SPI pins as digital pins, but supposedly you can connect another SPI device.

Some of the esp8266 'free' pins have some restrictions. Boot configuration pins io 0, io 2 and io 15 need to have some state at boot. io2 not LOW, io 15 LOW and with io 0 flashing mode is activated. The A0 is ADC only pin. And you can't count power, EN, Reset and ground as 'pins'.

You can use a multiplexer or an I2C expansion board to get more pins.


Converting live vocals to discrete signals I would like to augment a live music performance by displaying an specific LED for any given musical note.

For vocals:
Rather than attempt to process the audio using the Arduino board, I'd like to use something like an auto-tune box to do the heavy lifting.

For digital instruments: Would like to drive the Arduino board with some kind of digital signal (for example midi)

I'm having trouble finding out which (if any) consumer audio device can provide the pre-processing. Are there any comparable projects or insights?

Confusing question. You list vocals and Digital Instruments, then you ask which audio device provided pre-processing?

There are the auto tunes boxes you mentioned. Since you know about them I don't see how you would be asking about them.

A digital instrument might output midi, and midi is just a simple serial protocol, so there is no device needed.

So what is your question actually?

An auto-tune box does work that would be best suited to a laptop or desktop computer. It first must determine the intended pitch than apply a formant filter to shift the incoming signal to a correct pitch. It requires the use of heavy fast math, Fast Fourier Transforms, FFT.  The smaller boxes you see doing this are actually specialized computers. Do not confuse their size with their power.

Google 'digital tuner software' to get an idea of what goes on.  I do not know of a device that specifically output the 'corrected' midi for an auto-tune, but at that point it would be fairly trivial so it would not surprise me if many did it.  For sure the many guitar to Midi converts do just that, but a good one is several thousand dollars.


Arduino nano Serial port not recognized First sorry for my bad english, not my native lenguage.

Today I started working on my Arduino nano (first time used). When plugged for the first time the "L" led started blinking, after that I tried to write a simple program but I noticed that the "Port" option on the Arduino IDE was Gray. So I couldn't choose the port. After that I searched A LOT but nothing seems to work.

While trying to test if the problem was the Arduino and not the PC, I make a simple circuit with 1 LED, 1 resistor of 1Kohm, and a breadboard. I connected the 5V pin to the LED and GNG to the other point, And when I did this the "L" LED stopped blinking forever. I am 100%  sure that I did not make a short circuit. ¿Maybe the breadboard is in a bad state?

Additional info:

-Windows 10.
-The port doesn't appear at Device manager (tried every port of my notebook).
-The "POW" led is ON when I plug the USB.
- The Arduino is a clone (chip CH340G).

So now I don't know if the problem is the port or if the Arduino Nano is dead because of a possible short circuit between 5V and GND pins.

thanks in advance!

I think your Arduino got short or the transmitter-receiver in it is damaged so the device manager cannot recognize the COM port.It once happened with my Arduino Uno. Try changing the USB cable.If it does not help your Arduino is damaged.


How can I send/write two doubles via Bluetooth (nRF8001 Bluefruit LE) in Arduino? I recently purchased an nRF8001 Bluefruit LE and I am now trying to read/send data with an app. But I am not sure how I can write/send a double value. I want to send two double values at once and to successfully send this, do I have to convert these doubles to a byte array? If so I would very much appreciate how that would look!

This is documentation on how my module works:
https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail

Under the headline Writing data they give examples on how to send data but as far as I can see (I am a bit new to Arduino code) in their example they only send an int and a string.

I know how to read and set up the module, so it is only the writing/sending doubles that I am struggling with.

These are the two doubles that I wish to send and I control it with:

double valueOne;
double valueTwo;

The Bluetooth control:

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

So if I for example do this:

BTLEserial.write(valueOne, valueTwo);

I get this message: no matching function for call to 'Adafruit_BLE_UART::write(double&, double&)'

So do I need to convert these two double values to a byte array and if so how would that look?

Appreciate every help, tips, code! :)

As the link "Adafruit - nRF UART In Detail" describes, the function write(sendbuffer, sendbuffersize); is waiting for a buffer of uint8_t followed by the size of the message.

Here are the step--by-step solution to send the 2 doubles by using that function.

Step1 - convert the floating-point values into a char string.

  In the Arduino environment, the standard format-specifier %f or %lf
  is not well-managed and the function dtostrf() is recommended.

The format is char *   dtostrf (double __val, signed char __width, unsigned char __prec, char *__s) where:

__val is the floating-point value to be converted,
__s is the array of char to store the result,
__width is the number of characters to store the result,
__prec is the number of digit

The conversion is:

char sValueOne[16], sValueTwo[16];
char sBuffer[33];

strcpy(sBuffer,dtostrf(valueOne, 15, 8, sValueOne));
strcat(sBuffer,",");
strcat(sBuffer,dtostrf(valueTwo, 15, 8, sValueTwo));

Step2 - write the buffer over the BTLEserial object.

BTLEserial.write((uint8_t *)sBuffer, strlen(sBuffer));

  Alternate output solution using BTLEserial.print() function.

BTLEserial.print(sBuffer);


128x64 and pushButtons Could someone give me some advice related to building a menu for a 128x64 LCD using 5 pushButtons?
i have 5 screens.
btn1 is for display MainMenu and Selection.
btn2 and btn3 is for up and down scrolling
btn 4 and btn4 is for switching on/off and increase decrease values.

the problem which i encounter is related to btn2 and btn3.
i don;t know how to use them for scrolling in in another screen except screen1 (MainMenu).

#include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(13,12,11); //Enable, RW, RS, RESET

int selectionButton = A1, selectionButtonState, selectionButtonLastState = 0, cntSelectionButtonPressed = 0, cntSelectionButtonPressed2ForMenu2 = 0;
int menuButton = A0, menuButtonState, menuButtonLastState = 0;
int scrollDownButton = A3, scrollDownButtonState, scrollDownButtonLastState = 0;
  boolean mainMenu = false;

void setup()
{
    Serial.begin(9600);
    if ( u8g.getMode() == U8G_MODE_R3G3B2 )
    u8g.setColorIndex(255);     // white
    else if ( u8g.getMode() == U8G_MODE_GRAY2BIT )
    u8g.setColorIndex(3);         // max intensity
    else if ( u8g.getMode() == U8G_MODE_BW )
    pinMode(selectionButton,INPUT);
    pinMode(menuButton,INPUT);
    pinMode(scrollDownButton,INPUT);

}

void loop()
{

 scrollDownButtonState = digitalRead(A3);
 selectionButton = digitalRead(A1);
 menuButton = digitalRead(A0);

//pin A1 = RiGHT
 if(selectionButton != selectionButtonLastState)
 {
  if(digitalRead(A1) == HIGH)
  {
    cntSelectionButtonPressed += 1;
    if(cntSelectionButtonPressed == 4)
    {
      cntSelectionButtonPressed = 0;
    }
  }
  selectionButtonLastState = selectionButton;
 }

////////////////////////
 if(menuButton != menuButtonLastState)
  {
    if(cntSelectionButtonPressed == 1 && digitalRead(A0) == HIGH)
    {
         cntSelectionButtonPressed2ForMenu2 += 1;
    }
      if(cntSelectionButtonPressed2ForMenu2 == 4)
      {
        cntSelectionButtonPressed2ForMenu2 = 0;
      }
       u8g.firstPage();
       do{
           Menu2();
         }while(u8g.nextPage());

       menuButtonLastState = menuButton;
  }
 else
 {
 u8g.firstPage();
  do{
    MainMenu();
  }while(u8g.nextPage());
 }

}

void MainMenu(){
switch(cntSelectionButtonPressed)
{

  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("> Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("> Exterior casa");
           break;
}
}

void Menu2()
{

  switch(cntSelectionButtonPressed2ForMenu2)
{
  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("> Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("> Stil3");
           break;
}
}

First, I'm a bit surprised you use analog pins for button checks, instead of digital pins.

About the code, without analyzing it completely, the easiest way is to make a state diagram in pseudo code first.

E.g.suppose you want to have the following screens(a screen 'title/content' is shown in[], a button transition with ---(key)-->

InitScreen--- (right)--> MenuOption1Highlight---(right)-->MenuOption1Items
                              |       ^     \---(left)----+
                           (down)    (up)
                              v       |
                           MenuOption2Highlight---(right)-->MenuOption2Items
                                              \---(left)----+

To program this (roughly), create an enumeration for each menu page :

enum EMenuPage
{
        None,
    InitScreen,
    MenuOption1Highlight,
    MenuOption1Items,
    MenuOption2Highlight,
    MenuOption2Items
};

Than create a current state for it as global variable:

EMenuPage _eMenuPage;

And initialize it in Setup:

_eMenuPage = None;

Create an enum for the keys :

enum EKey
{
    None,
    Up,
    Down,
    Right,
    Left
};

It is easier to create a function that reads keys, and returns one key, maybe one key has priority over another,
or you can combine keys (in that case add in EKey e.g. UpAndDown). If no key has been pressed, None is selected.

In the loop, use a state transition diagram to program out the options :

EKey pressedKey = GetPressedKey(); // This is for yourself to implement, it updates _pressedKey;

switch (_eMenuPage)
{
case None:
    InitScreen();
    break;

case InitScreen:
    ProcessInitScreenKeys();
    break;

case MenuOptions1HighLighted:
    ProcessMenuOptions1HighLightedKeys();
    break;

...
default:
    // Illegal key
    break;
}

For each page you make a function (e.g. InitScreen) which updates the state and shows the content on the display:

void InitScreen()
{
    _eMenuPage = InitScreen;

    // Show content on display.
}

Also, you create a Process...Keys function to handle the keys. Like:

void InitScreen()
{
    EKey pressedKey = GetPressedKey();
    switch (pressedKey)
    {
    case Right:
        MenuOptions1HighLighted();
        break;

    default:
        // Ignore other keys
        break;
    }
}

For another function it would look like:

void ProcessMenuOptions1HighLightedKeys()
{
    EKey pressedKey = GetPressedKey();
    switch (pressedKey)
    {
    case Down:
        MenuOptions1HighLighted();
        break;

    case Right:
        MenuOption1Items();
        break;

    default:
        // Ignore other keys
        break;
    }
}

(Btw I did not check neither compiled the code).

Probably there is a nicer more object oriented way to do this, but it costs more memory and is more advanced. This is to create an abstract Page class, which has two virtual methods (one to show and one to handle keys), and create a derived class for each page implementing the two functions from the base class.


log STK500v2 commands while flashing a Mega My final goal is to replicate the process with which the PC programs the arduino.
I have gone through the commands.h file and made a couple of attempts to get the logic right. But no success at flashing the arduino.
Is there any way to view the Hex commands that are written to the arduino from the PC? Something like verbose but list every hex command.
My idea is that I will just replicate the same commands and try uploading hex files from SD card.

Add the flag -vvvv to the avrdude command. That will show you the flow of data between the computer and the Arduino.
You can copy and paste the executed command from the IDE and run it in a terminal / command window adding the flag manually. Or you could modify the platform.txt file for the AVR core.


Wiring VCNL 4000 Proximity Sensor I was looking for wiring the VCNL 4000 Proximity Sensor.

I found this one http://bildr.org/2012/11/vcnl4000-arduino/

but there is used a sensor on a red board, which has other pins like mine (which has a blue board) see http://www.adafruit.com/products/466?&main_page=product_info&products_id=466

as I see SCL,DSA,GRND on both

the red has IR+ which is connected to the 5V . mine (blue one) has VIN. Is this meant to be the same and should it be connected to the 5V ?

Any hints?

I tried the following wiring but the following call does not finish.

3,3V TO 3,3V POWER

SCL TO SCL (Last pin on the digital side)

SDA to SDA (Beside SCL)

GND TO GND on the Analog side

Vin to 5V

 readVCNLByte(0x81); is called

i used the example code from adafruiut

There seems to be a big difference between the Sparkfun and the Adafruit breakouts:

Sparkfun breadkout needs 3.3V and 5V power as inputs as shown in their wiring circuit (in the first link you mentioned)
Adafruit breakout needs only 5V as input but has a 3.3V regulator on it that provides the 3.3V to all its internal circuits that need it; it also has a 3.3V pin which is an output not an input as for the Sparkfun

Hence your wiring is wrong. The expected wiring is described in Adafruit sample sketch:

// Example sketch for talking to the VCNL4000 i2c proximity/light sensor
// Written by Adafruit! Public domain.
// To use: Connect VCC to 3.3-5V (5V is best if it is available), GND to
//         ground, SCL to i2c clock (on classic arduinos, Analog 5), SDA
//         to i2c data (on classic arduinos Analog 4). The 3.3v pin is
//         an ouptut if you need 3.3V
// This sensor is 5V compliant so you can use it with 3.3 or 5V micros

In comments, VCC should read as Vin on the breakout.

Note that the comments mention SDA and SCL pins on A4 and A5 respectively, this is correct on Arduino UNO, but your wiring on the 2 leftmost pins of the digital pin header is also correct, as these pins are now replicated there on UNO and Leonardo. On Leonardo, the real pins for SDA/SCL are pins 2 and 3. If you don't have a UNO or Leonardo though, you should check where SDA and SCL can be found (that's generally described on Arduino Product page for your board).

Although wiring SDA/SCL on these 2 replicate pins is correct, I would rather recommend using A4 and A5 instead, so that you don't get the illusion that you can both use SDA/SCL and A4/A5 for something else at the same time.

This circuit uses I2C which means you should normally add pullup resistors to SDA and SCL wires; however, it seems that the Adafruit breakout already integrates them, so no problem here.

To sum up, and provided that you have a UNO or Leonardo, your wiring is correct except that you should remove the wire between both 3.3V pins.

This is shown below for UNO (I used the real pins for SDA and SCL so that you don't use them for something else later):

Arduino UNO 5V  ---> Breakout Vin
Arduino UNO GND ---> Breakout GND
Arduino UNO A4  ---> Breakout SDA
Arduino UNO A5  ---> Breakout SCL
Breakout 3.3V left unconnected

For Leonardo it would be:

Arduino Leonardo 5V  ---> Breakout Vin
Arduino Leonardo GND ---> Breakout GND
Arduino Leonardo D2  ---> Breakout SDA
Arduino Leonardo D3  ---> Breakout SCL
Breakout 3.3V left unconnected

I show you both UNO and Leonardo since you did not mention which board you use.


How to make an arduino webserver over USB? without ethernet shield nor wifi chip I would like to begin to understand ethernet handshakes by integrating an Ethernet over USB protocol within an arduino mega or nano. Is there something about the ethernet protocol that requires more  components? I know that USB to ethernet adapters exist. In this scenario, it would be more like a USB to arduino webserver experiment, except the arduino webserver would also be providing the IP address to the laptop during the initial handshake.
Shouldnt it be possible to create a simple router from an ATMega2560, where you plug in an arduino to a computer, and the computer is assigned an IP address on the ATMega's network?
Likewise, couldnt you then serve small files from the ATMega to a web browser through this IP connection?
I know this sounds dumb and like over engineering. But i promise i am not crazy and that this could be useful. USB to Ethernet adapters and drivers exist, so i am not sure that there is a hardware limitation. In other words, while ethernet normally requires 4 data lines and USB 2.0 has only 2 data lines, there are still kernel drivers that allow USB to work fine in this way. Likewise the ATMega has only 2 available data lines. So couldnt you begin by simulating a USB to Ethernet device firmware using the ATMega?
A new avenue here that isnt available with Serial connections would be that you could access the ATMega from a web browser, whereas in other driver modes the browser doesnt have the permission to communicate with the Mega.
Why or why not? / How could this be done?

You cannot change what the Arduino's USB does. The USB is not provided by the ATMega2560, but by the USB to UART interface chip.
On a genuine Arduino that may be an ATMega16U2 which could be reprogrammed, but on Chinese clones it most often isn't.
You would need to start with a board that has a real "native" USB connection, such as the Arduino Leonardo (ATMega32U4) or the much more capable (though deprecated) Arduino Due.
Then you would need to create not only the USB "CDC/ECM" device profile, but also the IP stack on top of it to handle the IP data, then a TCP later on top of that to handle the socket data.
The actual CDC/ECM device itself is very simple - much like the CDC/ACM (USB serial) device it's really just a dumb pipe that sends and receives raw Ethernet frames. Interpreting those frames and managing TCP/IP sessions and streams is a far more involved process and would be the bulk of the work. You'd probably want to take an existing standalone IP stack implementation and replace the existing layer 2 code with the CDC/ECM interface instead.
An alternative, as advocated by @Juraj, is to use IP over Serial. This uses a serial protocol (SLIP) to encapsulate the IP frames and has a rudimentary cut-down IP stack in it. However this is old technology and is not well supported by operating systems any more. For example the home versions of Windows no longer have any SLIP support (it used to be provided through "DUNS" - the Dial UP Network Server - which no longer exists).


Relay with mechanical fallback In my circuit I have a relay that will turn on some light bulbs this is my circuit:

The switch over the 5V is in fact my Arduino. A HIGH will turn on the relay and a LOW will turn it off.

This is working fine, but because of security measures I need to add a mechanical switch to be able to turn on and off whenever needed. This is the circuit I'm using for this configuration:

This circuit also works fine, the lamp is turned on and off by changing either switches but the Arduino loses track of the status of the lamp. The only thing it knows is if the relay is on or off.

Is there a simple way to tell when the lamp is on?

If you add an optical sensor appropriate for the lamp (UV, IR, visible light?) and add a test line to your code, the Arduino would "know" if the light is on. Your second circuit could remain as presented, while the sensor would provide a status of the light.

If the light failed for an unknown reason, the code for your Arduino would not know the difference between that and a manually opened override switch.


Arduino nano ATmega328p with CH341 won't upload When I try to upload a sketch to an Arduino Nano, it stays stuck on uploading, and after a time it shows the following error code:

stk500_getsync() attempt 1 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 2 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 3 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 4 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 5 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 6 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 7 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 8 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 9 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 10 of 10: not in sync: resp=0xc2

Sometimes the resp=0xc2 variable changes to another hex code.

The weird thing here is that before this happened everything worked fine. I could upload and the serial communication was fine. But after trying to upload the same sketch with a different variable, this started to happen.

Windows recognizes the COM port, in Arduino the COM port is selected. Sometimes, without doing anything, the Arduino works fine again, I can see the serial communication fine, but after some time the serial communication stops sending and again I can't upload the sketch.

I have 2 Arduino Nanos. Both of them start presenting the same problem. But the other one has the Power, RX, and TX led always on and this one never worked again, like the other one that sometimes can upload the sketch and see the serial communication that the last sketch was sending. I have an Arduino Mega, this one has the ATmega16U2 to communicate to USB and this one works fine. And I also have a NodeMCU Lua, with CH341. But this one works just fine.

If you are using a fairly recent version of the Arduino IDE, try using the old bootloader for the 328P.
Go to Tools --> Processor:"ATmega329P" --> ATmega328P(Old Bootloader)


Identify UUID of HC-06 I'm currently learning about using BLE with Arduino and iOS. From what I understand (correct me if I'm mistaken), each type of BT device has a UUID. I'm using a HC-06 module connected to my Arduino. How do I find out what the UUID of a HC-06 is? I've been looking through data sheets to no avail.

In Android, I used this UUID to connect to HC-06,

  socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

  inputStream = socket.getInputStream();
  outputStream = socket.getOutputStream();

You can use this UUID in your Android code, But over iOS, I think the Bluetooth is really a completely different hardware specs.

Hope I helped


How to count the time until the next day of the week? I wants to do in Arduino countdown that shows how many days, hours and minutes remaining to Friday 12:00.
In my program I used a function in php strtotime('next friday') which thus could calculate differential timestamp and show how much time is left until Friday 12:00.

Is there a function strtotime('next friday') in Arduino?
I have RTC which gives me just the current date and time, but does not show the current day of the week.

EDIT:
I have a solution

We have day of week. We multiplied by 86400.
We have an hour. We multiply by 3600.
We have a minute. We multiplied by 60.
Add everything.
Subtract this from 604800.

nextFriday  = 604800-((dayofweek * 86400)+(now.hour()*3600)+(now.minute()*60)+now.second());

Important, Friday is the number of the week "0". Friday = 0; Saturday = 1; etc...

The key to working with time is to have a known "base" time to calculate everything relative to.  This is called the epoch.  Different systems use different epochs, and each has advantages and disadvantages.

I generally use the UNIX epoch in my programming (chiefly because I am a UNIX nut), which is the first of January, 1970 (01/01/1970).  This is year, month, day, hour, minute and second 0.

From that you can then calculate the number of seconds between the epoch and any other time you choose as long as it is later than the epoch.

To calculate the day of the week for any given date you first need to know the day of the week for the epoch (for UNIX that's a Thursday) then work out how many days there are between the epoch and the target time.

Calculating real times in terms of seconds can be somewhat tricky due to leap years and daylight savings, but there are plenty of algorithms in the public domain, and many RTC libraries include functions to convert to/from epoch times.

For instance, the Arduino Time Library has functions to calculate weekdays, and to convert to "time_t" format (seconds since epoch) which can be used to work out differences in times.  For instance, if you know that it's Tuesday and you want next Friday then you know that Friday is 3 days in the future - so you can get the current time in seconds from the epoch then add to that 3 days' worth of seconds (3 × 60 × 60 × 24) to that time to get the same time of day next Friday.


Why can't my Arduino IDE recognize serial ports? (Mac El Cap, Ard. UNO) My Arduino UNO I bought directly from Arduino.cc, so I'm pretty certain it's not a cheap clone. I have a MacBook Pro El Capitan 10.11.5. My Java is 1.8, but I'm pretty sure that doesn't matter. I have never used Arduino before, though I know a good bit of programming and some about computers. Whilst setting up Arduino, the only serial port my computer/Arduino recognizes is /dev/cu.Bluetooth-Incoming-Port. Please comment if there is more information I should provide.

My computer recognizes that I have a USB device as seen here:

Here is a screenshot of the Arduino IDE:

Finally, the commandls /dev/tty.* outputs only /dev/tty.Bluetooth-Incoming-Port. Is it possible no other serial ports exist for me?
Sorry for the barrage of pictures but I thought they'd help.

Things I have tried:

Installing CH34x driver

I'm convinced it's not a driver issue though, as users and Arduino say that OS X does not need drivers installed to run Arduino

Turning off System Integrity with csrutil --disable and also tried csrutil --enable without kext
Installing a FTDI USB Serial Driver
Bought a new USB A/B cable, as many reported the cable was faulty. I am getting a green light on my board

Does anyone know why my computer and/or Arduino does not list more serial ports that work? It's as if I don't have any besides the one Bluetooth port. I've been getting frustrated over this for several hours, so a solution would be much appreciated :)! I've tried all the solutions I've seen on SE thus far, but maybe I'm missing something

Thank you ahead of time!

"ATmega16u2 DFU" indicates a USB interface micro that is in a state to have new firmware downloaded to it (DFU), not one which is ready for operational use as a USB interface to program the Uno's ATmega328p target MCU.  If this persists after power-cycling/re-plugging the board, it is probably faulty and at minimum needs firmware repair - though it might be worth trying on another computer (preferably with a different OS or version) just to be absolutely sure nothing in the host software is forcing it to this mode.

If this is a new board you have not modified in any way, you should probably return it as defective.

If you have modified it, or you want to try to fix things yourself, you would need to follow the instructions for reflashing the 16u2 via USB-DFU.  Beware that this is a non-trivial task that looks like it is going to require installing macports and running some terminal commands, and on older boards some soldering.


How to control 12v water pump by arduino? I have arduino uno and I've bought 12 Volt/350 GPH Seaflo Electric Bilge Pump, how to control it directly from arduino?

It's not possible to control it directly. You need relay module (better one is with opto coupler).

Or you can use some N-Mosfet like IRF540 with antiparallel fast diode to supress induced high voltage from coil. However arduino output might be weak for fast charge/discharge mosfets gate and it gets hot.


How do I correctly choose components for my current project? Previously I asked a question that was a bit to broad so I'm narrowing the focus to a single component board of my design.

I have a set of 3 luckylight R/G bar graphs
(datasheet here: https://cdn-shop.adafruit.com/datasheets/KWL-R1230XDUGB.pdf)
A 5.1 V 2A power source
(recycled ac/dc converter voltage tested datasheet here: http://pdf1.alldatasheet.com/datasheet-pdf/view/322359/BOTHHAND/M1-10S05.html)
a series of 5 SN74HC595 (for controlling the LED multiplexing)
and an Arduino Nano.

The purpose of the bar graphs is to show the player how much of his available system energy he/she is using.

The first three bars of the graph are set to Red, the next 5 are yellow, and the final 4 are green.

As various components are switched on, or other activities drain the power of the engine core, a program level command will switch the multiplexing array to have them shut off.

The problem I'm having is getting enough power to each of the LEDs of the bar graph without overloading the IC pins on the Arduino or shift registers and making the colors appear correctly.

I know I could use Darlington arrays, or a bunch of transistors to keep the power going to the LEDs on a line independent of the ICs, but i'm not sure the right way to go about this. I have a few ULN2803 Darlingtons and a lot of 2n2222a transistors.

(Also my current Arduino code only has, at max, 8 LEDs from each register on at the same time, with a forward voltage of 2.4 volts and 20mA per LED. There are three cycles to my code because the bar graphs have three shared cathode pins that run three 2x4 matrices.)

Additionally I don't know precisely how to calculate the resistor values I would need for this arrangement to maintain the same voltage being applied to the 24 simultaneously running LEDs and get their brightness to be equivalent. Currently i'm noticing LEDs that are farther down the 595 logic chain are receiving less power and appearing weaker. (yes i have been running them off the power coming from the Arduino thus far)

Hopefully this is a narrow enough question.

According to this datasheet the 595 can drive up to 6 mA per output pin with a maximum of 20 mA for the input to the chip (so, 2.5 mA if you are driving all outputs).

Since your LEDs are quoting a forward current of 25 mA it seems that you will fall somewhat short of providing the 25 mA per LED.

There are higher power shift registers, eg. the TPIC6B595.

You might want to consider a multiplexing LED driver such as the MAX7219. I have a post about using that chip.

Your LEDs sound similar to the things that the MAX7219 is designed to drive. It also has inbuilt current-limiting with the current selected by a single resistor.

It isn't clear from your question whether you have the common anode or common cathode device, but you need a common cathode for the MAX7219.

The MAX7219 is not that expensive if you buy it from eBay. For example search for "MAX7219 kit". I found hits for 4 x MAX7219 for $US 9.75 including boards, capacitors and LEDs. Just discard the LEDs (8 x 8 dot matrix) and run the wires to your bargraph.

  As they are designed to run 7 segment displays how would I connect it to transfer from my current 16 bit binary shift setup ...

They can run in a couple of modes (see the Decode Mode register) and one is to send arbitrary bits. Since you can program in any combination of bits (in my link above there is an array which does a CP437 font) you can therefore make up any combination of bars on and off. I would get one as an experiment (buy one of those kits from eBay) and try the idea out. It will be a lot less mucking around than 595 chips, transistors, current-limiting resistors, and so on.

There are various kits around, some are pre-soldered (which you won't want), some come with SMD chips and some with through-hole chips. Choose SMD or through-hole depending on your confidence with soldering SMD parts.

  I know on my shift registers pins 1-8 go to the LED anodes and Pins 9-11 go to transistors that run the cathodes. Can you help me understand the pin connections to get the MAX to run this?

Looking at your bar graph specs:

You have 3 rather than 8 cathodes (pins 14, 9 and 8 are duplicates of 1, 6 and 7). So, you would run the cathode wiring (1, 6, 7) to the first 3 "digit" pins (2, 11 and 6) on the MAX7219. The other 8 wires (marked anodes) would go to the 8 anodes (2, 3, 4, 5, 10, 11, 12, 13).

As you have only used 3 cathode pins you could wire up a second bargraph using another 3 cathode pins (and run the anodes in parallel). That way a single MAX7219 can drive two bargraphs, giving you a total of 24 bars, each of which can show red, green, or yellow at one time.

Example wiring and code

I ordered a couple of the LED modules and worked out a schematic for them:

One MAX7219 can drive two of the modules.

Example of wiring:

Example code:

#include <SPI.h>

 // define max7219 registers
const byte MAX7219_REG_NOOP        = 0x0;
const byte MAX7219_REG_DIGIT0      = 0x1;
const byte MAX7219_REG_DIGIT1      = 0x2;
const byte MAX7219_REG_DIGIT2      = 0x3;
const byte MAX7219_REG_DIGIT3      = 0x4;
const byte MAX7219_REG_DIGIT4      = 0x5;
const byte MAX7219_REG_DIGIT5      = 0x6;
const byte MAX7219_REG_DIGIT6      = 0x7;
const byte MAX7219_REG_DIGIT7      = 0x8;
const byte MAX7219_REG_DECODEMODE  = 0x9;
const byte MAX7219_REG_INTENSITY   = 0xA;
const byte MAX7219_REG_SCANLIMIT   = 0xB;
const byte MAX7219_REG_SHUTDOWN    = 0xC;
const byte MAX7219_REG_DISPLAYTEST = 0xF;

// which groups of bars we are addressing
const byte BARS_1_4   = MAX7219_REG_DIGIT0;
const byte BARS_5_8   = MAX7219_REG_DIGIT1;
const byte BARS_9_12  = MAX7219_REG_DIGIT2;
const byte BARS_13_16 = MAX7219_REG_DIGIT3;
const byte BARS_17_20 = MAX7219_REG_DIGIT4;
const byte BARS_21_24 = MAX7219_REG_DIGIT5;

// within a group, which one (from the left)
const byte BAR1_RED = 0x80;
const byte BAR2_RED = 0x20;
const byte BAR3_RED = 0x08;
const byte BAR4_RED = 0x02;

const byte BAR1_GREEN = 0x40;
const byte BAR2_GREEN = 0x10;
const byte BAR3_GREEN = 0x04;
const byte BAR4_GREEN = 0x01;

// yellow is done by adding red and green
const byte BAR1_YELLOW = BAR1_RED + BAR1_GREEN;
const byte BAR2_YELLOW = BAR2_RED + BAR2_GREEN;
const byte BAR3_YELLOW = BAR3_RED + BAR3_GREEN;
const byte BAR4_YELLOW = BAR4_RED + BAR4_GREEN;

void sendByte (const byte reg, const byte data)
  {
  digitalWrite (SS, LOW);
  SPI.transfer (reg);
  SPI.transfer (data);
  digitalWrite (SS, HIGH);
  }  // end of sendByte

void setup () {

  SPI.begin ();

  sendByte (MAX7219_REG_SCANLIMIT, 5);   // show 6 digits
  sendByte (MAX7219_REG_DECODEMODE, 0);  // using an led matrix (not digits)
  sendByte (MAX7219_REG_DISPLAYTEST, 0); // no display test

  // clear display
  for (byte col = 0; col < 8; col++)
    sendByte (col + 1, 0);

  sendByte (MAX7219_REG_INTENSITY, 7);  // character intensity: range: 0 to 15
  sendByte (MAX7219_REG_SHUTDOWN, 1);   // not in shutdown mode (ie. start it up)
}   // end of setup

void loop ()
 {
  // send various test combinations
  sendByte(BARS_1_4, BAR1_RED | BAR2_GREEN | BAR3_RED | BAR4_GREEN);
  sendByte(BARS_5_8, BAR2_RED);
  sendByte(BARS_9_12, BAR2_YELLOW);
  sendByte(BARS_13_16, BAR1_RED | BAR2_GREEN | BAR3_RED | BAR4_GREEN);
  sendByte(BARS_17_20, BAR2_YELLOW);
  sendByte(BARS_21_24, BAR1_RED | BAR2_RED);
 }  // end of loop

This is documented in my page about the MAX7219.


Arduino Mega reading from external sensor Issue I have one external sensor and I want it to be connected with Arduino. The sensor came up with a usb cable and the pin out diagram is also given in the data sheet .
When I simply connect the the cabe which came along the sensor (E322968) with no Arduino board involved, but through Arduino IDE and setting baud rate to 115200 I am able to see the output in serial monitor of the Arduino .

I want to capture this data to some variables for further manipulation. In the data sheet the pinout is specified as

Please help me get the data to Arduino variable .
What I tried is connected,

the RX1 or Arduino mega to the TX1 of the sensor (pin2) and
from Arduino VCC(5v) to VCC of the sensor :: pin(1)
ground to gnd of sensor, (pin5)

the RX1 or Arduino mega to the TX1 of the sensor (pin2) and

That will not work. These pins are for RS232, which uses the same communication protocol (UART) as the Arduino, but it uses different voltage levels. But fortunately your sensor has also RX and TX pins at TTL level (Transistor-Transistor-Logic). You want to connect these to the Arduino.
One thing to keep in mind: The sensor logic seems to work at 3.3V (voltage on the RX and TX lines). If you also want to send data to the sensor, you may need to step down the 5V of the Uno to the 3.3V of the sensor on its RX line (since 5V might damage the sensor). You can use a simple voltage divider with 2 resistors or a proper level shifter (which uses transistors) (voltage dividers limit the communication speed, though 115200baud should not be a problem).


Is it possible to program a few Arduinos at the same time? I have 10 Arduino Pro Minis and one Arduino Uno. Via breadboard, if I connect Pro Minis in parallel, can I program all of them at same time?

Is it possible?

Arduino Pro Mini is programmed through serial, using a bootloader. It uses STK500 protocol, which is described by Atmel.

In theory, it can be possible to program multiple boards if only one TX Arduino pin is connected to USB-Serial converter, and all RX are in parralel, but this is an unreliable method. Only the board with TX pin connected can send its status back to programmer.

Arduino Mini also requires a physical reset before uploading. Make sure that all Reset pins are connected together when reset button is pressed.


AVR Timer1 OCR1A controls TIMER1_COMPB_vect interrupt! I was struggling with timer interrupts in my project. I couldn't make it work properly. So I decided writing a simple code and I saw a very interesting case.

ISR(TIMER1_COMPB_vect)
{
        PORTB ^= (1 << PORTB5);
}

int main(void)
{
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    OCR1A = 10000;
    OCR1B = 100;

    TCCR1B |= (1 << WGM12);

    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);

    TIMSK1 |= (1 << OCIE1A);
    TIMSK1 |= (1 << OCIE1B);
    DDRB= 0xFF;

    #define F_CPU 16000000
    sei();
    while (1)
    {

    }
}

Here is my code. When I change OCR1B value, nothing happens, but if I change OCR1A value then blinking gets faster. Is there a logical explanation for this?

By setting WGM12, you set the time to CTC mode. In this mode the timer will restart when it reaches that value set to OCR1A. So the lower the value, the faster it restarts, so the higher the frequency.

The OCR1B value only changes where in this cycle the interrupt occurs. It will however still only be called once per timer1 overflow.


Can Arduino UNO permanently store a code? I'm really new to Arduino and wanted to know if I can make Arduino a permanent controller?
and could you help me with a cheaper alternative?
I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.
Thanks a lot for helping me out:)

idk if the arduino stores the code for ever

The code is saved in the flash memory, which is non-volatile. It does not lose its content during power cycles. Also, when looking at the time dimension, it holds the code over a very long time, though not for ever. The datasheet of the Atmega328p (the microcontroller in the Arduino Uno or Nano) states:

Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

So over 20 years at a temperature of 85°C you can get 0.0001% of data loss in the flash memory. At normal room temperature you can get that loss in 100 years. So significantly longer than the lifetime of most electronic products.

I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.

There are different ways and levels of protection. Though that is a more advanced topic, that you should tackle, when your product is finished otherwise. There are multiple resources on the web about this. The first place to look is always the datasheet of the used microcontroller. First part might be to not use the standard Arduino bootloader, but your own. And then you can set 2 fuses for getting different levels of protection (write protection, read protection), that will lock out 99% of the people. This question on Electrical SE might also be interresting for you. You can find many resources on the web by searching for something like "Arduino code protection" or "AVR code protection" (if you are using an AVR based microcontroller like with the Arduino Uno/Nano/Mega)

Apart from that I also would open the question to you, if your code is really that new and ingenious, that you need to protect it from being read that way? It might totally be, that this is the case for you. But from my perspective the probability is very low. I cannot say of my own codes, that they are worth the hassle of protection. And it also depends on what you really want to prevent that way.
For context: When you program the Arduino (or any microcontroller) with your C/C++ program, the text of the program is not saved on the Arduino. Instead the code is first converted to Assembler code and then compiled into binary machine code. On that level all the nice concepts of the higher level languages are not present, so they are done by multiple lower level functions (for example loops are jumps with conditions). An attacker might read the machine code back from the microcontroller. The biggest threat here is, that he would just copy it to a new microcontroller.
If he wants to get "code" from it, he would invoke a disassembler, which converts the machine code back to the assembler language. But at this point all symbols (names of variables, functions, ...) are lost, because they are not saved in the original machine code from the start. Reading and understanding such a code is very difficult, especially, if your code is rather big and complex. Most times it would be easier for an attacker to just reverse engineer your code based on the behavior of the original microcontroller.
So in the end, you cannot really prevent people from building counterfeit products. That's what a patent is for.
This does not mean, that you should not use the code protection. Just do a realistic security assessment and then decide, if it is worth the hassle.


Motor isnt spinning when using L298N motor controller I have a L298 motor controller connected to a motor with a 6 volt power sources. the motor however isn't spinning any ideas I'm using a esp 8266 node mcu board. I would like to use pwm but for right now I'm just trying to get it to work so I disabled the pwm.

//int d0 = 16;
const int d0 = 16;
const int d4 = 2;

//=======================================================================
//                    Power on setup
//=======================================================================
void setup() {
  Serial.begin(115200);
  pinMode(d0,OUTPUT);
  //pinMode(d1,OUTPUT);
  pinMode(d4,OUTPUT);
}

//=======================================================================
//                    Main Program Loop
//=======================================================================
void loop() {
  //PWM Value varries from 0 to 1023
  Serial.println("10 % PWM");
  //analogWrite(d0,102);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("20 % PWM");
  //analogWrite(d0,205);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("40 % PWM");
  //analogWrite(d0,410);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("70 % PWM");
  //analogWrite(d0,714);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

  Serial.println("100 % PWM");
  //analogWrite(d0,1024);
  digitalWrite(d0,HIGH);
  digitalWrite(d4,LOW);
  delay(2000);

}

You need two supply voltages for this board to work: motor supply, which goes directly to your motor (up to 35V for this L298N board, depends on what your motor needs), and logic supply of 5V, which powers the board's logic chips. If the motor supply voltage is between 7V and 12V, you can derive 5V logic supply from motor supply by enabling this board's built-in linear regulator.

The actual motor power supply should be connected to the VCC terminal of the L298N board you have in your picture. This is the leftmost terminal in the block of 3 in the picture (sometimes it is labeled +12V instead of VCC). In your case it is not connected to anything at all. This is already wrong.
It is not clear what the purpose of the red wire is in your picture.

In your comments you mention different voltages of motor power supply (6V in one place, 9V in another...). If you are feeding this board 9V through the red wire, you are doing it wrong. The rightmost terminal in the block of 3 is the 5V pin. Don't attempt to feed more than 5V to that pin.

If you'll be using the red wire to supply 5V logic power to the L298N board from an external source, then you need to disable this board's own linear regulator - remove the jumper that is shown above the 3-terminal block.

If you'll decide to use it to supply 5V logic power from the L298N board (e.g. to your Arduino), then you have to keep the jumper.

In any case, the leftmost terminal has to be connected to motor power supply.


How can I make a Parallax Servomotor move a water tap correctly and prevent from vibrations? I am using Arduino Mega 2560

I have built an structure with plastic 3D pieces to move this water tap.:

I am using the "Servomotor Parallax Inc 140 mA, 4 6 V" to rotate the tap:

Some more images to show how I mounted it:

Video 1. I tried to use the power of the arduino directly (5V). But the motor is not steady in all the positions I set, in some positions the noise you hear in the video do not stop, and my impression is that the motor will burn soon because it keeps pusshing all the time.

Video 2. Without almost any load, the motor is also making a small sound. I don't know if you can appreciate it in the video. They are like cracks or clicks

Possible solutions:

Is there a way to cut the power supply when the motor already moved the tap? Or just to stop the motor to keep pushing?
Using a external power should solve the problem? I found this tutorial where they use that system. Which will be the benefits of that? It will fix the problem?
Using another stronger servomotor?
A stepper motor?
Is my servomotor faulty?
Would I need some controller?

Any other suggestion?

When you set a servo motor to be in a specific position it is constantly and actively striving to keep in that position. The feedback from the internal potentiometer is constantly being processed and the motor adjusted to ensure that it remains at the right position.  Potentiometers, of course, aren't 100% perfect, and there will always be a certain amount of "noise" in the signal that means the motor will always be making really tiny adjustments.

That's perfectly normal.

The simple way to stop it trying to keep precisely to one position is to stop telling it to be in that position.

.attach() the motor
Move it to the desired position
Wait long enough for the motor to get to that position
.detach() the motor

When you call servo.detach() the PWM signal is terminated and the motor no longer has a position to keep to - so it just stops doing anything and goes to sleep.

The down-side of this is that if you have a load under tension (for example if you are lifting a weight with the servo) the tension is then free to move the motor.