Execute function until called again? I am building a simple security system with my Arduino Uno. I have an alarm() function:

void alarm() {
  tone(8, 3300, 200);
  delay(200);
  tone(8, 3000, 200);
  delay(200);
}

When I call it in the loop() function like so:

void loop() {
  alarm();
}

the alarm sounds fine. I just want to be able to stop it. What I mean is, I want it to start the alarm (if it is off) when I call the alarm() function, then stop it when I call the alarm() function again. How can I do this?
P.S. Can someone with over 150 reputation please make the tone tag? I can't believe it's not here!

Edit: I tried the following code, but the alarm just kept going:

bool alarmOn;
void setup() {
  pinMode(8, OUTPUT);
  alarm(true);
  delay(5000);
  alarm(false);
}

void loop() {
}

void alarm(boolean call) {
  if (call) {
    alarmOn = true;
  } else {
    alarmOn = false;
  }
  while (alarmOn) {
    tone(8, 3300, 200);
    delay(200);
    tone(8, 3000, 200);
    delay(200);
  }
}

You can just have a variable that remembers whether the alarm is
supposed to be on or off. Let's call it alarm_on. Then:

bool alarm_on;
static void start_alarm() { alarm_on = true; }
static void  stop_alarm() { noTone(); alarm_on = false; }

void loop()
{
    if (alarm_on) alarm();
    if (some_condition()) start_alarm();
    if (some_other_condition()) stop_alarm();
}

For a better approach that allows you to sound the alarm without
blocking the whole program, see the Blink Without Delay Arduino
tutorial.

Edit: I just wrote (but did not test) a non-blocking version of this
alarm, based on a state machine and the timing technique from the Blink
Without Delay tutorial. Here it is, as a class:

class TwoToneAlarm {
public:
    static const uint16_t HIGH_FREQ = 3300;
    static const uint16_t LOW_FREQ  = 3000;
    static const uint16_t TONE_DURATION = 200;

    TwoToneAlarm(uint8_t output_pin)
    : state(OFF), pin(output_pin) {}

    // Start the alarm.
    void start()
    {
        tone(pin, HIGH_FREQ);
        state = HIGH_TONE;
        last_tone_change = millis();
    }

    // Stop the alarm.
    void stop()
    {
        noTone(pin);
        state = OFF;
    }

    // Call this periodically to handle the tone changes.
    void update()
    {
        if (state == OFF) return;
        if (millis() - last_tone_change >= TONE_DURATION) {
            switch (state) {
                case HIGH_TONE:
                    tone(pin, LOW_FREQ);
                    state = LOW_TONE;
                    break;
                case LOW_TONE:
                    tone(pin, HIGH_FREQ);
                    state = HIGH_TONE;
                    break;
                default:
                    break;
            }
            last_tone_change += TONE_DURATION;
        }
    }

private:
    enum { OFF, HIGH_TONE, LOW_TONE } state;
    uint16_t last_tone_change;
    uint8_t pin;
};

It could be used like this:

TwoToneAlarm alarm(8);

void loop()
{
    if (some_scary_condition()) alarm.start();
    if (some_other_condition()) alarm.stop();
    alarm.update();
}

Note that the whole program must be non-blocking (delay()-free),
otherwise the tone changes will not be done on time.

Edit: more about being non-blocking.

There is normally no reason for you to use delay() at all in your
program. The only reason for this function to exist is to help complete
beginners write their first blink-the-LED program. As soon as you start
writing anything non trivial, you should ban it from your vocabulary.
The Blink Without Delay tutorial is here precisely to teach you how to
get rid of delay() by using millis().

In this particular case, however, the drawback of delay() may not be
too severe: if the alarm is sounding and you delay a tone change, you
may hear it as a glitch that breaks the rhythm of the sound. If the
delay is short enough, maybe up to 10 ms or so, you are unlikely to
notice it. Longer delays will be noticeable, and it's up to you to
decide whether you find them annoying or not.

It is possible to ensure a very steady rhythm despite the delays by
using interrupts, but this will cost you your 16-bit timer. Or you could
write your own implementation of tone() that does both the pin
toggling and the tone changes using a single timer. Any such option will
require you to learn about low-level timer
programming, which is significantly
more demanding than learning to use millis().


Calling class member from .h file In .ino file I have a class defined (called IPmonitoring).Also, inside the same .ino file, I call a .h file ( which is located "above" class IPmonotoring).
When I try to call members of IPmonitoring inside .h file - I get an error, which usually I solve using extern, but seemingly it is not the same for classes.
What should be done ?
Guy

You need to re-think your layout, and your usage of the .h file.

You should never have code in a .h file unless it is either inline or part of a template class.

A .h file should only contain hints about where other things are. Those things should then be in .cpp or .ino files.
For example your IPmonitoring class would be declared in a .h file, and defined (or implemented) in a .cpp file (or .ino file if you prefer). Any place you want to use that class you #include the .h file. In one place you may choose to create an instance of that class. It is that instance that you then reference with extern.
In the Arduino world it is common to create a single instance of the class in the class's .cpp file and extern it in the .h file so everywhere that you include the .h file instantly has access to that single instance of the object.
This is how most libraries are written.
For example:
// IPMonitoring.h

class IPMonitoring {
    public:
        void doStuff();
};

extern IPMonitoring ipMon;

And:
// IPMonitoring.cpp

#include <IPMonitoring.h>

IPMonitoring ipMon;

void IPMonitoring::doStuff() {
    // Do something
}

And finally:
// mySketch.ino

#include <IPMonitoring.h>

void setup() {
    ipMon.doSomething();
}

void loop() {
}


avrdude: stk500_recv(): programmer is not responding after all tries After months of good use, both my boards Mega 2560 and Uno became unavailable for uploading sketch or burning bootloader.

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\[...]bin/avrdude -CC:[...]avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM5 -Uflash:w:C:\Users\GREGOR~1\AppData\Local\Temp\arduino_build_242793/BareMinimum.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:[...]\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

Facts :

v1.6.20 of the boards
v1.8.5 of the IDE
Windows 8.1 64bits
Programmer: "AVR ISP"
Drivers are fine (the boards are well recognized)
Serial monitor works
I'm trying to upload the "Bare minimum" exemple sketch
Nothing in pin 0 and 1, nothing at all is plugged actually
Get Board info:
Uno : VID 2A03
Mega2560 : VID 2A03
From instructions here, every instruction is "echoed back"

What i tried :

https://forum.arduino.cc/index.php?topic=385160.0
avrdude: stk500_recv(): programmer is not responding
https://zestedesavoir.com/forums/sujet/5676/probleme-televersement-arduino
All other programmers
A few old versions of boards
Resetting the boards a few times, during upload, before, after...

Nothing works. If you have any idea.....

Thank you all !

It eventually worked by using upload / ctrl+U (what I didn't try... smh) instead of  upload using programmer / ctrl+shift+U.

So i know now where it comes from, though I don't know what's wrong with AVR ISP.


Troubleshooting DC motor I worked on the starterkit project #9 motorized pinwheel, and the motor worked just fine.

I then tried to add a potentiometer, and now the motor won't rotate at all any more (neither in the current nor in the project's baseline configuration). I also tried connecting the motor to the 9V battery directly, to no avail.

I did check the battery by briefly connecting a LED right away. The motor apparently also still generates current if I turn it manually (checked with a directly connected LED either).

What else can I do to check what's wrong with the motor? Is it possible that I somehow accidently killed it with my attempts with the potentiometer?

If your motor doesn't work when connected to the 9V battery, either the battery is flat (which is likely since you were able to connect the LED without destroying it!! - they are a 2.5-3v part, not a 9v part) or the wiring to the motor is damaged. When you connect the motor directly to a 9v battery, it should turn pretty fast - may also work if you connect it to between 2 & 4 AA batteries.

9v batteries don't have that much energy in them... you would be better off with a battery pack with 6 AA batteries in it.


Square LED vs Round LED I'm trying to choose between square or round LEDs.  I would like to select an LED that will "project" light and I cannot find any information comparing the two types.

Which style of LED will project light better?

Projection, for the purposes of this question, means casting light "in-line" with the LED.  For example, an LED right out of the box with straight leads plugged into a breadboard on a flat table will stand vertically.  In this case, I would like to project as much light onto the ceiling as possible.  I hope this makes sense.

If it matters, I'd like to use water clear blue LEDs.

Many of the square or rectangular LEDs with leads  – that is, not surface mount devices (SMD)  –  that I've seen are intended for use as panel indicator lights, so are not very bright.   On the other hand, among SMD devices square, rectangular, and round lights run the whole gamut of brightness.  Of course many white LEDs, square or round, are extremely bright because of being intended for illumination.

For projecting a beam against a ceiling, adding optics to the LED may be the best approach.  For example, buy some 99¢ flashlights like “Waterproof 3500LM Pocket LED Flashlight Zoomable LED Torch Mini Penlight Light” on ebay, and either add a blue filter in front of the lens or replace the LED with an ultrabright blue LED, using the zoomed-out flashlight lens to concentrate the light.  Also, search for 10° or 15° “PMMA LED lens” on ebay, Amazon, aliexpress, etc.

Note, for determining if any given LED will project a tight bright beam, look at the angles of its beam pattern.    This diagram (from Led Buying tips at sunriseled.us) contrasts the intensity of a 30°-beam LED with that of a 70°-beam LED.  The diagram at left below (from dimmable-gu10.com) is typical of intensity-vs-angle diagrams, which usually are shown on a polar plot like that, with a narrower oval corresponding to a tighter beam.  The diagram at right below shows the same information, in a perhaps more easily comprehended form.


LF: flexible scheduler/timer library I'm working on a few arduino projects where I've needed a flexible scheduler and/or timer library and was wondering if anyone has a library they recommend?
Case 1:
I have a sensor that needs to collect observations every hour, but it has a specific  measurement sequence:

Power up/boot (takes about 15 seconds)
Warm-up for 60 seconds.
Observe (2 min), collect raw data, generate stats
Cool-down for 5 min.
Power off

In this case have a single micro-controller acting as a data-logger that is controlling multiple sensors and writing to an SD card.
Case 2:
I have an oven that needs to be controlled to a user-specified temperature profile (up say to 6 points of change), i.e.:

Turn on heater
Set temperature, 100C and hold for 2 min
Set temperature, 160C and hold for 15 min
Set temperature, 250C and hold for 1 hr
....
Set temperature, 100C and hold for 1 hr
Turn off heater

I'm familiar with non-blocking timers and (in the past) have cobbled together a few simple timers with millis() and some ulong variables. Alas, the complexity and debugging time rapidly grows with the number of dependent timers. Before I sit down and sketch out a class definition, I figured I'd ask what others are using.

Some libraries I find good (opinion-based):

TaskManagerIO: https://github.com/davetcc/TaskManagerIO

does a good job at managing events / scheduling things for a certain (system) time, or even repetitively.
with that you could e.g. use a scheduleFixedRate() API to call a function every 60 minutes. Then starts the power up (I assume asynchronously, by setting a pin or something), and just primes the scheduler with the scheduleOnce() API to call another function in 15 seconds. That target function then starts the warmup and schedules the next function / step for 60 seconds into the future, et cetera. It would express the flow very naturally.

If accurate timekeeping is needed so that it's really every hour, you might want to  use an external RTC module. Also depends on the microcontroller you're using, many have a builtin one that you can feed with a 32.768 kHz crystal and thus you don't need an external chip

library for the DS3231 / DS3232 RTC lets you set an alarm in the RTC: https://github.com/JChristensen/DS3232RTC/blob/master/alarm-primer.md
with that you can e.g. set an alarm for every 60 minutes and then execute your task.


ESP8266 communication issue I have an issue communicating with ESP8266 via Arduino Uno's serial ports.

I can connect to it using
python -m serial.tools.miniterm /dev/ttyUSB0 115200
command but when trying to send an AT command, it looks like this:

�tC�

ERROR
�v[�
ERROR
at

OK

So, sometimes I'm able to properly send a command, but usually what I type turns to gibberish. I've tried other baud values, but only 115200 works.

I'm powering Arduino via USB from my laptop. I've seen some mentions that this behavior may be caused by low voltage but unfortunately, I'm currently unable to verify it whether that's a case here.

My schematic looks like this:

I'm new to this, so if there is any crucial information I've missed, then please let me know and I'll do my best to provide it.

The issue, as Maximilian Gergardt suggested in comments, was with Arduino's TX/RX sending 5V signal. Adding voltage dividers on RX line solved the issue. Refer to diagram below for details:


Arduino transmitter and receiver hi I am using Arduino transmitter and receiver it works properly with sending and receiving username and password but I would include to check the username if its true open the led , I added this in the code but it seems that the code ignoring it ( the last part) as well as I want it to take the password and username at the same time

this is the recover code

#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray

 RH_ASK rf_driver; // create ASK object
int ledon = 13;
String userid;
String password;
 //RH_ASK ID1; // create ASK object
//RH_ASK pass1; // create ASK object

void setup() {

  rf_driver.init(); //initialize ASK object

  Serial.begin(9600); //setup serial monitor to 9600

  //if(!rf_driver.init())
       //Serial.print("init failed");
}

void loop() {

  // set buffer to size of expected message
  uint8_t buf[9];
  uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  if (rf_driver.recv(buf,&buflen))
  {
    int i;
    // message received with valid checksum
    Serial.print("id: ");
    Serial.println((char*)buf);
      userid =(char*)buf;
        Serial.println(userid);

  }

delay(5000);

   uint8_t buf2[8];
  uint8_t buflen2 = sizeof(buf2);

   if (rf_driver.recv(buf,&buflen))

  {

    int i;
    // message received with valid checksum
    Serial.print("password: ");
    Serial.println((char*)buf);
      password = (char*)buf;
      Serial.println(password);

  }
  delay(5000);

while ( userid =="A00034732" && password == "123456789"){
digitalWrite(ledon, HIGH);
delay(2000);
digitalWrite(ledon, LOW);

}
}

transmitter code ----

//Include RadioHead Amplitidue shift keying library
#include <RH_ASK.h>
// Include dependatnt ISP library
#include <SPI.h>

//create Ampitude shift keying object
RH_ASK rf_driver;

void setup() {
 // intialize ASK objct
rf_driver.init();

Serial.begin(9600);

  //if(!rf_driver.init())
      //Serial.print("init failed");

}

void loop()
{

  const char *pass= "123456789";
rf_driver.send((uint8_t *)pass, strlen(pass));
rf_driver.waitPacketSent();
delay(5000);

const char *ID= "A00034732";

rf_driver.send((uint8_t *)ID, strlen(ID));
rf_driver.waitPacketSent();
delay(5000);

//const char *pass= "12345678";
//rf_driver.send((uint8_t *)pass, strlen(pass));
//rf_driver.waitPacketSent();
//delay(5000);

}

You're not comparing strings - you're comparing addresses of strings.  Use strcmp().

while (
    (strcmp(userid, "A00034732") == 0) &&
    (strcmp(password, "123456789") == 0)
) {


When the Arduino is in reset mode are the digital pins high impedance? I have an Arduino (Arduino A) hooked up to an external FRAM chip and I want to be able to pull the Arduino A's reset pin to ground to keep it in a constant reset state. Then I want to hook up another Arduino (Arduino B) up to the same lines going from Arduino A to the external FRAM chip and pull data off of the FRAM chip.

I am worried that when I hook Arduino B to the lines running between the FRAM and Arduino A that it will damage Arduino A. If the digital pins are in a high impedance state while I do this though, then it should be fine. I can't find the necessary documentation to figure this out though.

All Arduinos involved are Uno Rev 3s.

Any help would be appreciated, thanks!

From the ATMEGAxx8 datasheet...

11.1 Resetting the AVR
... The I/O ports of the AVR are immediately reset to their initial state
when a reset source goes active. This does not require any clock
source to be running.

(bold added)
Looking over the register descriptions for the Data Direction Registers, all bits have an initial value of 0, corresponding to high impedance input.
...so it is safe to assume that all IO pins will be in a high impedance state a very short time after the RESET pin goes low.
Caveats:

The clamping diodes are in-circuit even when pins are in high impedance state, so current will flow if the voltage on the pin is higher than Vcc or lower than Ground (at least until the diode blows up!).

Some Arduino pins are connected to other things besides just the pin on the MPU. For example, digital pin 13 is connected to ground though a resistor and diode, so current will flow into it if you connect a voltage higher than the threshold for the diode. On the Uno there are also resistors on the RX and TX pins connected to the serial communications link, so current can flow there too.

The MISO pin can inadvertently become an output while RESET is held low if the Programming Enable command ($AC $53 xx yy) is transmitted over the MOSI & SCK lines. This process is described in App Note AVR910.


Why change the variable content? I don't understand why change uidList[reader] variable, when doesn't run more to the else. I use in this test only the "0" reader.

First loop go to the "else" and fill the uid to uidList[reader]. (good)
Second loop go to the "if" because the two uid is equal.(good)

I remove NFC and place the other, but the uidList[reader] updated immediately to the new UID, not in the "else". Never go again to else. Why?

#define NR_OF_READERS   2
byte* uidList[NR_OF_READERS];
MFRC522 mfrc522[NR_OF_READERS];   // Create MFRC522 instance.
......
void loop() {
  ....
  delay(2500);
  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {

     dump_byte_array(uidList[0], 8);
     dump_byte_array(uidList[1], 8);

   if (mfrc522[reader].PICC_IsNewCardPresent() &&     mfrc522[reader].PICC_ReadCardSerial()) {

     dump_byte_array(uidList[0], 8); //WHY UPDATED HERE???
     dump_byte_array(uidList[1], 8);

     if (uidList[reader] == mfrc522[reader].uid.uidByte) {

        Serial.println(F("Same NFC"));
        dump_byte_array(uidList[0], 8);
        dump_byte_array(uidList[1], 8);

     } else {

        Serial.println(F("Other NFC in this reader"));

        uidList[reader] = mfrc522[reader].uid.uidByte;

        dump_byte_array(uidList[0], 8);
        dump_byte_array(uidList[1], 8);

     }

   }
}

void dump_byte_array(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
  Serial.println();
}

When I placed the new NFC in the reader, this debug appear on serial monitor.

 DF 6D 05 D2 00 00 00 00 //old NFC uid it's good

 AB 00 6C 02 F0 21 00 00

 FF 2C 02 69 00 00 00 00 //WHY UPDATED HERE???

 AB 00 6C 02 F0 21 00 00

Same NFC

 FF 2C 02 69 00 00 00 00

 AB 00 6C 02 F0 21 00 00

Thanks any idea.

Well, it's easy, as you are using pointers. If the original place gets changed, you can see changed value because you don't have your own copy.

Your if statement is also wrong, as you are comparing two pointers here. They will be different at the first time comparation, but after the assigment they are unlikely to change.

The solution is using:

byte uidList[NR_OF_READERS][8]; // better to use some constant value instead of magic number

and memcpy for making a copy and memcmp for comparing its content. Both are from <cstring> include


Relay 24 V appliance I want to use a switch and an Arduino to "power" a 24 V DC appliance and I am not really sure what relay to use for this.
So I need the relay to be able to switch it on and off, but I have not really been able to find any that do it for 24 V DC, only for mains.

Can I use a mains relay or is there special one for 24 V.
I have all tried searching for the problem but haven't really found anything that helps. I'm probably searching for the wrong thing.

I am new just started learning electronics and stuff.
Thanks.

Most relays have their ratings written on them. You can also find all the information you need in the datasheet for that relay. Search for the part-nr in your favorite search engine.

You need to find a relay that can handle at least 24Volt DC. Not AC as relays can handle a much higher voltage at AC than they can at DC.

You also need to check how maximum current your appliance draws. Make sure the relay is rated for at least that amount of Amps.

For example; the picture below shows a relay that's rated for 10A and 30VDC


Are these relays connected correctly? I currently have limited electronics experience. I am planning to use mains power through relays for climate control, so considering the risk, I would like to check to see if these relays are appropriately connected to receive mains power.

I have two relays. One relay will take 600W (a heater) while the other will have 50W/0.2A (a fan).

The relay module is: https://www.auselectronicsdirect.com.au/assets/files/(ST1080)5V%20Relay%20module.pdf
There seems to be a resistor inbuilt into the casing, and according to the packet (but not the PDF) there is inbuilt Back-EMF protection.

My concern is that it may not be protected against inrush, uses screw terminals, and may not be isolated.

Diagram is:

Any advice will be appreciated. Once again, I will not run mains power through it until I am sure of it being safe.

Yes, your relays are hooked up the right way. I'm using the same modukes to drive a fan 75W and a HPS-Lamp with 400W. As long as you drive the heater with AC voltage, you're in the specs (different than stated in previous comments).
But the humidity sensor (a DHT11/22) isn't, as far as I remember its pinout...
And could you explain what the Transistor is for (if it is a transistor, I'm curious what you want to achieve with this wiring)?


Why is Serial.write() slower than memcpy()? I use Serial.write() to transmit 53 bytes to PC. For the time measurement I use micros() (before and after the write function). There is a delay of 1s after each transmission.

The time of the Serial.write() function is 532 us with 1000000 baud rate, and 360 us with 9600 baud rate.

The Serial.write() function is clearly asynchronous because the transmission of 53 bytes with 9600 baud rate is 53*8/9600*1e6 = 44167 us. (By the way, in the case of 1000000 baud rate, it is not so obvious that the function is asynchronous.)

I use Serial.availableForWrite() before Serial.write() to confirm that there is enough space in the buffer (this returns 63 each time, the buffer size is default 64).

I don't understand these numbers. Using memcpy() to copy the 53 bytes only takes 32 us. Is copying to the serial buffer not the same as the memcpy() function? And why is there a difference in the copy times when the baud rate is different? Serial.write() is even slower with higher baud rates according to the results. Why does Serial.availableForWrite() return 63 while the buffer size is 64 (according to SERIAL_TX_BUFFER_SIZE)?

Update:
Thanks for all of your answers.

I have tried another library for serial communication: https://github.com/greiman/SerialPort

It seems to be faster than the original one.
I use 2 time measurements and a delay in the code, these 3 deltaTimes represents the whole step as follows:

writeTime + memcpyTime + delaymicros = computedTime != realTime

The first 2 times are measured, the delaymicros is the theoretical delay (900 us), I can compute the step time from these. This computed step time is different from realTime (the measured step time, I measure the whole step too). It seems that the additional time can be found in the delay.

SerialPort library:
100 + 30 + 900 = 1030 != 1350

writeReal = 100 + 1350 - 1030 = 430

Arduino Serial:
570 + 30 + 900 = 1500 != 1520

writeReal = 570 + 1520 - 1500 = 590

Then I measured the delaymicros time (which is 900 us in theory), the missing time can be found there. I programmed 900 us delay, but the real delay was around 1200 in the first, and 920 in the second test.

These measurements can prove the existence of the interrupts, because measuring only the write functions doesn't give all of the writing time (especially with the downloaded serial library).
The downloaded library can work faster, but requires bigger tx buffer because of errors (256 works properly instead of 64).

Here is the code: I use a checkSum in the sendig function (which is 570-532 = 38 us). I use Simulink to receive and process the data.

struct sendMsg1 {
  byte errorCheck;//1

  unsigned long dT1;//4
  unsigned long dT2;//4
  unsigned long t;//4
  unsigned long plus[10];//40
};//53

sendMsg1 msg1;
byte copyMsg1[53];

unsigned long time1;
unsigned long time2;
unsigned long time3;
unsigned long time4;

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

void loop() {
  sensorRead();
  sendMsg1_f();

  //time3 = micros();
  delayMicroseconds(900);
  //time4 = micros();
}

void sensorRead() {
  time3 = micros();

  msg1.t = micros();
  for (unsigned long i = 0; i < 1; i++) {
    memcpy((void*)&(copyMsg1[i*sizeof(sendMsg1)]), (void*)&msg1, sizeof(sendMsg1));
  }

  time4 = micros();
  msg1.dT2 = time4 - time3;
}

void sendMsg1_f() {
  time1 = micros();

  msg1.errorCheck = 0;
  for (int i = 0; i < sizeof(sendMsg1) - 1; i++) {
    msg1.errorCheck += ((byte*)&msg1)[i];
  }
  Serial.write((byte*)&msg1,sizeof(sendMsg1));

  time2 = micros();
  msg1.dT1 = time2 - time1;
}

If you take a look into the implementation:

size_t HardwareSerial::write(uint8_t c)
{
  _written = true;
  // If the buffer and the data register is empty, just write the byte
  // to the data register and be done. This shortcut helps
  // significantly improve the effective datarate at high (>
  // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
  if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
    // If TXC is cleared before writing UDR and the previous byte
    // completes before writing to UDR, TXC will be set but a byte
    // is still being transmitted causing flush() to return too soon.
    // So writing UDR must happen first.
    // Writing UDR and clearing TC must be done atomically, otherwise
    // interrupts might delay the TXC clear so the byte written to UDR
    // is transmitted (setting TXC) before clearing TXC. Then TXC will
    // be cleared when no bytes are left, causing flush() to hang
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      *_udr = c;
#ifdef MPCM0
      *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << MPCM0))) | (1 << TXC0);
#else
      *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << TXC0)));
#endif
    }
    return 1;
  }
  tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;

  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  while (i == _tx_buffer_tail) {
    if (bit_is_clear(SREG, SREG_I)) {
      // Interrupts are disabled, so we'll have to poll the data
      // register empty flag ourselves. If it is set, pretend an
      // interrupt has happened and call the handler to free up
      // space for us.
      if(bit_is_set(*_ucsra, UDRE0))
    _tx_udr_empty_irq();
    } else {
      // nop, the interrupt handler will free up space for us
    }
  }

  _tx_buffer[_tx_buffer_head] = c;

  // make atomic to prevent execution of ISR between setting the
  // head pointer and setting the interrupt flag resulting in buffer
  // retransmission
  ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
    _tx_buffer_head = i;
    sbi(*_ucsrb, UDRIE0);
  }

  return 1;
}

It basically answers all the questions.

If the buffer is empty and it's not sending anything, it'll send the character directly so it's synchronous (but sending the character will be much faster than overhead of function callbacks and so)

No, you cannot use memcpy, as it just replaces buffer, but it does nothing else, like actually start the data register ready interrupt nor proper setting of head/tail counters (it's round buffer, so there can be scenario you'll overwrite something outside of buffer)

And write function is called for each character separately (all other specialisation of write are using this one)

Also if the buffer is full, it'll wait until there is a space for another character.


How to use this Toggle Switch? I purchased this toggle switch recently because I want to use it in my project:

But I don't know what to connect up the three pins to and I can't find any information about it online. Nor can I find sample code. Can someone show me how to wire it up and provide sample code please?

It's basically a push button. Possible examples depend on what you want to do. As it seems, you simply want to start interfacing it with Arduino, just use it as a normal push button. Use the DigitalInputPullup example, that comes with the Arduino IDE:

Middle pin to pin 2 on the Arduino
One of the other pins to ground (depending on which state you want to be reflected with a HIGH in the Arduino)
The other pin unconnected

Look at these two schematics. The left one is a normal push button. It connects, when pressed and disconnects, when released. The right one is your button. When pressed it disconnects the upper  pin and connects to the lower pin. When released vice versa.  When you don't use the upper pin, your button behaves just like the push button on the left.

simulate this circuit – Schematic created using CircuitLab


Help managing the fallout from timer0 mode and prescaler change on ATMega2560 without modifying wiring.c For a driving application I need the PWM mode to be phase correct and the prescaler to be 1. The issue is that the board I am working with has the load hooked up to a PWM pin reliant on timer0. The firmware running on this board makes use of the delay(), delayMicroseconds(), and millis() functions from wiring.c. The goal is to make the timer0 change, shown below, and then make small modifications where the firmware calls the wiring.c timing functions. My approach was to find a scaling factor to be applied to the call of these functions. The scaling factor I came to was 32.12549, calculated by taking the wiring.c expected timer0 behavior: prescaler=64 and TOV0 flag every 256 counts, and comparing it to the actual values after my change: prescaler=1 and TOV0 flag every 510 counts

Calculation: 64*256/510=32.12549

Timer0 change:

// Set timer0 to phase correct PWM
TCCR0A = TCCR0A & 0b11111100 | 0x01;

// Set prescaler for timer0 to 1
TCCR0B = TCCR0B & 0b11111000 | 0x01;

The other timers are all configured in phase correct PWM mode, with a prescaler of 1.

...When I apply this scaling factor to a value returned from millis() to keep time it works well. For example the two pieces of code below proved to be equivalent through the timer0 change:

Use of millis() before timer0 change:

//current time
long unsigned now = millis();

//delay for 1 second
while(millis() - now < 1000){}

Use of millis() after timer0 change:

//current time
long unsigned now = millis();

//delay for 1 second, with x32.125 scaling coefficient
while(millis() - now < 32125){}

The two snippets of code above both delayed for 1 second

Now comes the problem: when I try to apply that same scaling factor to delay() or delayMicroseconds() it seems to give unreasonable delays...

Use of delayMicroseconds() before timer0 change:

// wait 1.5ms for mux to switch
delayMicroseconds(1500);

...this delays for 1.5ms

Use of delayMicroseconds() after timer0 change:

// wait 1.5ms for mux to switch, with x32.125 scaling coefficient
delayMicroseconds(48188);

...this delays for ~20ms.

Assuming this is still linearly scalable:
 if 48188 -> 20ms, therefore 1.5ms -> 3614

But when the following code is used...

// wait 1.5ms for mux to switch, scaled
delayMicroseconds(3614);

...this delays for ~4.5ms

Why is it that delayMicroseconds() and delay() cannot be linearly scaled to account for a timer0 change? Furthermore, is there any simple modification to how these functions are called or utilized that can account for the effect of changing timer0?

The millis() roll over

By making Timer 0 faster, your millis() will roll over much more
often than normal: every 37.1 hours instead of every 49.7 days. Thus,
when you “scale” millis(), you should be careful to do it in a
rollover-safe way. From the code you show, it appears that you are doing
exactly the right thing. Well done! Don't change anything. Don't be
tempted to scale the value returned by millis().

The overflow in delayMicroseconds()

As this function just burns cycles in a busy loop, it is not affected by
your configuration of Timer 0. You can just use it as is, with no
scaling. Beware however that it's argument should always be smaller than
16384 (on a 16 MHz board). Otherwise it will overflow when it is
multiplied by 4 in order to get a loop count.

For example, when you call delayMicroseconds(48188);, the function
computes the number of loop iterations to make as

48188 × 4 − 5 = 61675 (modulo 216)

Then, it burns about 15 ms of CPU time (0.25 µs per
iteration), which is close to the 20 ms you see. For the
difference, see below.

The cycles burned by the Timer 0 ISR

This ISR, which keeps the millis() counter updated, is supposed to run
every 1024 µs. Each time it runs it burns a few cycles, but it's
usually not a big deal. With your new timer configuration, it is now
running far more often: every 31.875 µs.

From the numbers you give in the question, I would say the ISR is
eating about 20% of your CPU power: when you call
delayMicroseconds(3614);, that function burns 3614 µs of CPU
time, yet you measure a delay of about 4500 µs. The difference is
taken by the Timer 0 ISR.

Use another timer for millis()

If you can spare a timer, you could both restore the normal behavior of
millis() and avoid wasting so much CPU in the Timer 0 ISR:

configure Timer 0 to not trigger interrupts
configure your spare timer just like the Arduino core would normally
configure Timer 0
write an overflow ISR for your spare timer that just calls the Timer 0
overflow ISR.

This way your spare timer is basically replacing Timer 0. Example using
Timer 2:

// This Timer 2 overflow ISR simply forwards the call to the Timer 0
// overflow ISR from Arduino core.
ISR(TIMER0_OVF_vect);
ISR(TIMER2_OVF_vect, ISR_NAKED) {
    TIMER0_OVF_vect();
    asm volatile("reti");

    // Alternatively, just:
    // asm volatile("jmp __vector_16");
}

void setup()
{
    // Set timer0 to phase correct PWM
    TCCR0A = (TCCR0A & 0b11111100) | 0x01;

    // Set prescaler for timer0 to 1
    TCCR0B = (TCCR0B & 0b11111000) | 0x01;

    // Disable Timer 0 interrupts.
    TIMSK0 = 0;

    // Configure Timer 2 to replace Timer 0.
    TCCR2A = _BV(WGM20)   // fast PWM, TOP = 0xff
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(CS22);   // clock at F_CPU / 64
    TIMSK2 = _BV(TOIE2);  // enable overflow interrupt

    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    // Blink the LED at 1 Hz.
    uint32_t now = millis();
    static uint32_t last_toggle;
    if (now - last_toggle >= 500) {
        last_toggle += 500;
        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    }
}

I wrote a “naked” ISR to avoid having plenty of CPU registers saved and
restored twice (once by each ISR in the call chain), but then I had to
put the return instruction explicitly in assembly (ret and reti
would be equivalent in this instance). The version with jmp is
slightly more efficient, but you have to know the “real” name of the
ISR, which is MCU-dependent (__vector_16 on an Uno).

Notice that with this technique micros() will not work, as it reads
TCNT0 directly. And delay() will not work either because it relies on
micros().


Fatal Exception Error on ESP8266 + Arduino When I was trying to blink an LED using ESP8266, I had an issue with it. After successfully uploaded the code (https://diyhacking.com/esp8266-tutorial/), the blue LED stayed on & when I opened the serial monitor using Arduino IDE 1.6.12, I only saw "Fatal Exception" error (showed in the picture). I couldn't see how the code works and the worst thing was I couldn't even try the AT command.

The connections:

Arduino <--->   ESP8266 (ESP-07)

Tx  <--->   Tx
Rx  <--->   Rx
GND <--->   GPIO0
GND <--->   GND
3.3v<--->   CH_PD
3.3v<--->   VCC
            GPIO2 -> LED

I have been trying to troubleshoot this issue but haven't got the solution yet. I am afraid there is an issue with the firmware or the worst situation, I spoiled my ESP8266.

Looking at your serial monitor window it shows "Geuino Uno". I think you forgot to change the target of the compiler to "Generic ESP8266" like shown in the how-to and you probably uploaded bad code to your module.


Post-split, where do I download the Arduino IDE? I've been out of the loop with Arduino for several years.  I heard about the split (another link), but didn't really understand, nor keep up with it, nor the details of the fallout.

Today, I decided to jump back in and make something, and a DDG search led me to Arduino.cc to get the software.  But is that what I need?

How do I know if that's the right software IDE?  Is there another location?  Does it matter?  Does it depend on more variables?  Is this split akin to the OpenOffice and LibreOffice split, where one is more better (technical term!) supported than the other?

I'm working on an Arduino Uno I got from Microcenter.

The split is already over. They are working on merging everything that happened during the split, if they haven't already.

I'd go with the arduino.cc version, as that was the website before the split (where the other party used arduino.org).


SD card example freezes at line SD.begin() what should I do? I have a 16GB SD card which is formated with FAT32. I'm trying to run the example codes presented for SD in Arduino. The SD card is inserted in the data logging shield and the CS pin in this shield is connected to pin 10.
I first tried the Cardinfo example and this is the result:

The SD card is not empty, there exist a few files in it but this example was unable to show this files.
I then tried the example ReadWrite and the code freezes on line SD.begin(10).
I have no Idea where this problem is coming from.

I found another SD with 16GB capacity, and fortunately it worked. So the problem was because of the SD but I don't know what was the exact problem. I post the photo of this SD cards.


OSC parsing code. Can it be optimised? I'm using this OSC library and TouchOSC to controls some motors.
Right now I'm receiving those two kind of messages:

/u/1       // move motor 1 of default steps
/u/2       // move motor 2 of default steps

/u/1/5     // move motor 1 of 5 steps
/u/3/25    // move motor 1 of 25 steps

and so on.

Right now I have this piece of code:

void loop() {
  OSCMsgReceive();
}

void OSCMsgReceive() {

  OSCMessage msgIN;
  int size;
  if ((size = Udp.parsePacket()) > 0) {
    //Serial.println("incoming message.. ");
    while (size--) {
      byte n = Udp.read();
      msgIN.fill(n);
      Serial.print((char)n);
    }
    Serial.println();
    if (!msgIN.hasError()) {
      msgIN.route("/u", up);
    }
  }
}

void upValueExtraction(char *ca, int &num_motor, int &num_step) {
    String s = String(ca);
    String num_motor_s = "";
    String num_step_s = "-1";
    int n = 0;
    for(int i=0; i<s.length(); i++) {
      char c = s[i];
      if(c=='\\') {
        n++;
      }
      if(n==0) num_motor_s += c;
      if(n==1) num_step_s += c;
    }
    Serial.print("num motor: "); Serial.println(num_motor_s.toInt());
    Serial.print("num step: "); Serial.println(num_step_s.toInt());

    num_motor = num_motor_s.toInt();
    num_step = num_step_s.toInt();
}

void up(OSCMessage &msg, int addrOffset) {
  static boolean flag = false;
  if (!flag) {
    Serial.print("route: up "); Serial.println(addrOffset);

    char ca[200];
    msg.getAddress(ca, addrOffset+1);

    int num_motor, num_step;
    upValueExtraction(ca, num_motor, num_step);

    if(num_step==-1) {
      num_step = defaul_steps;
    }

    Serial.print("Have to move motor n ");
    Serial.print(num_motor);
    Serial.print(" of step ");
    Serial.println(num_step);
  }
  flag = !flag;
}

Even if it is working and even if I'm using an Arduino DUE (much more memory then the UNO) I think it can be optimised.

Does it contains some leeks? How can I better use the OSC matching part of the library? Any kind of "embedded c++" guidelines? Can I do everything inline without a ca char array and s String variables? Is better to use Arduino Lib String class or plain old C str* functions? Any kind of comment?

Thanks in advance.

OSC is such a simple format that I ended up ditching libraries entirely, and just parsing the UDP packets directly with a state machine.  Just learn the wire format of the bytes and parse the state machine explicitly.

It's just a trivial function calling format.  The message starts with a 32-bit padded zero terminated string (important!) for the method name.  I am not sure if the type tag is mandatory but it was always being sent (ie: ",iff"), then the binary values corresponding to what type tag says - like bigendian int32,float32,float32.

This was related to OSC generated by ChucK, SuperCollider, and CSound.

Real optimizations would come just from the design of the protocol itself.  You will need to assume that any UDP packet can be dropped.

You are sending motor changes as diffs from current position, so you need to handle packet drops somehow.  (ie: Do you have a TCP-like mechanism?  Do you change the design to send absolute motor positions so that position reports are idempotent and subject to re-broadcast?  Do you ack message receipt individually, or do you periodically poll the device for its current state?)


How to change the topic_name string to PROGMEM? I'm trying to save SRAM on my Arduino pro mini by going through some libraries. I've noticed that to use my Arduino as a ROS node the library stores the topic name and message type as constants.

class Publisher
{
public:
  Publisher( const char * topic_name, Msg * msg, int    endpoint=rosserial_msgs::TopicInfo::ID_PUBLISHER) :
    topic_(topic_name),
    msg_(msg),
    endpoint_(endpoint) {};

  int publish( const Msg * msg ) { return nh_->publish(id_, msg); };
  int getEndpointType(){ return endpoint_; }

  const char * topic_;
  Msg *msg_;
  // id_ and no_ are set by NodeHandle when we advertise
  int id_;
  NodeHandleBase_* nh_;

private:
  int endpoint_;
};

How can I store the constants to PROGMEM? Thank you

My take on this is that you cannot save more memory on topic-name nor msg parameters. Their memory usage is already optimized.

The const keyword in the constructor declaration Publisher( const char * topic_name, Msg * msg, ... just tells the compiler that the parameter won't be changed throughout their life cycle. But their values will be defined at run-time during object creation when you issue something like this:

Publisher pb = new Publisher("topic", "message", ...);

So, they cannot be put into flash memory if they are not there already. But if the strings you pass on to the constructor are already in flash, then you're already saving those bits of RAM.

Finally, I just wanted to warn you not to modify 3rd party lib code extensively without comprehensive testing, like you are trying to do. You'll start to get strange behavior in your code. The slightest and simplest of changes may have unforeseen consequences.


Problem building a smart shopping cart I'm building a smart shopping cart with Arduino for my final year project.

The cart is supposed to be able to follow its user while shopping. I don't know of many feasible indoor positioning systems to use.

Proposed solution 1

I have recently seen some RF/ultrasonic positioning systems that make use of:

one ultrasound transmitter and one RF receiver, carried by the person,
and two ultrasound receivers and one RF transmitter carried by the robot.

The robots RF transmitter sends out a signal, which when received by the person's RF receiver, triggers the person's ultrasound transmitter to transmit a signal. This signal is received by the robot's two ultrasound receivers (with a distance, d between them), and the distance and angle to the target person can be calculated.

That sounds very feasible, but my question is, if the robot is in a crowded place, where the other people are also carrying ultrasound transmitters and RF receivers:

Will the RF signal meant for the owner of the robot be accidentally received by the RF receiver on another person, or is there some kind of unique ID shared between RF receiver/transmitter pairs that could prevent this problem, or maybe some kind of frequency hopping system, so there would be no mistaken identity.
How will the ultrasound receivers on the robot be sure that the received signal is from its matching ultrasound transmitter. Again, is there some kind of special ID systems employed by some ultrasonic transmitter/receivers.

Proposed solution 2

I have also read about this new device called Trackr, it makes use of bluetooth low energy to track objects based on their proximity to bluetooth enabled devices like smart phones.

Considering a scenario where various bluetooth devices (beacons) are placed at specific points in a room, and the target to be tracked is equipped with a bluetooth emitter/bluetooth chip/dongle.

When the target passes each of those beacons, the signal strength intensity is received and distance from the target is calculated.

I understand this concept, but have some questions:

When distance is calculated between beacon and target, what about the angle, how would the robot follow the target based on distance alone?
If this method is not accurate enough to be used in a crowded space, what other method can be used, I have checked out some indoor GPS devices and they are way to expensive (above $200).

Would a camera-based tracking system be better and how easy would it be for a non expert like me to implement.

I have a couple of ideas for you but know these are only suggestions. No hate please.

Have you tought of IR following?

IR is a almost unique signal that only you have. You can either use multiple IR sensors to determine where the emitter is or you can use the servo motor to do it as a radar. Note that you have to isolate each sensor so it knows where you are and it doesn't captures the wave from a different angle by accident.

Extra safety?

You can also incorporate an untrasonic distance sensor so that the cart doesn't bump into you or any one. Like you can say, if the distance is smaller then 12 inchs / 30 cm, stop the cart. It is practically an extra safety feature.


Using A 4 Ohm Speaker With Arduino I've salvaged a 4 Ohm, 1.5 Watt speaker from an old computer, and I was wondering how I'd go about getting it to work with my Arduino. I've heard of various amplifier circuits such as opamps, but I do not know which would be the best for my situation. I've also heard that using the speaker in certain ways (such as directly connected to a pin from the Arduino) could damage both the speaker and the output pin, so that is definitely something I'd like to avoid. I'm not looking for anything complicated; I'm just trying to get a feel for the general circuitry, programming, and speaker volume. Any suggestions?

5v, 4ohm, >1amp from a pin rated for 0.04amps; this isn't safe!
You would need a driver, but it would suffice to add a small transistor & a couple of resistors to drive it; here is a slightly more complex layout, there are many examples on the web.


how to send data to 15 meters with KY-005 I am using the LED KY-005 as emitter and the KY-022 as a receiver, according to their specifications they reach 18 meters.
I have performed the tests and it supports more than ten meters, however after the 6 meters the data is not received correctly. For example, I send 0xa90 but any other value except the desired one arrives at the receiver.
Here I leave the connection diagram:

This is the code that I use to send data:

#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     delay(40);
   }
}

In the emitter breakout board there is only a LED, nothing more. Comments in the linked page of the supplier states, that the 5V pin of it is not connected to anything. This means you are driving the LED directly from the Arduinos pin, which cannot provide more than 40mA. The supplier states a forward current from 30 to 60mA. You can use a small MOSFET in combination with a resistor, that limits the current to maybe 55mA, to drive the LED indirectly.

With this you won't fry the pins hardware and can provide more current, which means the LED can shine brighter. If you can find out, what LED is actually used for this board, you can refer directly to its datasheet. I couldn't find a part number at the site.


Adding slave device to Arduino Uno-SPI | Configuring pins I recently started an oled project. I use a small "128X64 OLED LCD LED Display Module" and I control it using SPI protocol(with my Arduino).

It is the only device connected to the microcontroller. But I have some questions regarding the pins. I found this tutorial and it uses pins 9 as DATA(known as MOSI) and 10 as CLK( or SCK). But the datasheet for my microcontroller(328) shows that pin 11 is MOSI and 13 is CLK.

Obviously..it works. So I think the program provided by the adafruit(that I used-Adafruit_SSD1306) took care of MOSI and generated the clock impulses on pin 10.etc. . But then what are those pins on the board and why are called like that? I mean it seems to me that everyone can just use other pins for MOSI/CLK(at least).What is their purpose?

Question #2: What does DC (or D/C) means?

#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

VS

(328<=>128)

You can answer these questions by opening the library and looking "under the hood". This is the most beautiful advantage of open source projects.

Here are the links to the relevant files in the library, so I can comment on them.

INO example file
Library header file
Library source file

Ok, first of all let's have a look at the example. you can see that the constructor is called as

Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

When looking at the lines 144 and following of the source file, you can see

hwSPI = false;

Wait, this means that it is not using the hardware SPI? Sure! In the following overload, then, you can see that if you call the constructor as Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS), you will use the hwSPI.

Now, I'm not sure whether you know the difference between HW and SW implementations, so here they are. The HW implementation is a peripheral which can run "on its own" and provide the microcontroller the results (automatically send and/or receive the bytes). The SW one, on the other hand, is an emulation done by the microcontroller.

You can also see it in the example:

// If using software SPI (the default case):
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

/* Uncomment this block to use hardware SPI
#define OLED_DC     6
#define OLED_CS     7
#define OLED_RESET  8
Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
*/

So you can use the second part to initialize a display which will use the hardware SPI (so MISO = 12, MOSI = 11, SCK = 13). If you want to free the microcontroller in order to be able to do other tasks, use the HW peripheral.

As fot the DC pin, it is labeled "DataCommand". I think it is a pin to tell the controller whether the data shared through the SPI port is a command or it is data


How to disable Arduino Yun to work as Access Point and set it to work as needed? I am using Arduino Yun and I would like to disable it to work as Access Point. That is, I don't want that it is displayed in the list of available networks.

Then I would like to set and use it (separately) in the following scenarios:

a) Arduino Yun connected just over a given Wi-Fi network (Ethernet connection disabled).

b) Arduino Yun connected just over Ethernet (Wi-Fi connection disabled).

How can I make it?

Note: In my previous attempts I tried to customize and/or disable someway the Wi-Fi connection (through the LuCI panel) in order to reach what I am looking for but in all of these cases I had to restore my Arduino Yun from scratch because it did not work anymore.

Yun expects wifi to be working and, if it's not, it will reboot itself after 60 seconds and return in access point mode.

In order to disable this check, edit file /etc/rc.local and turn wifi-live-or-reset into #wifi-live-or-reset (with a starting #).

Once done, use LuCI (the advanced configuration panel) to configure network interfaces.


Unable to declare variable in a library that doesn't have a class: multiple definition of the variable I have created a library Lib that doesn't have a class. I want this library to have a variable that can be accessed from outside. The way I would go about this is to just declare them in the header file.

However, if I do this like so:

int myVariable = 1;

with the .cpp-file containing only

#include "Lib.h"

I get this error message when compiling an empty sketch that includes this library:

  multiple definition of `myVariable'

and for some weird reason

  Multiple libraries were found for "Lib.h"

on top of that (although, this is something I have encountered before - when there is some error during the compilation, this error may come alongside it, even though there are no multiple libraries; it goes away when the other compilation errors are resolved aswell).

What is causing that error and how to resolve it?

In Lib.h you should declare an

extern int myVariable;

In Lib.cpp you can define it once

#include "Lib.h"
int myVariable=123;
...


How can I sense very high temperatures with Arduino? I've seen many temperature sensors, but the highest temperature they go up to is 125 degrees C (257 degrees F). I want to reach higher temperatures than that. I'm thinking about rigging up a closed loop sensor for my soldering iron (for a convenient LCD display), but I can't find out how to sense the temperature of the tip due to the higher operating temperature than most sensors.

You probably want to use a thermocouple. It'll give you the ability to measure much higher temps than regular temperature sensor. You'll also need a IC like the MAX6675 to interface with it.

  The MAX6675 performs cold-junction compensation and digitizes the
  signal from a type-K thermocouple. The data is output in a 12-bit
  resolution, SPI™-compatible, read-only format.

  This converter resolves temperatures to 0.25°C, allows readings as
  high as +1024°C, and exhibits thermocouple accuracy of 8 LSBs for
  temperatures ranging from 0°C to +700°C.

Page 6 of the datasheet has the serial interface protocol information and. You can really just set the Chip Select line and it'll give you 16 bits of information, 12 of which will be the temperature.


I would like to add a RGB led strip to my arduino alarm system I am new to programming and would be grateful for any helpful answer...Thank you
I used a ping sensor, a piezo buzzer and an RGB strip. I used the Schematic from Adafruit Learning System..
Here is my code:

#define trigPin 5
#define echoPin 6
#define RED_PIN    10
#define GREEN_PIN   11
#define BLUE_PIN  9
int Buzzer = 3;

void setup() {
    //set pinModes for RGB strip
    pinMode(RED_PIN,OUTPUT);
    pinMode(BLUE_PIN,OUTPUT);
    pinMode(GREEN_PIN,OUTPUT);

    pinMode(Buzzer, OUTPUT);

    //reset lights
    analogWrite(RED_PIN,0);
    analogWrite(BLUE_PIN,0);
    analogWrite(RED_PIN,0);

    delay(5000);
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(Buzzer, OUTPUT);
}

void loop() {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance >= 80 || distance <= 0){
        Serial.println("No object detected");
        digitalWrite(Buzzer, LOW);
    } else {
        Serial.println("Object Detected");
        tone(Buzzer, 1000); // play 400 Hz tone for 500 ms
        delay(500);
        tone(Buzzer, 10000); // play 800Hz tone for 500ms
        noTone(Buzzer);
    }
    delay(300);
}

An interesting problem with the Arduino paradigm is that not only do you need basic programming knowledge but you also need basic electronics knowledge.

On the plus side, there are plenty of good tutorials where you can over look these issues if you follow the tutorials step by step.  That is, get exactly the same parts and wire them up exactly the same way.  Later, if you like, you can go over the tutorial, ask questions here and discover how and why what you did works.

In your diagram:

You are implying you are using ordinary Red, Green & Blue LEDs and are going to vary their brightness using the Arduino's Pulse Width Modulation feature.

Possible problems:

You are powering the LEDs from the 9 volt pin of the Arduino.  And the LED strip in the diagram is clearly marked 12 volts.  This may work.  But is out of specification.

Also, this setup makes the assumption you are powering your Arduino with a 9 volt wall power supply.  Are you?  You could also power the Arduino with 5 volts using only the USB cable.  There would then be no 9 volts available at the 9 volt pin.  (I would avoid plugging in both power sources at the same time.  I think the Arduino design has changed over time.)

You are using a strip of Red, Green & Blue LEDs.  Which implies more than 1 of these Red, Green & Blue LEDs.  There is an upper current limit on the outputs of the Arduino.  More LEDs means more current.  Too many LEDs will damage the Arduino.  I would stick to 1 LED until you research the amount of current 1 LED takes verses the upper current limit of an Arduino output pin.


Speed of built in DAC/ADC in Arduino Due Can someone tell me how fast the built in DAC (and ADC) in an Arduino Due can be written or read? I currently don't have the equipment to measure but need the information to plan my next steps.

I try to move galvanometer mirrors and want to make the voltage/position updates as small as possible. How fast are the internal DACs compared to an SPI connection (where I have to write 2 Byte).

See sections 43, Analog-to-Digital Converter (ADC), and 44, Digital-to-Analog Converter Controller (DACC), in the Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf specsheet.

In particular, subsection 43.2, Embedded Characteristics, says: “1 MHz Conversion Rate”.  Some time diagrams appear quite a few pages later that suggest 10-bit conversions can be done more rapidly than 12-bit.

For the DAC (or DACC, per the specsheet), section 44.6, Functional Description, says:

  The DACC uses the master clock (MCK) divided by two to perform conversions. This clock is named DACC Clock.
  Once a conversion starts the DACC takes 25 clock periods to provide the analog result on the selected analog
  output.

AIUI, the Due's master clock frequency is 84 MHz, so DACC Clock frequency is 42 MHz, whence 25 cycles take 575 ns, which is an update frequency of about 1.74 MHz.

For more details about the ADC, see eg
Analog performance, particularly of Due's 12 bit ADC at djerickson.com.


Single & multi sensor code I have been having problems trying to run multi sensor code for my project, this requires four KY-024 Linear magnetic Hall sensors as position sensors that trigger NC independent relays to make a circuit.
I can get the code to run on one independent circuit, one hall switch one relay with no problems.
But when I try the code for 4 hall sensors + relays I get no response from the circuit at this point I am at a loss where to go from here the code compiled with no problems.

int hallswitch = 1;
int val = 0;
int RELAY1 = 6;

void setup() {
  pinMode(hallswitch, INPUT);
  pinMode(RELAY1, OUTPUT);
}

void loop() {
  val = digitalRead(hallswitch);

  if (val == HIGH) {
    digitalWrite(RELAY1, HIGH);
  }
  else {
    digitalWrite(RELAY1, LOW);
  }
}

and

int hallswitch1 = 1;  //Pin for Hall switch
int hallswitch2 = 2;  //Pin for Hall switch
int hallswitch3 = 4;  //Pin for Hall switch
int hallswitch4 = 5;  //Pin for Hall switch

int val = 0;       //Integer for reading Hall statu

int RELAY1 = 6;    // The socket number on the Arduino that the relay1 will go to.
int RELAY2 = 7;    // The socket number on the Arduino that the relay1 will go to.
int RELAY3 = 8;    // The socket number on the Arduino that the relay1 will go to.
int RELAY4 = 9;    // The socket number on the Arduino that the relay1 will go to.

void setup()
{
  pinMode(hallswitch1, INPUT);
  pinMode (RELAY1, OUTPUT);

  pinMode(hallswitch2, INPUT);
  pinMode (RELAY2, OUTPUT);

  pinMode(hallswitch3, INPUT);
  pinMode (RELAY3, OUTPUT);

  pinMode(hallswitch4, INPUT);
  pinMode (RELAY4, OUTPUT);
}

void loop() {
  val = digitalRead(hallswitch1);               //Read Hall pin status
  val = digitalRead(hallswitch2);               //Read Hall pin status
  val = digitalRead(hallswitch3);               //Read Hall pin status
  val = digitalRead(hallswitch4);               //Read Hall pin status

  if (val == HIGH) {                        //If there is a magnet infront of Hall switch...
    digitalWrite(RELAY1, HIGH);             // Turn RELAY1 on:
    digitalWrite(RELAY2, HIGH);
    digitalWrite(RELAY3, HIGH);
    digitalWrite(RELAY4, HIGH);
  }
  else {
    digitalWrite(RELAY1, LOW);               // Turn RELAY1 off:
    digitalWrite(RELAY2, LOW);
    digitalWrite(RELAY3, LOW);
    digitalWrite(RELAY4, LOW);
  }
}

This is the quick and dirty way, I would suggest re writing it to use arrays rather then having to declare all these variables and copy paste pinMode, read,writes if statments a bunch of times.

 int hallswitch1 = 1;  //Pin for Hall switch
 int hallswitch2 = 2;  //Pin for Hall switch
 int hallswitch3 = 4;  //Pin for Hall switch
 int hallswitch4 = 5;  //Pin for Hall switch

 int val1 = 0;       //Integer for reading Hall statu
 int val2 = 0;
 int val3 = 0;
 int val4 = 0;

 int RELAY1 = 6;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY2 = 7;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY3 = 8;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY4 = 9;    // The socket number on the Arduino that the relay1 will go to.

void setup()
{

  pinMode(hallswitch1, INPUT);
  pinMode (RELAY1, OUTPUT);

  pinMode(hallswitch2, INPUT);
  pinMode (RELAY2, OUTPUT);

  pinMode(hallswitch3, INPUT);
  pinMode (RELAY3, OUTPUT);

  pinMode(hallswitch4, INPUT);
  pinMode (RELAY4, OUTPUT);

}

void loop() {

  val1 = digitalRead(hallswitch1);               //Read Hall pin status
  val2 = digitalRead(hallswitch2);               //Read Hall pin status
  val3 = digitalRead(hallswitch3);               //Read Hall pin status
  val4 = digitalRead(hallswitch4);               //Read Hall pin status

  if (val1 == HIGH) {digitalWrite(RELAY1, HIGH);}
  else {digitalWrite(RELAY1, LOW);}

  if (val2 == HIGH) {digitalWrite(RELAY2, HIGH);}
  else {digitalWrite(RELAY2, LOW);}

  if (val3 == HIGH) {digitalWrite(RELAY3, HIGH);}
  else {digitalWrite(RELAY3, LOW);}

  if (val4 == HIGH) {digitalWrite(RELAY4, HIGH);}
  else {digitalWrite(RELAY4, LOW);}

}


Why doesn't my code work in a function, yet works inline? I'm trying to write a faster shiftOut function, which does not use the slow digitalWrite. In my code I have the original shiftOut, the new shiftOutFast, and the same as shiftOutFast, but inline. The three blocks are separated by delays to tell them apart on my scope. Here's the code:

#define CLR(x,y) (x &= (~(1 << y)) )
#define SET(x,y) (x |= (1 << y) )

void shiftOutFast(uint8_t dataPort, uint8_t dataBit, uint8_t clkPort,
                  uint8_t clkBit, uint8_t bitOrder, uint8_t val) {
  for (uint8_t i = 0; i < 8; i++)  {
    if (bitOrder == LSBFIRST) {
      if (val & 0x01) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val >>= 1;
    } else {
      if (val & 0x80) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val <<= 1;
    }

    CLR(clkPort, clkBit);
    SET(clkPort, clkBit);
  }
}

#define dataPin 4
#define clockPin 5
#define dataPort PORTD
#define dataBit PORTD4
#define clockPort PORTD
#define clockBit PORTD5

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

void loop() {
  shiftOut(dataPin, clockPin, LSBFIRST, 0x55);
  delay(1);

  shiftOutFast(dataPort, dataBit, clockPort, clockBit, LSBFIRST, 0x5C);
  delay(1);

  bool bitOrder = LSBFIRST;
  uint8_t val = 0x5C;

  for (uint8_t i = 0; i < 8; i++)  {
    if (bitOrder == LSBFIRST) {
      if (val & 0x01) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val >>= 1;
    } else {
      if (val & 0x80) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val <<= 1;
    }

    CLR(clockPort, clockBit);
    SET(clockPort, clockBit);
  }
  delay(1);
}

The problem is that calling shiftOutFast doesn't do zilch. Absolutely nothing. It doesn't seem to be the logic, because when I do the same inline it works. Any ideas?

The problem is that you are passing the value of the ports to the function, not the address of the ports.

You need to either pass "by reference" or as a pointer, so that modifying the port variable modifies the actual port variable not the copy of the value that you pass.

The simplest way is to modify your function to be:

void shiftOutFast(volatile uint8_t &dataPort, uint8_t dataBit,
                  volatile uint8_t &clkPort, uint8_t clkBit,
                  uint8_t bitOrder, uint8_t val) {
....
}

That way, instead of passing whatever is in the port at the time to the function (pass by value) it instead creates a new variable which is located at the same address as the variable that you are passing (pass by reference) so modifications of one variable modifies the other.

Note that only the "port" variables need to be passed by reference, all the others remain as pass by value.  Also they should be, as Edgar says, flagged as volatile.


Serial.write(buf, len) error. How to remove an error and pass an array of bytes? int angleServo1,angleServo2 = 0;
const int axisX=A0; // ось Х подключена к A0
const int axisY=A1; // ось Y подключена к A1
int valX, valY = 0; // переменные для хранения значений осей
int datos[3];
#include <SPI.h>

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

void loop()
 {
      valX = analogRead(axisX); // значение оси Х
      valY = analogRead(axisY); // значение оси Y
      // масштабируем значение к интервалу 0-180
      angleServo1=map(valX,0,800,100,-100);
      angleServo2=map(valY,0,810,100,-100);

       datos[0] = angleServo1;
       datos[1] = angleServo2;
       Serial.write(datos, sizeof(datos));
       delay(100);
}

error: no matching function for call to 'HardwareSerial::write(int [3], unsigned int)'

how to remove an error and pass an array of bytes?

You want to send data to computer processing or print them for user to read? Functions write send raw data. To print the data to Serial monitor print and println functions are used.

There are two write functions. First sends one byte. Second sends array of bytes. There is no write function to send array of ints. You could cast the array of ints to array of bytes to send the array as raw bytes for processing on the receiving side. But then you first should perhaps send to the receiving side some control data about the data package.

  Serial.write((byte*) datos, sizeof(datos));

If you want to print numbers to Serial Monitor, the print functions have variants which take a number and convert it to string. But there is no print function to print an array of numbers. You must print them one by one in a for loop. And put some separator between them (coma, space, new line).


Arduino IDE fails on Fedora with arduino-builder error "Parameter 'tools' is mandatory" The arduino-builder app when invoked directly with parameter --tools /usr/bin works, but the IDE fails with the error in the title for any sketch (including the Blink example).

I've tried adding things to preferences.txt like

tools.path=/usr/bin

And variations, but I keep getting the same failure in the IDE.  This is using a fresh distro package install on Fedora 27 (I did not have this problem previously using Fedora 25).

I don't understand why this worked, but I found this comment in Redhat Bugzilla (it doesn't seem to be a bug report specifically about that...but anyway):

    Parameter 'tools' is mandatory
    [...]

  However, if I create the packages directory in ~/.arduino15, compilation now works.

mkdir ~/.arduino15/packages

Seemed like an easy thing to try, and voila -- after an hour of fuss.

I do not understand why this is so (nothing ends up in that directory, either) but I'm leaving this in hopes it may save someone else some time.


My arduino won't show up in Device Manager in any way, neither in unknown devices nor in COM port. I have a brand new arduino(original), and it is not showing up in Device manager or anywhere else. Even the computer doesn't Prompt anything. I am using Windows 7 32 bit.

As the OP reported: It worked with a different cable.

I converted his comment to an answer so the system would regard this issue as solved. Please accept this answer.

Some cheap USB cables only carry power, and not data. I have such a cable that came with a USB desk light. To save money they only run two wires and not four, since the desk light is not a data device.

Be cautious about grabbing any old cable from your desk for testing. Make sure it is designed for data use. If in doubt, try a known good cable.


How to set CS pin on Beetle BLE/Bluno Beetle to Adafruit SD Card Breakout - Initialization Failed! Hi I have a Beetle BLE (https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339) and I am trying to connect an Adafruit MicroSD card breakout board+ (https://www.adafruit.com/product/254) via SPI connections. I am trying the following code, but I am having trouble selecting the CS pin using D4 since the Beetle has no D10. Does anyone know if I am selecting D4 correctly, while keeping pin 10 as an output. I keep getting initialization failed! My setup is on the ICSP 6 pin configuration:

5V --> 5V

MISO --> DO

SCK -->CLK

GND --> GND

MOSI --> DI

D4 --> CS

RST is left out

Here is my code:

#include <SPI.h>

#include <SD.h>

File myFile;

void setup()
{
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
//   pinMode(4, OUTPUT);
   pinMode(10, OUTPUT);
//   digitalWrite(4, HIGH); // Add this line

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.

  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
  // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop()
{
  // nothing happens after setup
}

The ICSP header labels on the Wiki page are wrong. In the schematic here the ICSP header has the same pinout as other Arduinos. The legend doesn't match the picture on the Wiki page but is true:

ICSP1: Atmega 328P
ICSP2: CC2540

The ICSP header is the inner one. Is right on the pictures.
At pin 1 on board the corner of the white square around pins is skewed. The pins are from left to right first row Eeset, CLK, MISO, second row Ground, MOSI, 5 V.

pdf schematic for the board


How to connect Flora 2 and nRF8001 BLE Breakout I'm trying to get the nRF8001 BLE Breakout polling properly on Flora but Adafruit's tutorial and everything I've read and hunted around but I'm new to Arduino and not really sure how the Adafruit_BLE_UART library is handling I/O on the various pins. I'd appreciate it if anyone knows the proper pin configuration to get this working. I'm not in a position where I can easily change out to a better BLE device for my Flora.

So it's clear I have

SCK connected to SCK.
MISO to MISO, I've also tried it in D12 with the same outcome.
MOSI in MOSI, there's no D11 on this board so I couldn't try that.
REQ in D10.
RDY in SDA, which is supposed to correspond to D2 (besides SCL I don't think there are any other interrupt pins).
RST in D9, also tried it in the Reset SPI, doesn't seem to make any difference.

In short I'm using all the appropriate SPI pins and two of the data pins mentioned in the BLE tutorial, and I've tried a couple other configurations without much success.

And it appears to be powered properly.

using echoDemo, getState always returns the disconnected opcode. Polling apparently does nothing, setDeviceName does not set a name. I think either MISO or MOSI or both are the problem here. I can blink the LED, and other peripherals are working okay. (Crossposted to Adafruit forums.)

Some code:

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

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

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

void setup(void) {
  Serial.begin(9600);
  while(!Serial); // Leonardo/Micro should wait for serial init
  Serial.println(F("Adafruit Bluefruit Low Energy nRF8001 Print echo demo"));
  BTLEserial.setDeviceName("NEWNAME"); /* 7 characters max! */
  BTLEserial.begin();
}
aci_evt_opcode_t laststatus = {5};

void loop() {
  // Tell the nRF8001 to do whatever it should be working on.
  BTLEserial.pollACI();
  // Ask what is our current status
  aci_evt_opcode_t status = BTLEserial.getState();
  Serial.println(laststatus);
  Serial.println(status);
  Serial.println(ACI_EVT_DEVICE_STARTED);
  Serial.println(ACI_EVT_CONNECTED);
  Serial.println(ACI_EVT_DISCONNECTED);
  delay(1000);
  // If the status changed....
  if (status != laststatus) {
    // print it out!
    if (status == ACI_EVT_DEVICE_STARTED) {
        Serial.println(F("* Advertising started"));
    }
    if (status == ACI_EVT_CONNECTED) {
        Serial.println(F("* Connected!"));
    }
    if (status == ACI_EVT_DISCONNECTED) {
        Serial.println(F("* Disconnected or advertising timed out"));
    }
    // OK set the last status change to this one
    laststatus = status;
  }
}

The SPI bus can be accessed using a 6 pin header located next to the embedded processor.  Look at the embedded image below. Locate the 6 pin header just to the right of the processor.  Note the white dot indicating pin1 of the header.  Now look at the bottom of the embedded image to see the definitions of the 6 pins.  MISO, MOSI and several other SPI signals are listed.


Using multiple laptop battery packs to power everything I'm working on a medium sized robot project with multiple arduinos to control stuff. I've been planning on using a lead-acid battery pack, but then I was given 10 working and identical Asus laptop battery packs rated at 14.8 V 4400 mAh, and one old Asus laptop.

I opened up one of the battery packs, because it was bad and it has a 4S2P battery configuration and a protection board.

Can I hook all of these battery packs in parallel, or will power leak between the battery packs, and is that be a problem?

Is there alternatively some 4S20P or 3S25P battery pack with charger I can purchase to put these batteries in?

(I do have a step-down converter that will provide the Arduinos with the right voltage, regardless of input voltage up to 36 V)

I tried to ask a similar question on electrical engineering, but ot was deemed off topic for the site.

I'd be cautious about hooking them in parallel. According to ADAfruit power leakage between batteries is a problem.

  [multipack parallel] ... batteries are assembled by a company that is experienced and certified to test and assemble battery packs. The individual batteries are tested and sorted by machine so that each pack has matching batteries with the same capacity and internal resistance. Individuals do not have this equipment, which is why you should not try to make your own packs.

Are you certain all your batteries are the same age and have the same usage history? A brand-spanking new one will try to charge an old worn battery to its own fresh voltage.


How much power can the Teensy 3.2 deliver to external components? Can a teensy 3.2 deliver enough power to properly activate multiple servos by chance?

No.  You should provide your own regulator or supply for the servos specified voltage.

This might be an original design, or an off-the-shelf "battery eliminator" intended for an R/C vehicle of similar needs.

Note that the teensy regulator's maximum input voltage is fairly low, and may be in the range of what more powerful servos expect, ie, you might be able to run the teensy regulator off of the servo supply.

Be sure to consider the possibility of brownouts - multiple active or stalled servos can consume a lot of power, and if your upstream supply is not "stiff" enough this can result in the voltage dropping low enough that control electronics misoperate or reset - granted that is less likely with the teensy than with a 5v MCU using a regulator with a higher voltage dropout.


5v relay module and bulb holder Hello sir , so can i cut the switch from the picture and connect the wires to my relay module ? Im sorry because im still learning . Thank you !

A relay is nothing more than a switch - but instead of your finger controlling it, it's controlled by an electromagnet.

The relay can perform the exact same function as the switch on that cable.  In the image you have posted you would use the right-hand two screw terminals (middle is "common", right is "normally open") to replace the switch.


Arduino Keyboard - print() works but println() does not I am recently seeing strange behavior in my Arduino Yun.

Just using the microcontroller, I enter the following:

#include <stdlib.h>
#include <string.h> // For string operations.
#include "Keyboard.h"
#include "Mouse.h"

void setup() {
  Keyboard.begin();
  Keyboard.println("Hello world.");
  Keyboard.print("Hello world.");
}

Rather than getting two lines as expected, I get Hello world.Hello world..

It is a very strange error because println (docs) is so 'core' to Keyboard function. I've never had this issue before and I've been playing with it for months. I am running IDE 1.6.11.

A possibly relevant detail

I had this working on my Yun months ago without the #include "Keyboard.h" and #include "Mouse.h". I opened the IDE again just recently and, upon compiling, it failed saying I needed to add those lines. So I did, and it now println doesn't work.

Please test: Keyboard.print("Hello world.\n");

...

  That works. println still doesn't.

I'm going to guess here that println is doing something odd in the Yun libraries. I note that the Keyboard.cpp file in my release has this in it:

#define SHIFT 0x80
const uint8_t _asciimap[128] =
{
    0x00,             // NUL
    0x00,             // SOH
    0x00,             // STX
    0x00,             // ETX
    0x00,             // EOT
    0x00,             // ENQ
    0x00,             // ACK
    0x00,             // BEL
    0x2a,           // BS   Backspace
    0x2b,           // TAB  Tab
    0x28,           // LF   Enter
    0x00,             // VT
    0x00,             // FF
    0x00,             // CR    <---------- note!

Notice that linefeed has a code mapped (0x28) but carriage return (CR) does not (unless you call 0x00 a mapping).

I think you'll find that when you hit Enter on a keyboard it is sending a CR (after all, it used to be labelled the "return" key) and not a LF.

However I thought that the Print class outputted both:

size_t Print::println(void)
{
  return write("\r\n");
}

Maybe yours doesn't. I'm not certain which exact println will be pulled in for a Yun. The fact that it used to work, and now doesn't, suggests a change there somewhere.


Is there a good Arduino enclosure for that works with the Olimex MIDI shield I have a MIDI project I put together using an Arduino UNO R3 and the Olimex Shield-MIDI.

I want to install the project permanently in my Guitar rack so I want a decent enclosure, but there doesn't seem to be anything that would support the extra height that the MIDI ports have, relative to the Arduino + Ethernet enclosures.

Has anyone come up with a good solution for Arduino + MIDI projects?  A metal enclosure would be a plus.

Your best bet is to 3D print the enclosure.

There are many places that will 3D print your enclosure for you and most will mail it to you as well. I would recommend Shapeways as they are fairly reasonable in price and ship worldwide.

If you are a handy DIY person you could use SketchUp or Tinkercad to design your enclosure. Also there are many Arduino enclosures on Thingiverse that you could use as a starting point.

Alternatively there are often places that will design (and then 3D print) the enclosure for you, you just have to supply your hardware. There are often a few places like this in each city.


Branching Bus for Sensor I am looking to setup a system where I have a master Arduino polling a number of sensors.

The way I am thinking is hooking the master TX line to the sensors RX line(and the opposite for the other line)

Questions

How long can the lines be?
Can the lines branch?

I have a page about connecting Arduinos using RS485. You can connect multiple devices up like this:

That has a reasonable range, 20 metres or more.

On that page I describe a Rolling-master system where each device takes turns to be the master and transmit information to the other devices. It also manages some devices not responding.

This screenshot shows the various devices "talking" during their timeslot:

In that particular case there were 3 devices active out of 4 configured.

  I have a master ardunio polling a number of sensors.

I'm assuming in my answer that you have an Arduino at each sensor point (you could use a cheap ATtiny85 or something). That would be needed to run the rolling master code.


Why is it i need transistors and resistors to turn a dc motor with an Arduino but i can connect it directly to a battery As the question says im building a circuit to run a DC motor whenever motion is detected on a motion sensor. Now as this image suggests

I need a diode + resistor + transistor to get this thing to turn with an arduino but i can do the same with a battery and connecting each of the terminals to the + and - of the battery. I understand this might be for speed control ? or turning the motor different ways ?
But if I just need it to spin at 100% would all this be needed ?
I tried hooking up the motor directly with a resistor to the 5V + GND of the board while it was on but no joy (obviously) doing something wrong but wanted to use this problem as a way to learn circuits better.
Thanks
S

If you want the motor to rotate continuously, without using PWM, and without switching the motor on and off from the Arduino, you can connect the motor straight to 5V and ground. If you then add a large resistor like you tried, not enough current will pass through the motor to rotate it; in the image the resistor is there to limit the current into the transistor, not to limit the current into the motor.
You can't connect a motor directly to an IO pin because an IO pin can only deliver about 20mA, which isn't enough for a motor. So, if you want to control a motor from an IO pin, you need a transistor as a switch and you operate that transistor from the IO pin. The transistor does the heavy lifting and switches the larger current the motor needs. The resistor is there to limit the current into the transistor.
Note that it is generally better to wire a motor directly to a 5V power source and not to the 5V pin on the Arduino, as the current you can get from that pin is limited; it will do for small motors, though, if they don't pull more than, let's be safe, about 300mA. In other words, it is preferred not to use the Arduino 5V pin as a power source, but use a 5V power source directly.
Also note that you always need the diode across the motor, however you wire it. It keeps inductive spikes away from the rest of your circuit.


How to handle an error in setup() What is the "proper" way to handle an error during setup on an Arduino -- for example some attached component is missing or returning an error code or invalid response?  The setup() function returns void so that's no help. This just doesn't seem to be an issue that is addressed in the official docs -- at least not that I have found so far.

Here are some options I have considered:

Throw an exception (but where does that go?)
Write a message to Serial and then go into an infinite loop or wait for a y/n to continue.
Set a setup_successful flag and then do if (!setup_successful) return;  in the main loop()

Same way you would handle any error in an embedded system; either try to recover from it if you can, or use whatever communications mechanism you have to let the user know that something failed.

I normally use a combination of Serial.println in case I happen to have a serial connection at the time, and also a blinking pattern on an LED (which most boards I use have). As an example, look at my code here: https://github.com/jayeye/jardino/blob/master/libard/WiFiSPIFFSConfig/src/WiFiSPIFFSConfig.cpp#L11. error() will do a sequence of slow and then fast blinks, and either return if I think the error is recoverable and I'm merely warning the user, or just stay in an infinite loop and keep blinking in despair :)

Obviously this is not an original idea -- think beep codes!


What not to do to an Arduino I may have been working with my Arduino UNO board improperly,
because now it fails to upload sketches (says some programmer is not responding)
and when I press the cute little restart button, the green LED doesn't do its blink anymore. I am aware what that means, but what I really wonder is how should I properly care the board. I probably will have no other chances to buy more arduinos so this information follows to be of a great importance.

As an example I would give, is touching the arduino board with bare hands risky, how much shock-tolerant it is, what if I mistake some pins, are there pins that cannot be mistaken, what will happen if I declare a pin as an output, but use it for input and the contrary, is loading a PWM program onto TFT touch screen shield unhealthy and so forth and briefly - how should I properly care the arduino board.

it is okay to use for simple experiments directly. But while you choose to opt for a complex tasks read the details about all the components and their wiring techniques.
specifically try to check soldering is done correctly or not while connecting the wires to any component or to other wire. wrong soldering may damage your parts and arduino as well.
Be careful while using power supply, more when it comes to use multiple sources.
read carefully before you do anything. Dont be afraid just be careful.


ESP32 documentaiont for "time.h" I am working from the example sketch in that installed with the ESP32 Dev Module into the Arduino IDE.  It includes <WiFi.h> and "time.h".  I have a number of questions about how to use the clock that is set up with configTime using NTP. I am trying to find the documentation, but I'm having difficulty identifying exactly who is providing me the "time.h" header file, and of course, there are a lot of different time.h header files out there so googling is difficult.

Where can I find the documentation for this particular header?

Example questions:

Can the time be set manually without a WiFi connection?
Can the timezone be changed without connecting to NTP again?
Can I get the time as a Unix Time Stamp?  (Yes)
Can I arrange for a function callback at a certain time? (I'm aware I can use the timer library for this but I'm hoping for something like a callback at 4:20p every Saturday)

time.h is provided by the compiler (more specifically the C library in use in the compiler).

I believe the xtensa-esp32 compiler uses newlib as the C library. If that is the case, the documentation is here: https://sourceware.org/newlib/libc.html#Timefns


Can't move servo with my Nano I'm new to this kind of thing. My code works on my Uno without problem with two separate servos. I've ensured that it's not any faulty leads, having tried a few other circuits with LEDs, buttons and potentiometers as well, simply switching between my Uno (which works fine) and the Nano.

I've chosen the correct port, chipset and board each time and the code uploads fine to the Nano. The Nano simply refuses to do anything I tell it.

Digital PIN of servo goes to designated D5 pin.
Ground goes to the GND near the Analog pins (shouldn't matter which I imagine).
Power goes to 5V.

The code above simply tells the servo to go to a certain degree when uploaded. Could anybody tell me why the servo will not move at all with the Nano? I just bought it and I haven't hooked up any power to it other than the USB, surely it isn't fried. It lights up and flashes as well.

#include <Servo.h>
Servo my_servo;

void setup() {
  my_servo.attach(5);
  // Pin definition
}

void loop() {
  my_servo.write(60);
  // No. of degrees
}

Connect a multi meter in series with the servo connection from the uno to the servo and see how much current it draws when working (probably less than 20ma, definitely less than 40ma). Then connect it in series with the nano and see what happens. If you get no current then you're activating the wrong pin.

If you see a current draw but the servo doesn't move then you need to use some sort of switch (transistor, FET, relay) to switch the servo. You could also compare the voltage and current read off the nano to the requirement in the datasheet for the servo. Again, this may lead you to needing a switch.

Edit based on comments above... Also try your 5v directly to the servo, then add a forward biased diode in series which should simulate the voltage drop to the level of your nano (0.4-0.6v). If the servo doesn't work with the diode and does without then you can be pretty sure the issue is insufficient volts (which is likely given the rating of 4.8v you mentioned in comments).


The analog read is not giving the correct waveform as that of an oscilloscope I have this code that fetches analog input values from terminals A0, A1 and A2 of Arduino mega 2560. But, when I plot the data, it does not give the desired waveform. The desired waveform is parallel measured in the digital storage oscilloscope. I was thinking to make use of Arduino mega 2560 as an oscilloscope that can have 16 channels. Because the DSO has only 4 and for a project, I urgently need 16 channels. Would be great if the community people suggest something. Thanks.

Below is the desired data from the oscilloscope that is measured parallel to avoid any confusion about the circuit.

%This is a script that will plot Arduino analogRead values in real time
%Modified from http://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/
%The code from that site takes data from Serial

clear all
close all
clc

%User Defined Properties
a = arduino('Com5')             % define the Arduino Communication port
arduino=serial('COM5','BaudRate',9600);
s1 = serial('COM5');                                                       % Define here YOUR serial port
s1.BaudRate=9600;

plotTitle = 'Arduino Data Log';  % plot title
xLabel = 'Time (s)';     % x-axis label
yLabel = 'Voltage (V)';      % y-axis label
legend1 = 'Voltage 1'
legend2 = 'Voltage 2'
legend3 = 'Voltage 3'
yMax  = 5                           %y Maximum Value
yMin  = 0                       %y minimum Value
plotGrid = 'on';                 % 'off' to turn off grid
min = 0;                         % set y-min
max = 5;                        % set y-max
delay = .01;                     % make sure sample faster than resolution

%Define Function Variables
time = 0;
data = 0;
data1 = 0;
data2 = 0;
count = 0;

%Set up Plot
plotGraph = plot(time,data,'-r' )  % every AnalogRead needs to be on its own Plotgraph
hold on                            %hold on makes sure all of the channels are plotted
plotGraph1 = plot(time,data1,'-b')
plotGraph2 = plot(time, data2,'-g' )
title(plotTitle,'FontSize',15);
xlabel(xLabel,'FontSize',15);
ylabel(yLabel,'FontSize',15);
legend(legend1,legend2,legend3)
axis([yMin yMax min max]);
grid(plotGrid);

tic

while ishandle(plotGraph) %Loop when Plot is Active will run until plot is closed

%          dat = readVoltage(a,'A0')* 0.48875855327; %Data from the arduino
%          dat1 = readVoltage(a,'A1')* 0.48875855327;
%          dat2 = readVoltage(a,'A2')* 0.48875855327;

         dat = readVoltage(a,'A0')* 1; %Data from the arduino
         dat1 = readVoltage(a,'A1')* 1;
         dat2 = readVoltage(a,'A2')*1;

         count = count + 1;
         time(count) = toc;

         data(count) = dat(1);
         data1(count) = dat1(1)
         data2(count) = dat2(1)

         %This is the magic code
         %Using plot will slow down the sampling time.. At times to over 20
         %seconds per sample!
         set(plotGraph,'XData',time,'YData',data);
         set(plotGraph1,'XData',time,'YData',data1);
         set(plotGraph2,'XData',time,'YData',data2);

          axis([0 time(count) min max]);

          %Update the graph
          %pause(delay);
  end

delete(a);

disp('Plot Closed and arduino object has been deleted');`

Your sampling rate is far too low for the signals you are looking at; you're not getting enough data points for drawing something that looks like the original signal.
The Arduino library's analogRead(), while slow, can do better, up to about 9000 samples/s; the ADC in the atmega2560 in free-running mode can do about 75000 samples/s at 8 bits resolution. This would require programming it at the register level.
There is only one ADC, so if you want 16 channels, this leaves about 4700 samples/s for each channel. In that configuration, however, the first measurements aren't valid and the second ones should be used, further reducing the sample rate per channel to about 2300 samples/s.
With a perfect reconstruction filter, this would limit you to measuring signals up to only 1150Hz.
All this doesn't even consider the time it takes to store or transmit the results.
So, an Arduino mega 2560 will not do for making a usable 16-channel oscilloscope for your signals; it's not even close.


Controllino Debugging Its a well known fact, that you can debug your arduino board with the help of an Atmel Ice. However, you might know the Controllino which is an arduino compatible device.

It has an ATmega2560 on it.

Do you have an idea how to debug a controllino? I neither see any ICSP port nor did I found anything useful around this topic.

Any help is greatly appreciated!

Connector X1 has the pins you want.

ICSP is shared with the SPI pins. Wire those to your ICE in the same way as you wire the SPI pins of the ICSP header on a normal Arduino to an ICE.


Ultrasonic sensor returns random values on external power supply my Problem is, that I get random values from my ultra sonic sensor if my arduino is connected to any external power supply (vin port 30) on my arduino nano.

If I power up from the laptop usb port, I get consistent values.

I have tested 3 different power supplies between 7-17V and up to 2000mA.
I have tested this on 2 different nano boards.
Also tested with an extra 2000uF capacitor between vin and gnd

pls help if you got an idea :)

So i tried to used a stable 5V input on the 5V input pin and got the same more or less random values (jumping all around... especially on targets more than 1m away)

So I changed form newPing lib (http://forum.arduino.cc/index.php?topic=37712.0) to Ultrasonic lib (http://forum.arduino.cc/index.php?topic=37712.0).

Now the values are correct on each power supply and even more accurate on high distance than with newPing on USB power supply.

Don't know whats broken with the newPing v1.7 lib -.- but this works!