text:
Reset as I/O pin
I'm looking to minimise the parts count and the power consumption as much as possible and I was wondering if is it possible to store a variable or execute a method when the 'reset' button is pressed?
I didn't find any docs or hints regarding this.
In theory, can it be done with an interrupt?
Edit
In a further research Atmel shows, that if you burn the 'RSTDISBL' fuse (still in theory for me) you can get hold of the reset button by transforming it in a I/O pin with "special" electric characteristics:

Also, if you look at the schematic the reset pin shows that it has what it needs to be an I/O pin:

I say in theory because I really don't know if arduino has the required constellation for this capability and if it comes whit the fuses already burned.

The MCUSR register shows whether there was an external reset (EXTRF bit). But I don't see how you can save power with this. I do see how you could use this instead of needing a button.

Well... MCUSR / EXTRF info in particular would not help a power save, but the answer to what I've asked will.

Yes, there are several possibilities here.
One is detecting state after reset and acting on it.  One of the reasons you might do that would be to shut the processor down all but completely, and let the reset wake it back up.
Another would be to program the reset disable fuse and repurpose it as an I/O pin - of course if you do that, you can only then reprogram the chip if you have implement working functionality to get back to the bootloader (or similar), or if you use a high voltage programmer.
These are in the category of things which make development a lot more difficult, but are sometimes worthwhile as they let you squeeze a little more capability out of the hardware.  If you are just starting a design, you might consider a different chip instead - but if you have existing boards or design investment, and this lets you get the last little bit of needed capability from it, it is possible.

Wait ... What do you mean by a high voltage programmer ?

High Voltage Parallel Programming is described in sections 25.6 & 25.7 of the ATmega48/88/168/328p data sheet.  It involves using a ~12v signal on the reset pin, which allows overcoming fuse settings that might prevent other sorts of programming.  You can buy HVPP programmers from Atmel and others.


text:
What do I need to make fluffy toys move and talk?
My kids got many fluffy toys, and I would like to make them move and talk. Something like a small platform with wheels and a speaker and some sensors that I would be able to mount any of the toys on.
I'd like to build something like 2 platforms with motors and sensors that move around, and when encountering obstacles "bark" at them through the speakers, wait random number of seconds, and move in different directions. Then the kids would mount their favorite fluffy dogs/cats/bears/rabbits on top of these platforms and unleash them on each other.
I am very new to DIY; what do I need to buy for such a project?

How new? Have you created something before? (You can use @username-of-the-user in front of your comment to reply to a certain person)

You will need a processor board, motor driver, sensors, and audio amplifier.
Since you are asking on the Arduino forum, it would be natural to consider one of the Arduino boards or derivates - but beware they tend to be rather antiquated compared to alternatives now available.  The plus side of the classic ATmega boards is the wide variety of read-to-go example code available right within the IDE, and the wide supply voltage range (of the bare chips if not the boards) which is more compatible with AA-cell battery packs than competing device's narrower voltage range tends to be.  The one part of the functionality you describe that is a bit of an issue is the audio output - you can get it from an ATmega but it will be poor in quality and you will need to add storage for the "bark" data.  You might almost consider a separate module with an ATtiny and a small SD card for that (ironically the ATtiny while generally less capable has fast PWM better suited to audio).
For motor drivers, especially when using batteries steer clear of the older bipolar L293/L298 type of solutions, as these have very high internal loss which basically means that one cell in your battery pack exists just to generate heat in the driver IC.  A modern FET based driver (the TB6612FNG is quite popular) will be better.
For sensors you probably want one or more of microswitches extended with "whiskers", ultrasonic rangefinders, or short range IR reflectance.
Some dual wheel drive (or "tank steering") RC toys can be worth considering as platforms, but their gearing may be too fast for your purposes, particularly those designed to spin and tumble.  Continuous rotation servos are sometimes mentioned, but it can be hard to get them tuned to not rotate when commanded to stop, and mounting wheels can be tricky.  The small plastic gearboxes work well if you can get matching wheels but are hard themselves to mount.  Access to a 3d printer can be quite useful for creating missing physical components, though a block of wood and a router can make a nice chassis, too.  You can also buy ready made Arduino robot base kits with chassis, gearboxes, and wheels.
For audio output, you can accomplish something with an NPN transistor and base resistor driving a speaker, but best results would be with a small class D driver board as are now widely sold for a few dollars.  They tend to be stereo, but you can feed both sides with the same signal.  If you only wanted "robot beeps" you can drive a piezo disk directly from a processor pin with reasonable loudness at higher frequencies, but the low frequency response is quite poor.

beware they tend to be rather antiquated compared to alternatives now available - easy to use, however.

Don't do it.
When you say to us:

I am very new to DIY; what do I need to buy for such a project?

Then you really aren't ready yet.  Sometimes a virtuoso or savant exists, and they can make incredible DIY projects, but for most people, jumping into such an aggressive project as your first DIY is a recipe for disaster.
I'm not trying to be a smart-ass or negative, but you should get an Arduino and try some PROTOTYPING first.  Again, not trying to be a smart-ass, but if you even have to ask this question, then you really aren't ready yet.
When I work with people on their first project, you should see how excited they get when they can get a light to blink (I still get excited each time too)!
I think you should go for more of a "karate kid" approach: Wax the car, paint the fence, sand the floor.  Once you know the fundamentals, you'll be a ninja before you know it.
I could list a pile of "fundamentals" here, but any other guide would be more comprehensive than my Arduino karate kid list.

funny side-comment there:  I was getting parts to build a "robot", and someone close to me said:  "That's great!  Can you build me one to clean my floors, those brand name ones are expensive".  When I responded: "Well, they spend 80million dollars a year on R&D, so...  pay me 80million, and I'll get you a robot that's a few years behind their design." ...  http://www.bizjournals.com/boston/blog/techflash/2015/09/irobots-smartest-robotic-vacuum-debuts-after-well.html

This answer sucks, but someone needed to say it.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Using a L2938D Motor Driver Module. (Not IC, Module)
I have been trying to use my newly bought L293d Motor Driver Module to run motors(a single motor in this test case, simple 5V toy motor) from my Arduino UNO. Thing is, this is an entire module, not just the IC (in which case there are many tutorials available). So I was following this tutorial to try and get my motor running.
Here is the tutorial - http://www.instructables.com/id/Arduino-and-L293D-Robot-Part-1-/?ALLSTEPS
Here's what the module looks like -
There are 6 Pins on the module, which bring out the 6 inputs, EN1, EN2, IN1, IN2, IN3, IN4. Now since I am using only one motor, I connected my motor to the OUTPUT 1 & 2 header given on the module. I then take the 5V and GND from Arduino and connect them to my Module's 5V and GND header, (leaving the 12V one empty), I thought that this would be enough as my motor is also of 5V.
I then connected the IN1 and IN2 to the pins 7 & 8 on my Arduino and used the following code-
// Simple code to make the motor turn
int RightMotorForward = 7;
int RightMotorReverse = 8;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

Nothing happened. The motor didn't work and I have no idea why. I've gone through the entire datasheet for L293D but I found nothing that could help me. I suspect that it has something to do with the EN1 pin, but I don't really know how to use it, the tutorial said to connect it to 5V, which I tried but no results. So where am I making the mistake? How do I get this to work?

ooops. That 5V you are applying to 5V pin is actually an output pin.
You must apply some input voltage at the 12V & GND inputs.
Don't forget to remove that 5V connection to 5V pin

you can also try providing 5Vs from Arduino 5V output pin to module 12V input pin. that might also work.

I'm gonna try connecting the 12V with a 9V battery, that should be enough to run my motor shouldn't it?

that depends on how much current your motor is drawing...

I tried my above stated experiment and that did work. My battery was of no use after about 40 seconds though.. :P

While no one can tell you exactly how to connect that board without having its documentation or the board in hand to examine visually or with an ohm-meter, it is quite likely that by leaving the "12v" terminal unconnected, no power is being provided to the motor side of the circuit.
It kind of looks like there is a voltage regulator on board, so it may be that it will even provide 5v on that terminal when given something 7 volts (or so) or higher on the "12v" terminal - again, we cannot know without details of your exact board.
The L293 is an old and low-performing chip, with internal losses that mean  that to achieve 5 volts across a motor, you will need to supply very nearly 7 volts to the chip.  The difference gets wasted as heat.

Strangely there's no documentation or tutorials available for this on the internet, I'm gonna post a tutorial as soon as I can get it working. Anyways according to you this has nothing to do with the EN1 pin and I should try giving power to both the terminals right? I'm gonna keep the 5V power supply same and will add a 9V battery to the 12 V output, ground remains common.

No, I don't think you should power both terminals, rather, you almost certainly need to power the 12v.  And the EN pin is certainly relevant - it just is unlikely to be enough.  A 9v battery does not have the current capacity for a motor project - you need either a power supply or a series of connection of quality AA cells at minimum.

so uh, the EN1 pin just sits empty?

No.  Read the L293D data sheet.

I did. Acc to the datasheet the EN1 pin is to be connected to a 5v supply... I tried doing that but it didn't work.

Of course not - you still haven't powered the 12v pin.  But remember, even if you reverse engineer this board to the point of getting it working, it is still only going to work poorly.  Consider getting something not only better (FET rather than bipolar technology), but documented.

I see. I'll try wiring it that way. Actually I was planning to use the Motor Shield, but my teacher handed me the motor driver instead (most probably to test me), anyways, what do you mean by work poorly? Poorly as in taking time to respond, requiring more power or generating more heat?

Turning a lot of power into heat due to very high internal losses.  That chip along with its L298 brother, has long been obsolete.

Hmmm than shall I use it or are there better alternatives?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Adafruit Flora V2 use onboard and external NeoPixels
I am working on wearable project using an Adafruit Flora V2, and for this project I need to use the onboard NeoPixel. I also need to use Neopixels that are attached to the D6 pin (is it a pin?). I have a line at the beginning of my program that says #define PIN 6. I found that I can use the onboard NeoPixel by changing this to #define PIN 8. Is there a way to use the onboard NeoPixel and the ones attached to D6. I already have everything wired up, and the rest of my program is written, I just need to use both pins. Thanks for any possible help.

using Flora v2?

@ARK Yes, edited

Do you have external Neopixels attached to D6. Because,
Adafruit Flora v2 has only one on-board Neopixel and that is internally attached to pin 8?

Yes, my  external NeoPixels are attached to D6.

The #define is just letting you use a nice name for the numeric value of the pin.  If you want to use two different pins, you use two different names.
So you might define them at the beginning something like:
#define BOARDLED 8
#define STRIPLED 6

Then you create a NeoPixel object that uses that pin.  In your case, you'll do this twice.
Adafruit_NeoPixel flora_led = Adafruit_NeoPixel(60, BOARDLED, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, STRIPLED, NEO_GRB + NEO_KHZ800);

And then you call the one you want to set/modify/show/etc.
strip.show();
flora_led.show();

Ok, I'll try that tomorrow. I don't have my Flora right now, but I will then. Thanks.

+1 Note that it's covered in AdaFruit's Überguide (https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library) FAQ (second question).


text:
Converting RGB from color sensor into the Munsell Color System
I am hoping I could get some help developing a an idea I have for archaeologists/soil scientists using an arduino and the TCS3200 colour sensor. The idea I have is a simple device which can determine munsell colours with more accuracy and speed. The current conventional method is to use colour chips/swatches found in the Munsell system booklet and match them as close to examples of sediment/soil found at archaeological sites. The problem with doing this method is that it is highly subjective, and time consuming.
My idea is to use the Adafruit TCS34725 to read and detect the RGB colour of the sediment (in the RBG colour space) and convert the data into the Munsell System. I have all the data of what RGB ratio corresponds to each Munsell colour -- which I have downloaded from this site: www.cis.rit.edu/research/mcsl2/online/real_sRGB.xls
My problem is that when I use the sketch provided, I can not figure out how to use the "if" statement to "Serial.print" what the munsell colour corresponds to the RGB colour detected by the sensor.
My ultimate goal is to modify the colour view sketch here see: colorview
I would like to keep the everything provided but change two things, I would like to convert RGB into Munsell using the data provided by the RIT link and also add a screen and button to start the read process and display the colour.
If some one would be willing to help me that would be great!,

Maybe use the routines at https://www.cs.rit.edu/~ncs/color/t_convert.html

That would be a helluva lot of IF statements. What you need is a Look Up Table (LUT) - i.e., an array in PROGMEM.

Yeah, I figured there would be a better way than using the IF statements, However I am not sure if I can generate the LUT with the sensor. What I might do is use a python program that preforms the conversions. And input the data from that using my raspberry pi.

Before you even think of implementing this on an Arduino, you should set up a system where the Arduino reports the RGB readings over a serial link to an easily monitored, size-unconstrained, "thinking in code"-friendly piece of experimental software running on your PC.  Only move an algorithm to the Arduino after you have a good idea that it is sound.

Which if statement? Your link points to the github repo, not to a particular line.

Also: are you asking for help with the board? If so, you may have better luck posting at the Adafrut fora; engineers from Adafruit also read those, and you may get an answer directly from the designer.
if you are asking for programming help, it is a really inappropriate thing to do. Learn to code, or hire someone to do it for you.

@JayEye Thanks, for your suggestion to look at the at the adafruit forum, as for learning code that is what I am trying to do. I just was asking if it would be even possible use the serial.print and if statements,  in that way. Sorry that you felt it was inappropriate I am not asking someone to write the code for me I was asking for suggestions/help.

None of us were born knowing how to code (well, most of us at any rate :) ). Sorry if I sounded harsh. Sometimes I type too fast and don't think about how my answer might sound. Cheers!

@JayEye Not a problem :) Its a bit of a learning curve for me but this is just a side hobby project.

I have some thoughts on your task. First of all colorimetry is a science on its own. I know people working in this field for decades with equipment costing many millions of €. They all share some basic wise words. One is: "Because we all see colours we think measuring colous is an easy task. The opposite is true. Many of the best colorimetrists are colour blind." One second is: "Without light there is no colour". I will write on this later.
Colorimetry in fact is a complex matter. Between a colored piece of stone and a numerical value normally lie a lot of transformations and convolutions. And inbetween there are also lurking many error sources.
This said, I'm sure it will be possible to produce somewhat acceptable results with your sensor. Provided you do a proper calibration and add a calibratable light source.
Speaking of light source. A piece of stone can only reflect incident light (except some uranium/radium salts, you don't want to deal with). Pigments are basically LTI-systems (aka passive filters). This means they can only reflect wavelengths which are present in the incident light. And the will reflect a well defined and individual proportion of each wavelength regardless the luminous flux of the incident light. This means, if your incident light contains nearly no blue light then the stone or whatever you want to examine will reflect only the fraction of "nearly no light" it typically does reflect of any amount of blue light.
So the remission spectra of all pigments get shaped (multiplied) by the spectrum of the incident light. Your sensor sees only the reflected light and therefore will give totally different results for one and the same object depending on the incident light. Look up the spectra for daylight and incandescent light and think about the results of your sensor.
To make a long story short, you can only yield reproducable measurements if you supply your own light source along with the sensor. This is in fact the way all colour meters work.
The only other way was to measure the full spectrum of the incident light. Reasonable portable spectroradiometers for this purpose cost 5000 €. So it's better to go for a light source :).
As they are rather affordable I recommend using LEDs to make up a light source for examination. But LEDs suffer from several drawbacks. They tend to change their output spectrum with their chip temperature and ageing processes. So you have to supply a proper calibration procedure for your measuring equipment. And you better do the calibration sequence before every measurement.
You then have to design an apparatus which allows the light from your LED fall onto your samples (stones, sediments or so) but prevents other scattered or direct light to enter your sensor. Otherwise all measurements will be crap.
While this is not a direct answer to your question, I think the topic is important enough to write an elaborate pamphlet.
Update
Now some more words more closely related to your problem.
In general loading a huge excel table into your arduino is not necessarily a good idea, even if a big "if"-code array was possible. Storage is scarce on this platform.
If you combine a lookup table with interpolation, you can save much space. You would have to omit 90% of all datapoints and estimate all in between when measuring. Still the table will be rather big, because you have three degrees of freedom.
Another drawback of big tables and LUT with interpolation is, that it makes calibration difficult. Normally, when you calibrate your sensor, you have to adjust the parameters along the calculation. If you rely on a table, you have to exchange the whole table, regardless if it is something like that excel thingy or a condensed lookup table.
If you go for an analytical solution, as suggested in one comment, the number of parameters you have to update after calibration reduces drastically. Effectively you have to adjust some factors and offsets in the equations for this problem. Of course you will have to learn the ropes of the photometric equations, but you will  have to do that anyway, I think.
Some more words on the design of your appartus. Your idea of a cylinder in front of your probe is good. I recommend to fit it with a rim of black foam rubber, so you can seal light coming from outside. And you have to paint the inside of your cylinder as black as you can. See the interiour of a camera objective for reference.
If it is white you will have multiple reflections and multiple filtering which deteriorates your measurement results vastly.

Thank you for your help, I am fortunate that the sensor that I am using comes with its own light source :). So I think the design I am working up in my head is a tube around where the sensor will be placed, I am hoping that  I could then cover the sample/rock leaving only the LED light falling onto the sample. The sensor has a built in IR filter as well as the ability to detect the temperature of the ambient light reflecting off the sample.

I agree that it is a difficult science which I why I am hoping to find help on this forum. I am glad that there are people kind enough to offer opinions/comments on how to achieve this goal I have. I am looking at developing more tools for archaeologists to use in the field that are both cost-effective and simple to operate while providing accurate data. In archaeology I find that the methods we apply to answer particular questions could use improvement. Once, again thank you for your suggestions hopefully I can keep everyone updated on my progress.

I spent some more thoughts on your problem, let's see if we can get that going. Some of the problems perhaps might fit better into another SE community

I have been working on a python code that takes a user input defined input and converts it into munsell using a if/elsif print statement. It is a bit impractical, doing it this way but it works. I know that there is a python library that can work with excel files, and I am currently looking at using that as an alternative to printing 1000+ esif statements :p. I am thinking that the arduino may not be the best device to use for this project. I don't think it would have enough memory to run the program and run an small lcd. I am currently in the process of looking at drivers for the Rpi

The Arduino is able to do that task. You would need only roughly 6 (!) if statements an a while-loop to find corresponding munsell values for a given RGB from this table. Your only task was, to transform the table to something usable written in C and write a code to find the values in the table. I take bets it is possible with less than 50 lines of code. Moreover I strongly recommend to solve this problem analytically otherwise you will get into trouble if you want to calibrate your system.

Right so after a little looking around the net, I came across the colormine library. It is written in C# and the code can already convert the RGB color space into xyY mathematically. This is good because I don't have to re-invent the wheel.  Now I have to import the library into the code and use the serial data of the sensor into the formula. It's progressing at least :)


text:
Help compiling multiple .ino file code with code! (I'm not sure what to name this)
Ok, so i'm trying to make This Project and the code comes all in different .ino files but in the video its all in one program. So how do I compile all of the code onto the arduino? (By the way the code is on step 5 in a .zip file) Thank you!

One of the .ino files is likely the main code file.  Name the enclosing folder with the name of the .ino file, then compile it as normal.
In this case, AbHhGD.ino is the main file, and its folder should be named 'AbHhGD'
The comments indicate there are missing libraries you likely need to install.

Ok so I just rename the folder that has everything in it to AbHhGD and then compile abHhGD.ino?


text:
sensor sampling frequency
I have a problem collecting data from my accelerometer/gyroscope sensor with a constant sampling rate. Is there a way to program the arduino to collect data from the sensor and store these values in a SD card with a constant frequency of 1kHz without using delay? The sensor that I am using is a MPU6050 gy-521 sensor that uses I2C with arduino. I will be reading 6 different datas from my sensor: acceleration in x,y,z directions and gyration in x,y,z directions. Thank you all in advance for the advice/help.
so my project will be making a device that collects the values from the sensors and saves them to study the data later. First, a LCD display will print out a message without having any data collection to occur. The data collection will start when a button is pushed. After the button is pushed, the display will print out another message saying that the arduino is collecting data and the Arduino will save the 6 values (x,y,z acceleration and gyration) from the accelerometer/gyroscope sensor to the SD card. The data collection will stop after the button is clicked again and the display will print out another message saying that it has stopped collecting data. Then, this process can start again if the button is clicked once again. Thanks in advance

Welcome to Arduino.SE. What have you done so far? Liberally describe your setup and post any code as well.

You may actually find if you research it in more detail that you can get the MPU6050 itself to produce regularly spaced samples, and merely poll for their availability.

You have discovered delay() does not guarantee the period of your code.  This is because the period of your code is the delay() plus the time for your code to execute.
What you need is a hardware clock to give your code an indication that a fixed period has expired.  This is one of several Arduino timer libraries. The timer library web page describes your problem in more detail with example code using delays and using the timer library features.

A quick and dirty solution is to just the right the code that does the sampling and loop it, say 10,000 times, with a short delay.  Measure the time it takes to do the 10,000 samples by recording time before and after all the samples.
The amount of time taken will be:
10,000 x (delay period -> known) + 10,000 x (actual amount of time to do the sampling)

From this data you can determine the required delay to get your 1 kHz sampling goal.


text:
Arduinino & Max7219
I'm using a MAX7219 and 6 (six) seven segment displays
I used my own board and two purchased on ebay - no difference in operation.
MOSI, and CLK are correct and verified with my scope (Tektronics)
CS (chip select) is pin 22 (for no particular reason) SPI is set to Mode0
Yes, I have tried other pins as CS - all work the same.
My MEGA board can be powered by USB or 9.9 VDC wall-wart - no difference
Trial code is shown below, and works properly.
Placed 47 uF 50V cap on display board between +5 and GND - no effect
Placed 220 uF 35V cap on display board between +5 and GND - no effect
MOSI, SCK and CS are verified with scope to be 5 VDC. Compiler and D/L applications are set to MEGA and seem to work properly.
PROBLEM IS THIS:
Code compiles and D/L properly into Mega. Mega resets, and about 50% of the time all digits illuminate (not executing code properly?) Digit 0 (most right hand digit is enabled) never works. I can press the reset on the Mega as many times as I want - no effect.
HOWEVER if I pull either +5 or GND to the MAX7219 module, and reset my Mega, it works perfectly. Yes, this is obviously a reset problem, but I've never seen a reset problem before with the MAX7219. I put delays at the beginning at short delays in the SPI communications to no effect.
Has anyone ever seen anything like this before? I have no hair left to pull. I'm thinking maybe to use a MOSFET to turn the MAX7219 on after the MEGA is up and running. Any suggestions are appreciated.
 //version 0.1
 #include <SPI.h>
 #define LOAD_PIN 22

 void maxTransfer(uint8_t address, uint8_t value) {

 digitalWrite(LOAD_PIN, LOW);      // Ensure LOAD/CS is enabled (LOW)
 SPI.transfer(address);            // Send the register address
 SPI.transfer(value);              // Send the value
 digitalWrite(LOAD_PIN, HIGH);     // Tell chip to toggle in data

}

void setup() {

 pinMode(LOAD_PIN, OUTPUT);          // Set port pin to output

                 // Reverse the SPI transfer to send the MSB first
 SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));

                 // Start SPI with attributes in "SPI.beginTransaction"
delay(250);
SPI.begin();
 maxTransfer(0x09, 0xFF);           // Enable mode B
 maxTransfer(0x0A, 0x0F);            // Use highest intensity
 maxTransfer(0x0B, 0x00);           // Only scan digit 0
 maxTransfer(0x0C, 0x01);            // Turn on chip
}

void loop() {

  // Loop through each code
  for (uint8_t i = 0; i < 0x10; ++i)
  {
    maxTransfer(0x01, i);
    delay(50);
  }
}

Try adding a pull-down resistor to the CS pin. That way the pin isn't floating during power-up.

@Gerben - I added a pulldown resistor and it improved the reset about 50% of the time. Under SPI.begin I added:
maxTransfer(0x00, 0x0);           // flush SPI
and now it resets properly each time. I don't know how I missed these things! Thank you very much for your help.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino IDE get stuck while uploading sketch
I was trying to use my L293D motor driver module. But when I upload the following sketch to try and run my motor, but it would get stuck on "Uploading". This happens with this sketch only, and happens randomly, with odds of happening being 3 in 5 times. After a bit fiddling around I found an error

Programmer is not responding.

When I try to reset the board or just reconnect it to my PC it might work.
Here's the sketch-
int RightMotorForward = 12;
int RightMotorReverse = 13;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

Can anybody point out where I am going wrong? I am using Arduino UNO. Is this just some problem in my code?

Can you please upload a schematic of your wiring? Do you use a bare L293D or do you use a prefabricated shield containing it?

I'm using a prefabricated shield. See this - http://arduino.stackexchange.com/questions/23383/using-a-l2938d-motor-driver-module-not-ic-module/23384?noredirect=1#comment44462_23384

This may very well be a problem related to power supply and/or grounding. Please report all power supplies connected in your setup (including the one powering your computer!) and how they are connected to your arduino, shield and further equipment.

That's the exact conclusion I came to just a moment ago (I was just going to post it!). I have a laptop, connected to the wall outlet. I am powering up the Arduino from a USB port on my laptop. I have inserted the 5v and GND pins from Arduino to the 12v and GND pins on the motor driver. If you have seen the link I send you, I think I should connect the 5v pin to the 5v input on the motor driver and some other power supply on the 12v output (Lets say a 9v battery for experimentation.)

Yes. the USB port definitely cannot supply the power for high power actors on any shield (there may be exceptions, though). If you connect another, let's say 12V, wall wart to the 12 V input of the shield, I strongly recommend to unplug your laptop from the wall outlet during testing, as two SMPS can cause problematic interference due to their so called Y-capacitors.

Found the solution... Just connect the 5v from arduino to the 5v on the Module. Then another battery (12-36 V, I tried a 9v one... it worked but only for about 40 seconds), to the 12 V input, keeping the ground common... That's gonna make the motors run!

Is the motor driver connected to the Arduino while you program it?
When the Arduino is reset, the output pins on the Arduino are driven high. If too much current is drawn though any of these pins, then the voltage supply to the ATMega328 may drop, and the ATMega328 gets stuck in a brownout.

Yes the motor driver is connected to the Arduino. What I don't understand is, it takes, sometimes, several resets and reconnections to get the board working again... And sometime it would say "COM8 not available". So even if to voltage supply drops on the ATMega, it should work in only one reset only. Is this some problem with my code?


text:
How can I connect an 8-relay board without using 8 digital pins?
I'm looking to connect an 8-relay board to an Arduino Uno. A board like this one. However, I don't really want to use up 8 digital outputs if I don't have to. Is there some intermediate circuitry I can either buy or build that would do this?
For example, can I connect something to the serial so that sending '3' would result in binary 00000011 and thus turn on relay's 1 and 2?
Alternately, and probably more lazy, is there an extension board that would just give me a pile more digital pins?

Sure, use a Mega instead of the Uno, more memory and 3 times as many pins

You could use shift registers and/or I/O expanders.

You are using a UNO, you have the pins available, you could just use them. With the UNO and the relay board you have everything you already need, otherwise you're going to have to implement something else. A serial "3" is going to require more programming than just flipping the output register, much less overhead. Shift registers work well, but then you'd have to implement that at your relay board end. It's all unnecessary work, unless you have a valid reason to want to do it another way. Eight data wires and a ground IS the lazy way out.

A likely solution is to use the Arduino SPI interface and the Arduino SPI library to control a SPI relay board.  Here is a 6 year old thread talking about such a board. And another more recent relay thread where SPI is brought up.

There are ICs that provide additional I/O ports through either the SPI or I2C busses, such as  MCP23017 or MCP23018 or their 8 port equivalents.
There are many different makes, search Google for "Arduino addition IO Pins"

You can use a MUX/DEMUX. Check out the link. Basically, you can select the output pin by a series of commands that you can do with the Arduino. The relay inputs will be hooked up to the IC's outputs
https://www.sparkfun.com/datasheets/IC/cd74hc4067.pdf

Why should mux/demux help here? With a demux you can "attach" one pin to several outputs, and control which output is selected with the address. If the OP used one of these, he would have to attach +5V on the common input, one relay over each channel except one, and then he could only turn one ONE relay at a time...


text:
Arduino IO long distance travel
I would like to use Arduino to control locks around a building which is 5 storeys high and on every floor there is 2 door.
I'm concerned whether the wires is able to travel all the way from the ground floor to the 5th floor to provide enough power to the relay located at the door.
The lock will be a 12V magnetic lock and it will be unlocked thru a SSR relay which will be controlled by the arduino

Even without the problem of long wires, if you are using a typical Arduino, like UNO, you will have to add something in between the pin and the lock (btw, adding a reference to the specific lock would help understanding better the question).

Pulling wires across a whole building seems a bit of a hassle. Have you considered using a radio connection? There are many radios available, over which you could send signed messages.

@IgorStoppa What would be the something be?

Something like this relay shield: http://www.seeedstudio.com/wiki/Relay_Shield_V2.0, but maybe your lock already has something similar built in, therefore I was asking you to be more specific about what type of lock you want to drive. Even if you have a relay, that might still require an additional transistor, depending on the specs of your relay.

@IgorStoppa I'm afraid that the walls of the building will affect the radio signal. The lock will be unlocked by touching 2 wires together which I will be using a relay to do that

If the locks already have their own 12V supply and the SSR are mounted next to them (1SSR per lock) you won't have much troubles. You can add a buffer right before the SSR input to lower the required current

Are you adding additional wires to the building?

Yes, losses in wires are proportional to the length, so an excessively long wire may not be able to deliver enough power. Many factors come into play here:

higher current consumed by the relay increases the losses
smaller wire diameter increses the losses
the voltage required by your relay defines how much you can afford to lose

For example, a pair of AWG23 wires 30m long will have a total resistance of 4 Ohm. If your relay consumes 100 mA, you will lose 0.4V in the wires. If Arduino delivers 5V, and the relay requires a mininum of 4.5V to work, you're just good enough: you're delivering 4.6V to the relay after the losses.

Possible to add a amplifier between each level?

Technically, yes. Do you have a power supply on each level?

Yes that would be possible. What kind of amplifier should I be looking for?

The simplest one, something like this. But like I said, maybe you will get away without one, if the wires you have are thick enough and the relays don't consume much current.

You are addressing a device control problem that auto, home and building automation has concerned itself with for years.
As such there are many solutions.  Most require a transmitter and one or more receiver(s). C-BUS is one such solution.  Another is CAN-BUS.

Use wireless nodes which are self-powered. It is easier (no need for lot of cables) and also solves this issue completely.
You can use ZigBee, which is mesh network. Every node re-transmit signal for nodes which are far. Because you have one on every floor, you would not have issues with reception.
EDIT:
If you want to use wires, I would still keep self-powered nodes and you can communicate with them using i2c or similar. You would need only 3 wires (SDA, SCL and GND) and they could be very thin, because they transfer only signals (<1mA range)). These 3 wires would connect all nodes. All nodes should have distinct address. I think this could be very cheap because you can create nodes with arduino micro which can be bought for ~1.5$ each.

Wireless would need a lot of additional work to maintain security

ZigBee already have security mechanism (128-bit key) implemented.

He mentions Arduino + basic lines. This will drive costs through the roof compare to that

I have added second (wired) option which is very cheap. It needs only 3 thin wire for whole building because all nodes would have distinct addresses. If you take into account number of thick cables he needs this can be even cheaper.


text:
How can I get ultra clean dc wall power for my arduino project?
I'm doing an rfid project that requires a read range of at least 5 inches or about 13cm.  I'm using a nano with a usb port, a rfid reader from priority 1 design and a large antenna. The problem I'm running in to is that when I power the project from the usb port I get a pretty decent read range of 11-13cm. But when I power the project from a DC power supply the read range drops considerably.
After a lot of testing with various power supplies I believe that all my power adaptors are dirty enough to cause rf interference and reduce the range.  Powering the project with a 9v battery and a 5v power regulator gives me really good range: 18cm with the largest antenna.  But I need plug in power.
So how can I power this project in a way that gives me ultra clean power?

I tried that same 5v regulator with a 5v adaptor and still had short read range.
Someone suggested adding a smoothing capacitor between V+ and Gnd but I wouldn't know what size.  I'm not an EE - I'm just a coder with a soldering iron.
Is there a better power supply I can get?

[EDIT] Also just FYI, when I connect even only the ground wire the the computers USB port I get a much farther read range. So..

Could it be a case of needing to ground the circut better as the switching power supplies only have 2 prongs and probably no real "ground". (Or am I making stuff up?)

[EDIT 2] What about a rechargable situation where my wall adaptor keeps a litium charged and the litium supplies clean power to the circuit?
Also I now know that I can charge my whole circuit with anything from 5 to 12 volts. In fact it would be better to have more in the 7 to 12 range than strictly 5v.
[UPDATE 3] Since this project is in my wall I was able to ground essentially to "earth" and that cleared up the noise. See this question as well: https://electronics.stackexchange.com/questions/230024/grounding-dc-project-to-clean-rf-noise

You can't use a 5V regulator with a 5V adaptor.. You can experiment with 1) a USB wall adapter 2) a >7V wall adapter and a linear 5V regulator (e.g. 7805, with the two 100nF capacitors) 3) a >6V wall adapter and a switching step-down regulator, set to 5V 4) any wall adapter (maybe >3V) and a switching buck-boost regulator. I think that with the USB wall adapter you will already solve your problems, then I'd test a switching regulator (step downs are better, I think) and the last choice is a linear regulator. you can find switching regulator modules for a few dollars on ebay, if you need them

I did experiment with the USB wall adaptor and got the same short read ranges.
This is the regulator that I have today: http://www.robotshop.com/en/pololu-step-down-voltage-regulator-d15v35f5s3.html
I just tried that one with a 12v power supply and it won't read at all.
And the only thing I'm changing in these experiments is the power source.
I ordered this one which will be here tomorrow: http://www.amazon.com/SMAKN®-LM7805-3-Terminal-Voltage-Stabilizer/dp/B00RKY0NP6?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00

Strange.. No reads at all? Did you check the ouitput voltage with a multimeter? Anyway your "new" board is a linear regulator, so use a 7V+ voltage source (12V should be fine) and be aware that you won't be able to draw much current from it..

Yeah it essentially dropped the read range to nothing. Too much rf interference I suspect. Of course it's hard to tell what's happening when I can't see a console output. I do have it blinking out some return values as a type of "morse code".  So I can tell that it's taking to the rfid reader and read that the measured antenna frequency is near 125khz.

@frarugi87 The new stabilizer didn't help. I also realized that I can power the whole thing (arduino and rfid reader) from 9-12v. With a 9v battery my range is optimal. With a 12v switched power adaptor direct I get very short range. If I then connect the ground of my circuit to the ground wire at the wall my range goes up again to closer to the 9v battery range (about 1-2cm shorter).  I want to try the 2 100nF caps but where do I put them?  In series between vcc and gnd?  Or in parallel? Can you write this up as an answer?

Actually I think in my circuit I'll just be connecting to real ground.

The two 100nF capacitors should be put one between 12V and ground and the other between 5V and ground. But.. Well, they should be already present in the circuit you bought. If adding them does not solve, try adding a big (e.g 1MOhm) resistor between ground and your earth plug at the wall instead of directly connecting them

This is what I use, although admittedly not in your application. I run it from a 12V wall adaptor and adjust the output voltage to suit my requirements. The input should ideally be at least a couple of volts above the output(depends on current and temperature at 25degC and 20mA it's > 1.6V and 1.5A at the same temp it's > 2.7V).

Another alternative if you want to really go to town would be to repurpose an old computer ATX or similar PSU. There are plenty of guides out there and it's a straightforward job.

Please specify that the input voltage should be at least X volts, where X is 5V + the dropout voltage of the LM317 (I don't remember how much it was)

My issue appears to be RF noise coming from the 12v power supply is messing up the RFID application. Something in the power supply is noisy enough that it makes the RFID not read at all.  Where as when I use a 9v power supply everything works golden.  What I'm looking for is a solution that will give me ultra clean power in the 5.5v -12v range without having to swap out 9v batteries every few months.  Even if it were a rechargable situation where the 12v wall supply charged a litium that then gave clean power to my circuit.

I think the problem is not the voltage but the magnetic field, so maybe better to use a faraday cage (a metal box) around the power supply and connect it to output DC ground.

Grounding it to actual ground cleaned up the power.


text:
Proper error logging using Arduino
Coming from a C# background where I do logs for every application, and given that I will be using the Mega for most projects and therefore have the memory available to do so, I want to incorporate error logging in my projects.
What is the best way to do so? Writing to an SD card? Writing via Wi-Fi or Ethernet to a networked storage or PC? Writing to a USB thumb drive?
The current project I am working on uses the Adafruit Music Maker shield so has the SD card reader incorporated into it, so the easy choice there would be to use that but I like creating solutions that are portable to multiple projects so writing via Wi-Fi or Ethernet seems to be the preferred method?
Since I am not fully up to speed with C++, and I see there are various ways to write to text files in C++, are there any preferred ways to do so depending on which storage route I take?

What you ask is difficult to answer in generic way, because not all the Arduino boards have the same HW options and even if you were to require a certain interface (ex: WiFi), that will introduce other side effects:

it will use certain pins/buses (SPI) that one might want to reserve for other purposes (yes you can have multiple peripherals on the SPI bus, but it will require additional code)
it might significantly alter the execution timing in certain cases

What most people use - and seem to be happy with - is the serial port:

it is not too difficult to setup
the ide already has a serial port monitor
it can produce information that is immediately human-parsable
there is no need to retrieve it afterwards (an SD card has to be extracted, mounted, etc.)

I would advise you to consider this at least as option, if not the only option.
Of course each option has drawbacks: the serial port can also cause delays in the execution, might not be too good if you have lots of stuff to log, etc.
The serial port could be seen as a intermediate step toward wireless logging: modules like the esp8266 do rely on serial communication.
Which means you could have wired logging while in the early phase and wireless logging later on, assuming you can afford to have something constantly listening to your project.
I would consider the SD card only for cases where the device will run unattended for long periods of time and there might be some hard to reproduce event that you want to track.
You could also consider the onboard flash, if you have to log events that happen seldom.

I should've been a little clearer. In general I log errors to an array and infrequently write them to the log file , which is more appropriate here so as not to tie up execution with a lot of Serial... statements

In C it's typical to use a log() macro which is configured to do whatever is needed, when logging is enabled. When logging is disabled, the macro is empty.

Normally, because Arduino is meant to be easy to understand and use, C++ is only used (extensively) in the libraries.  Perhaps someone knows more about the Mega, but, in general, the Arduino platform does not contain many complex built in features.  For instance, before even thinking about how best to write to an SDCard, you need to do some research into how to load and use the Arduino SDCard library.
This appears to be what you eventually want to do.

already fully versed on how to write to an sd card, or to network for that matter. the question was about best practices

Embedded systems typically use UART for logging, and Arduino is no exception. Logging to UART is as easy as calling Serial.begin() in the setup() and Serial.println() in the loop(), it works on all Arduinos, doesn't require any additional hardware and consumes much less resources than the SD card or networking library. Of course, you're limited in bandwidth (115200 kbit/s, sometimes more), so you won't be able to log in the fast-running cycles.
If you don't like the Serial Monitor feature of Arduino IDE, you can install one of the many terminal programs which will happily write the data from serial port to a log file. Some of these tools also have nice analysis features, including plotting of logged signals, formatting, data conversions etc.
If you're good with command line, creating a log file is as simple as
cat /dev/ttyUSB0 > log.txt

in Linux or
type COM1 > log.txt

in Windows.

In my Arduino project, I wrote communication sub protocol between a Raspberry Pi (or a PC).
I simply added some commands to duo vars or arrays into memory.


text:
Pi3 + ATmega644P: How do I establish a data connection with 1 analog input and 1 digital output left on the AT?
I have no UARTs left on the ATmega and need to deliver 1 Byte of information from the pi using 1 analog input. I2C is no option either.
I planned using the digital output to request an analog signal from the Pi, but it does not seem to have a DAC.
Is it possible to properly translate/read a PWM signal with the atmegas ADC?
Analyzing the PWM the 'usual' way would probably be too slow as I don't trust the pi to keep up with a high PWM frequency.
PINS left: PA0(ADC0|PCINT0), PD7(OC2A|PCINT31)
I should add that this is a rather large robotics project involving communication between 8 MCUs in it's current state and needs to be extended by a computer vision module(=pi), which is not compatible with the existing custom bus
Edit: This also is a real time system which has approximately ~1-2ms left in it's main loop(10ms period). The required data has to be present in time as it alters the robot's behaviour for this loop.

You can use SoftwareSerial to connect to a pi uart; otherwise upi can use a software serial communication using whatever protocol you want. I highly suggest you to avoid using analog signals, since these signals can't transfer reliably one byte... And PWM too is a bit too imprecise. Just remember to voltage translate the 3.3V to 5V (even if you actually could use the 3.3V output to communicate to the arduino, since it should accept voltages as low as 3V...

I'm sorry but your question isn't very clear.  Do you know about logic level shifters?  You could use that to convert 3.3. to 5v.  Also you might want to look into adding additional ports to both devices, but you are going to need to use I2C or SPI to do that.

Yes I do know about level converters, the problem is about generating an analog signal on the pi or using a different method to communicate with given pins.
I should add that this is a rather large robotics project involving communication between 8 MCUs in it's current state and needs to be extended by a computer vision module(=pi), which is not compatible with the existing custom bus

While there are various ways to do digital signalling on your remaining pin(s), depending on how locked in to your current setup you are, an approach that might make sense would be to see if you could convert an existing point-to-point serial link to a multi-party serial bus.  Basically, read up on RS485 and see if you can do something conceptually similar, without the differential transceivers, but rather using your existing low or high voltage connections simply by software-enabling the output driver of only transmitter at a time and writing some rules for deciding who gets to talk.

The exisintg i2c interface is used to debug and locked during normal operation to not interfere with already multiply used connections.
The second UART is exclusive to robot2robot bluetooth communication.
I already thought about hooking up another bt module to that, which was too slow as well

Perhaps you should move the bluetooth to the pi, use that serial channel for communciation between the pi and the atmega, and encapsulate relayed bluetooth messages on it, perhaps divided into small pieces to fit in between the realtime messages (though why the Arduino would be the appropriate consumer of the bluetooth data at all is a mystery).  This is a really a system engineering problem, not a narrow Arduino question in the scope of this site.  Your fear about interrupts is not entirely unfounded, but the concern is something that can be overcome with careful software design.

The solution was to hook up PA0 to GPIO18 of the pi with an RC-circuit inbetween.
GPIO18 features a hardware PWM output, which has to be set to mode 0 (non balanced, mark-space), because the balanced mode could not handle odd pwmRanges for some reason(it is badly documented).
This setup enables the atmega to read the pi's pulsed 0-3,3V output as analog input.
Pin initialization on Pi(using a python library):
import wiringpi2 as wiringpi

wiringpi.wiringPiSetupGpio()
wiringpi.pinMode(18, 2)
wiringpi.pwmSetMode(0)    #<- important part

Currently writing the Atmega side
    uint8_t     i = 0;
    uint32_t val  = 0;
    while(i<8)    //average 8 measures
    {
        i++;
        ADMUX   = 0 & 0x1f;    //select channel 0 (PA0)
        ADMUX |= (1<<5);       //set ADLAR bit ADCH > ADCL
        ADCSRA  = ADCSRA | (1 << ADSC) | (1 << ADIF);
        while (ADCSRA & (1<<ADSC));
        val = val + (ADCH);
    }
    return ((val)>>3);

Note that this reads a 10bit value on the channel and discards the least significant 2bit stored in ADCL as ADLAR is set to speed everything up.

You can start researching about one wire protocol here to see if can implement it given your situation.

I have read about that but a minimum of 1,5ms to transfer 1byte is far too slow (reset + presence + 2x(8bit at 60us))

You really should include your speed requirement in your problem statement.

In your edit to the question, you are mixing up transmission time with the processor's attention time required to receive the data.  They are by no means the same thing, unless you sit in a blocking loop watching the signal change, which would be a rather unwise implementation.  1.5 ms for data transmission sounds like it would actually fit your 10 ms loop time rather nicely.

It is difficult to accurately ask a question dependant on so many factors.
Timers that could be used to modulate the signal are used up.
The PD7 pin has a signal change interrupt, whose use could interrupt the main bus, crashing the system.


text:
Arduino Uno (or Teensy 3.2) programmatically powering an external USB connection
I'd like to create a process to programmatically turn-on/activate a separate USB device connected to my computer...Thinking another way to state the problem, I want the Arduino to complete the USB power circuit and then "turn off" on a schedule.
In an essence, I'd like to have my Arduino facilitate the manual process of un-plugging a USB into my computer (lets say for 5 seconds) and then re-plugging it in (let's say for 5 mins)-- rinse and repeat on a schedule....I'd like to have this coded/programmed though (I'm ok in the Arduino IDE -- sample code would really help me out a ton though) -- I'm not going to setup an actual servo to do this.
I thought getting a Arduino Shield would be the right place to start but I'm really lost.  I also thought getting a USB cable with a flip power switch might be another way to tackle the problem too-- but I haven't started to mess with it yet.
Any ideas or resources to point me in the right direction are greatly appreciated.  Thanks so much.

I'm not aware of any off the shelf "shields" which would accomplish this goal.  Since you do not seem to want your Arduino device to play either the USB host or client role, but rather to interrupt power to a difference device, a traditional USB shield is probably not going to help.
Rather it would be useful to look at how the small minority of USB hubs that implement software control of downstream power on a port-by-port basis do it - USB allows for this, but doesn't require it, and most hub ICs have output pins to drive power switches, but don't include them.
Switching the 5v USB VBUS needs to be a done with a "high side switch" - a P-channel MOSFET would be an obvious candidate, but it has been historically harder to find good ones.  Some time ago I ordered a few Richtek RT9701GB USB power switch ICs - apparently they are actually more effective N-channel FET's packaged with surrounding circuitry to make them usable on the high side - but that project was shelved so they remain untried.  If you are up for creating an extremely simple surface mount board to hold them (or can find one already made) they might be worth a try.
At the crude end you could probably use a relay board. There are hubs sold with mechanical power buttons that can be very useful when debugging USB-based embedded systems as you can power cycle them without constant unplugging, and this would be a sort of automated version of that.
It's an interesting question however, if removing the power to a USB peripheral while the data lines remain connected is proper.  This is problematic in the simplest design of an ESD protected input, as the built in protection diode means that the data signal ends up trying to power the unpowered IC, something it isn't usually rated to do, but actually USB circuitry may be more complicated.  An original USB "A" connector is made with the power and ground pins longer than the data ones, in the intent that they connect first.   Pragmatically, I've seen numerous USB devices survive data connection without power - but it could be interesting to read the specs (both USB and of the data sheets of particular devices implementing it) and see what they say about this.
Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.
Or, if you did get one of the rare USB hubs that actually includes controllable downstream power switches, an investigatory dive into the depths of your computer's USB stack should theoretically yield a way to control them from software there, potentially eliminating the need for the Arduino/Teensy.

At the crude end you could probably use a relay board.

hmmm, you RAAAANNNNNGG? (yes finally a reason validating my existence!)
Sorry, but I just couldn't resist chiming in on this topic. So what I can add is:
I have a Teensy 3.2 - RPi2 contraption at a site which is impersonating a
 USB mouse, from the security NVR's perspective (think Fred Sanford meets Frankenstien) And since I just couldn't grok using the serial UART (I think) I did everything using relays and optocouplers. So I SSH my way into the RPi's using Putty to initialize a VNC connection (just once per restart; although ugly, this sure beats the trauma of BASHing commands into RPi which elf up its bootup behavior to autostart VNC) So now instead of dreary CLI hell I have an ARM friendly release of the latest Arduino 1.6.13 IDE(emphasis on GUI !!)  which (as of like the last few months) NOW SUPPORTS Teensy 3.2 with Teensyduino! (meaning support for teensyloader as well) Pretty slick, huh? Write Arduino sketches "anywhere on earth" with full GUI support and flash  them  onto a Teensy (well at least it's impressive to me...)
OK, so now comes the crude hacking of ugly relays I salvaged dumpster diving (that's pronounced "F-R-EE") The flaw in my setup is how to get the freshly programmed Teensy to change hosts? So I built an mechanical A-B switcher (2 hosts sharing a single client). Originally I was way cautious so I used four double pole relays for pluging/unplugging in a 5 step process controlled by three of RPi's GPIOs. USB power supply lines from the Teensy feed the poles on a DPDT relay, disconnecting Teensy from all power if energized. N.C. contacts feed the poles on another relay that selects one of two hosts. The N.C. contacts on this relay feed the NVR, so that if control circuitry fails to deliver power to any given relay coil, the "normal" contacts default to Teensy being fully connected to the NVR, which normally doesn't shut down. The Rx & Tx lines were wired the same way.
When jumping from host to host, I used the rule for PA amplifiers to remember: last to power up, first to power down. The five step sequence is derived from this rule, which is: ENERGIZE SIGNAL RELAY, ENERGIZE POWER RELAY, TOGGLE SWITCHING RELAY, KILL POWER RELAY, KILL SIGNAL RELAY This is the weakness in my system, because I use the same script regardless of the host. The middle step is just "toggle" and led to a sloppy protocol. Rigorous fool-proofing shouldn't allow a script to end with the A-B selector having an energized relay since the fall-back safety configuration was hard-wired for all relays being in their normal, unenergized state. As long as a relay is energized, the script keeps running would be best practice. So, being lazy and absent-minded, it wasn't long before I rebooted the RPi with the Teensy still attched. Sheer terror. And the next time, merely anxiety. Subsequent breaches of protocol became simple annoyances. So now, protocol is a joke, reboot has all the dignity associated with an episode of Jersey Shore! (translation the signal/power concern hasn't been an issue in this situation)
Bottom line, mechanical port switchers have worked great for me. After the Teensy project is complete, I plan on using it to switch a USB drive between the NVR to archive important files, and a RPi for file sharing over the web. And remember, mechanical switchs (with relays belonging to the family) are still superior to Silicon based devices in many way. For example, leakage current in mechanical switches is almost nil, they have no polarity constraints, consume no current, and produce no noise in a static state.
And finally, regarding this passage:
Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.
I'd like to share a gem I unearthed on eBay: a finer link you cannot find and is as fresh as today's date. So here's a hub that I think matches your description:
http://www.ebay.com/itm/NEW-7-Port-High-Speed-USB-2-0-External-Multi-Expansion-Hub-with-ON-OFF-Switch-LO-/161831365420?hash=item25ade6ab2c
Yes, that a 7 port hub with a toggle switch and indicator led on each port. Delivered right to your door for the tidy sum of US$3.01 What kind of numbers does it benchmark at? Hmmm. you might be missing the point. It's a 7 port UBS hub with bells $ whistles with FREE SHIPPING for 3 BUCKS !!!
(CLEAR)


text:
Arduino relay module working in a wrong way
I have an Arduino Mega and a 4-channel relay module.
This is the relay module.
When the Arduino digital output is LOW, the relay is energized.  When the Arduino output is HIGH, the relay coil is de-energized.
How can I fix this?

Hiii brother, yes all relays has this problem exept keystudio relay modules, you can fix it about using a trasintor npn 2a2222 and connect gnd to collector, pin x to base and relay pin to emetor,

That's how they're designed to work energized is LOW de-energized is HIGH you just need to take this into account when writing your Arduino code

Indeed, while not particularly relevant with an ATmega, historically low-side outputs have been stronger than high-side ones, so when driving an LED (in this case probably one inside an optocoupler on the relay board) it has been conventional to use the I/O pin to drive the LED cathode, while wiring the Anode to the supply.  (It doesn't really matter which side the current limit resistor goes on, since the same current flows in the entirety of the path).

If you read the documentation or watch/read any tutorials on the mechanical relay you are using you will learn that LOW is active and HIGH is inactive for these devices. There is no way to change that behavior, that is how they are built. (Well, you can, but it's not worth the effort)
This design is intentional to prevent relay activation on power-up or system reset. And be sure to put this code in your setup routine to ensure proper system initialization.
digitalWrite(Relay, HIGH);
pinMode(Relay, OUTPUT);

Where Relay is the pin variable you defined for your relay.
Just code your routine using LOW to activate the relay when necessary.
Try this tutorial 4 channel relay tutorial

I would first set it to output, and then set it high? Not sure if it makes a difference though.

Yes. some boards are working in wrong way. I suggest you to build the relay board your self. . Its better to plan your project according to your requirement.

The board is not "working in wrong way". It was designed to operate this way, and the user "Bra1n" gives the correct answer.

You can purchase relay boards that are active high or active low or selectable, your choice. You need to read the description to determine what type it is. Here is a link for one that is selectable high or low active: "https://www.rajguruelectronics.com/Product/1730/1%20channel%20relay%20board%20with%20high%20low%20level%20trigger.pdf" This is an example not a recommendation. These are very popular with the Arduino crowd.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino uno and ttl laser
I am using my uno with gshield for my cnc. I would like to put laser on it. Laser have 3 wires. Red wire to power supply +, Black wire to power supply -, White wire to Arduino digital pin. I need to Connect the Arduino board ground to power supply -, but don't know how... Simple diagram (like child is using painter) would be great.
Thanks for help,
Urban

The Arduino board's ground connection is labelled.  Where the ground on the rest of your equipment is, and if it is safe to connect exposed low voltage circuitry such as an Arduino to (particularly if it is safely close to the earth potential or the ground of the AC mains) is a serious question, but one which this site is not the appropriate place to ask.

You take a wire, connect one end to the ground on the Arduino board and the other end to the ground on your power supply. Don't forget to strip the insulation. It doesn't get simpler than that.


text:
Arduino digital I/O pins
I heard that using digital io pins in INPUT_PULLUP mode is much reliable and stable than in the case of using them in INPUT MODE.Then why is INPUT MODE still used...I mean Why isn't INPUT_PULLUP mode put as default ??

I don't think that first statement is correct. It really depends on the application. Sometimes a pull-up is needed, sometimes it's not, or worse sometimes a pull-up will even make the circuit not work or damage external components.

When the internal pullups are activated, a small amount of current is sourced by the pin's circuitry whenever the input is low.
That means that to drive the signal low, an external driver must not only sink current to discharge the capacitance of the internal and external circuitry, but it must continue doing so to dominate the attempt of the internal pullup to make the line high so that the voltage of the resistive voltage divider formed by the internal and external resistors is low enough to be an unambiguous low.
This means that the external circuit must be stronger - not normally a problem for an active device, but potentially an issue for monitoring some very high impedance external circuit.  So for example, if you wanted an external pull-down resistor, it would have to be substantially lower in value than the internal pull-up.
It also makes low power design (long life on batteries) difficult, as a system cannot take advantage of the best micropower suspend modes when any signal is being asserted against the direction of a pulling resistor.  With just one or two such cases you might still get reasonable life when using flashlight batteries, but not with a coin cell, something a well designed ATmega circuit can presently do.
After seeing Igor's comment, and re-reading your post, it seems maybe you are asking why the default is to have them disabled, rather than why you have the ability enable/disable them at all.  Most likely, the reason the Arduino core software has them disabled by default is because the ATmega resets that way.  As to why the ATmega resets that way, you might have to ask the design engineers, but generally it has been the norm to have an MCU reset to a state where it has the least influence on the external circuitry.  However, that is not necessarily the best - floating (undriven) inputs can potentially cause a typical CMOS input structure to consume more power than ones weakly driven to a known value.

I haven't done any low power with AVR, but on larger SoCs it's common to have different pin configuration for sleep mode, where only the wakeup sources are left configured active, while the rest is programmed to minimize overall battery current. In this case the pullup could be disabled during sleep and re-enabled after wakeup. Assuming that the input is sufficiently stable. But most likely one wants to debounce it anyway, if it's a button or similar jittery source.

I guess I had actually misread the question a little bit, and instead answered a different one about why the pullups are not permanently enabled, rather than why they merely default to being disabled.  In terms of what to do during sleep/suspend, typically if you have something like a switch rather than a bipolar external driver, you want a pulling resistor holding the signal in the state expected while asleep, and to wake and deal with any change.


text:
How to deal with launch4j error
It seems that the last several times I've tried to open Arduino IDE I've encountered an error that says Launch4j, "an error occurred while starting the application".  It takes some time before that happens.  I think I've seen some stuff online about this, however I've seen some mixed answers and results for how to solve that problem.  I'm using it on a Windows 7, 64 bit system.  I've tried opening it up while my Arduino was connected and it didn't work.


text:
Can burn bootloader but not sketches... thoroughly mystified!
I have a custom board designed to be essentially identical to the Arduino Micro (Atmega32u4). I can burn the bootloader (Caterina) and it burns just fine, including the fade-then-slow LED signal that indicates a successful bootloader burn. However, it does not turn up under USB. What am I doing wrong?

Explain better what you mean with "it does not turn up under USB". Add the details of how you burn the bootloader. Do you compile it yourself? How are you sure that it is flashed correctly? There is too little information in your question.

The bootloader has been burned straight from the Arduino IDE using a USBasp and a Diamex AVR (effectively the same as the MkII programmer). It completes the burn, completes the verification successfully, and uploads the blink sketch. At first run, the first 12 (I think) blinks are slow-fade.
When I then connect the board with a USB cable, it is not listed as under /dev as a tty device and it does not turn up in the Arduino IDE, either.

Oh, and to add to the weirdness: the board powers just fine from USB. It's also not a power issue as I get the same result with a reliable powered hub.

"Custom board essentially the same as" what is the difference?

What does dmesg tell you?

@Paul It has some components directly on its I2C bus. It is no different from an Arduino Micro with two I2C devices wired up to it. The power consumption is at least theoretically ok.

dmesg does nothing.


text:
how to differentiate in code between Sangunio and Microduino core+
Sanguino and Microduino core+ both uses ATMEGA644PA. I need to write a piece of code in my library where I need to check what board has been selected.

#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#   define TIMER_PWM_PIN  11             // Arduino Mega
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)// Sanguino or microduino
#    define TIMER_PWM_PIN  13        //Sanguino PD5
#elif defined(__AVR_ATtiny84__)
# define TIMER_PWM_PIN  6
#else
#   define TIMER_PWM_PIN  9              // Arduino Duemilanove, Diecimila, LilyPad, etc
#endif

If I used the above code #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)// Sanguino or Microduino will be true for both Microduino and Sanguino.
Is there a way I can know which one is it?
Here is the board.txt section for Microduino core +
##Microduino Core+ (644pa)
##############################################################
644p.name= Microduino/mCookie-Core+ (644pa)

644p.upload.tool=avrdude
644p.upload.protocol=arduino

644p.bootloader.tool=avrdude
644p.bootloader.unlock_bits=0x3F
644p.bootloader.lock_bits=0x0F

644p.build.board=AVR_PLUS
644p.build.core=arduino
644p.build.variant=plus

Never heard of either of them. Do they have specific Arduino IDE configurations for them? Do those configurations define a _BOARD_xxxx_ macro you can examine?

I ll check that !

Where should they be?

In a file called boards.txt somewhere wherever the boards were installed to by the IDE.

Ok and how should that appear?

As a file. Called boards.txt. What more do you want? It has text in it. Key/value pairs. In groups for the different boards.

I mean which key:value pair will define that? is it the variant? or board?

I have no idea in the current version. It used to be board.define IIRC in older versions.


text:
Is there a way to replace an Arduino core function without modifying the Arduino code?
(Let's just skip the suggestions that it's the wrong idea and interrupts for a while...).
Is there a way to replace the digitalWrite() method (for example) so I can add something more to happen in there? But the following rules must be obeyed:

A call to digitalWrite(pin, value) must invoke the new method.
A call to digitalWrite(pin, value) from a different library included in my code (SD.h for example) must invoke the new method.
None of the Arduino files can be modified (I don't want to do it on every Arduino version upgrade).
Everything must be done in a header file that I can include to use the new function.

I have tried this and it works, but only in my code, not in external libraries that I include after this header:
#include <Arduino.h>

class PinsHook {
  public:
    static void digitalWriteHook(uint8_t pin, uint8_t value) {
      digitalWrite(pin, value);
      if (pin == 8) {
        Serial.print("Pin ");
        Serial.print(pin);
        Serial.print(" changed to ");
        Serial.println(value);
      }
    }
};

#define digitalWrite(pin, value) PinsHook::digitalWriteHook(pin, value)

This library seem to be able to do it using templates.

Not sure about the Arduino IDE (I don't have it installed right now) but using UECIDE it's as simple as defining a new digitalWrite function in your code.  When the whole shebang gets linked together the function in your code overrides the function in the libraries.
void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(800);
}

void digitalWrite(int pin, int level) {
    // Not gonna do anything!
}

Comment out the digitalWrite function and the LED blinks.  Uncomment it and it doesn't blink any more.

Yes, I think it's working in external libraries too! But this way I can't invoke the original digitalWrite() from this method because the method is calling itself (stack overflow!). Can this be solved? If my method was the linked one, then I think the original method was not included at all and can't be called - am I right?

You are correct. You will have to copy and paste the content of the original digitalWrite into your variant to use it.

I have tried that but it doesn't compile. Some things are missing. If you can create an example code of such method, overriding and calling the original method (and add it to your answer), then it will be the answer I'm looking for.

There is probably a huge amount in the existing digitalWrite that you don't need. It's been made to be generic, but if you only want to do specific things with specific pins you could hard-code those calls to the PORT registers yourself.

@P.W. overwriting a single function will only work if it's the only function in the module. "The smallest unit the linker knows about is the object module". So, if the linker finds a matching function in your code, it will bring that module in and ignore the rest of the methods in the code lib. I believe that's what's causing the compiler failure you mentioned. More info in my answer below.

2018: Spend some hours with UECIDE, looks okay however it is not ok, many bugs. After changing some code (AVR) It compiles just once and after relaunching the IDE it didn't compile (define problem which doesn't exists before). ESP code, incompatible defined types in the library, changed, now problem AsyncWebServer which cannot be solved. IDE doesn't pick up library changes, needs to restart the IDE, etc. Don't waste your time on it, maybe try it after a few years.

If you find issues with UECIDE I suggest you raise them as issues on the github repository. that way there is a chance they may get fixed. If you just moan about unspecified problems they will never get fixed. My guess, though, is that you are just too used to the over simplified Arduino environment and haven't found the right options in the menus to do what to want - like the one to rescan all the libraries and suchlike.

Did you try with a C macro?
#define digitalWrite(a, b) \
(pre(), digitalWrite(a, b), post())

this evaluates to the retval of post()
you can omit either the pre() or the post() functions/macros.
This needs to be placed somewhere that is included whenever the header for digitalWrite is included, so that it can override it.
The only other alternative is to become creative with the library binary.
Or, just be reasonable and modify the source code.
It's specifically available so that people can modify it.
Wrt not repeating the modification every time there is a new Arduino release, that should be avoidable.
If you build the environment from the git sources, you can maintain your patch by merging/rebasing onto the master branch.

Yeah, but that's the last resort. Your macro works just like my macro (see last line of my code) - does not work in other libraries. I'm searching for a non-invasive way to make it included into other libraries. Any ideas?

You are going against every design principle used in designing function calls and libraries :-D What you want to do is closer to hacking a binary than altering the source code of a program. The only pseudo-legal option left is to play with the linker. For example rename the original function and use --wrap to hijack it. Check this as starting point https://sourceware.org/binutils/docs-2.21/ld/Options.html#Options

Btw, if you only want to track what is going on at pin level, you could use a logical analyzer - it's very cheap and more reliable than some prints. Plus it adds zero overhead to the program. See the section "sigrok and pulseview" about in the middle of the answer to http://arduino.stackexchange.com/questions/22898/how-to-design-and-debug-a-custom-i2c-master-slave-system

I know. I am thinking about redirecting pins, not debugging. And by redirecting I mean sending them through an expander or shift register for example, which the original libraries just cannot do. I'm out of pins and I don't want to write my own versions of the standard libraries. Does it make sense now?

Arduino uses the avr compiler to compile its standard library into a core.a file.
Due to the way the avr-gcc linker works and the order in which Arduino specifies the link order, you're able to "override" the behavior of core functions by copying the file that contains the method you want to alter into your project.

The compiler compiles a single high-level language file (C language,
  for example) into a single object module file. The linker (ld) can
  only work with object modules to link them together. Object modules
  are the smallest unit that the linker works with.
Typically, on the linker command line, you will specify a set of
  object modules (that has been previously compiled) and then a list of
  libraries, including the Standard C Library. The linker takes the set
  of object modules that you specify on the command line and links them
  together. Afterwards there will probably be a set of "undefined
  references". A reference is essentially a function call. An undefined
  reference is a function call, with no defined function to match the
  call.
The linker will then go through the libraries, in order, to match the
  undefined references with function definitions that are found in the
  libraries. If it finds the function that matches the call, the linker
  will then link in the object module in which the function is located.
  This part is important: the linker links in THE ENTIRE OBJECT MODULE
  in which the function is located. Remember, the linker knows nothing
  about the functions internal to an object module, other than symbol
  names (such as function names). The smallest unit the linker works
  with is object modules.
When there are no more undefined references, the linker has linked
  everything and is done and outputs the final application.
....
The linker will search libraries in the order that they appear on the
  command line. Whichever function is found first that matches the
  undefined reference, it will be linked in.

Arduino's linking occurs in this order:

Project Files
Libraries
core.a (Arduino std lib)

So, copying the file from the Arduino installation location (C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino) into your project and modifying it will result in it using your modified implementation.
This will certainly over-ride it for any files in your project, and I believe it will also override it in any libraries you're using as well, so be careful with this approach.

Just throwing an idea. No time to test now.
Edit: I tested the solution below, and it works as expected,
provided both the __wrap_ and __real_digitalWrite() are declared
extern "C".
If you can convince the IDE to add extra options to the compile command
line, you could:

name __wrap_digitalWrite() your implementation of digitalWrite()
inside it, call __real_digitalWrite() when you want to get the
implementation from Arduino core
add -Wl,--wrap=digitalWrite to the compile command of the final
link step

Example wrapper:
extern "C" {
    void __wrap_digitalWrite(uint8_t, uint8_t);
    void __real_digitalWrite(uint8_t, uint8_t);
}

// Calls to digitalWrite() are diverted to this.
void __wrap_digitalWrite(uint8_t pin, uint8_t value)
{
    __real_digitalWrite(pin, value);  // call implementation from Arduino core
    if (pin == 8) {
        Serial.print(F("Pin 8 changed to "));
        Serial.println(value);
    }
}

Trying to put this inside a class won't help.
C.f. the man page of gnu ld.

Please explain step 3 some more: How do we "add -Wl,--wrap=digitalWrite to the compile command of the final link step"?

In your code module, define your own wrapper function, and use the global scope operator to reference the Arduino function:
void pinMode(int pin, int pinmode)
{
  /*use my custom function?*/
  if(pin >= MY_OWN_PIN_CODES_BASE)
  {
    /*todo : my own custom pin access*/
    example_pinmode(pin, pinmode);
  }
  else /*use regular Arduino function*/
  {
    /*use global scope operator :: to call Arduino library version*/
    ::pinMode(pin, pinmode);
  }
}

Remember, the linker has rules for which one it references.  The global scope operator forces the linker to choose the globally available one, while the custom wrapper function is seen privately by the module.

To satisfy the OP's requirements, the wrapper should work in global scope. In this situation your technique yields an infinite loop.

"Maybe" using the c++ "functions overriding" feature can help
void digitalWrite(uint8_t P, int8_t V, bool _wrap)
{
  Serial.print("wrap digitalwrite");
  digitalWrite(P,V);
}

Thus, if you call in you main application:
digitalWrite(pin_button, 1, 0);

The wrapped version will be called
and if you used this:
digitalWrite(pin_button, 1);

The original one will be called

You may also use this definition:
void digitalWrite(double P, int8_t V)
{
  Serial.print("wrap digitalwrite");
  //digitalWrite(P,V); Calling it even with (int) P will cause a recursive loop
}

But in-order to use it you need to define a variable with double type:
double pin;
pin = 13;
digitalWrite(13,1);

This doesn't satisfy the first two requirements of the OP.

I know, I just thought that this will help in someway (and maybe enhanced by others comments).

@EdgarBonet see the new update if you're interested. This satisfies all the requested.

Except point 2, when calling from an existing library.

The information from Rubber Duck is correct but incomplete.
I need a huge amount of digital PWM output for hobby train control.
So I connected 4 x 74HC595 to my At Mega which must be fed with a 2 kHz bit pattern through 0,5 ms. interrupts.
My serial shift function that shifts 32 bits into the registers takes 562 us per cycle. Impossible.
I made an optimized version of digitalWrite and Read, which takes 328 us. Now it is possible to PWM with 2 kHz. The trick is that my optimized function remembers the last 2 Pins including its bitmasks and outports;  and  I skip the Timer check. It is thread safe. For a single digitalWrite this takes a tiny bit more time. With repeating writing to datapin and clockpin it improves the standard Arduino digitalWrite with about 42%.
By the way: With the digitalWriteFast library the result is 45,8 µs, a really enormous improvement. But this library handles only writes, if the pin number is known (and thus fixed!) at compile time. That is not the case with my LiquidCrystal library, where either 4 or 8 bits parallel are written to the shield via 4 sequential pins.
I got my optimized digitalWrite only working for my application including the LiquidDisplay when I copied the C:\Users\Dell\Downloads\arduino-1.8.5\hardware\arduino\avr\cores\arduino library to a subfolder in the folder of my application, called
C:\Users\Dell\Google Drive\ …\…..\AppFolder\libraries.
When I replaced in both folders the wiring_digital.c with my optimized version, it worked.
I could not get it at work, when I only replaced the wiring_digital.c in the Arduino library (the LiquidCrystal took the standard function somewhere else).
Adding only wiring_digital.c in de subfolder of my application generated a mass of linking errors.
Thus I copied the whole Arduino folder (which is not that large) to my subfolder in the application and it compiles without any problem. Not a very elegant solution, because there is a replication of the whole library; but it works.
Conclusion to override a core Arduino function:
•   Put your changed function(s) (.c and/or .h) in the Arduino library, and copy this library entirely to the subfolder "libraries" in your application folder.  Then all other libraries will also use your own changed function.
Conclusion performance digitalWrite in a real 32 bit serial shift :
•   An optimized  generic digitalWrite and Read easily outperforms the standard one with 42% if 2 pins are used in repetition.
•   digitalWriteFast (with determined pins at compile time) outperforms the standard digitalWrite in a real 32 bit shift application with 92% (is 12,2 times faster).
Hope this helps other Arduino users…..
//**********************
void digitalWrite(uint8_t pin, uint8_t val)
//**********************
{
uint8_t
  timer,
  bit,
  port;

volatile uint8_t *out; // volatile because bitmask may be changed by (higher) interrupt

uint8_t oldSREG;

static uint8_t pin1 = 0,
               pin2 = 0;

static bool    p1   = true; // boolean toggle memory

static uint8_t // Store 2 sets of port/out adresses static

//          timer1, //now exclued. Safety threat?
          bit1,
          *out1,
//          timer2,
          bit2,
          *out2;

  oldSREG = SREG;  // CLI for thread proof function
  cli();
  if ( (pin == pin1) || (pin == pin2) )
  {
    if (pin == pin1)   //Compiler optimizes this excellent (see ASM listing)
    {
      if (val == LOW)
      {
        *out1 &= ~bit1;
      } else
      {
        *out1 |= bit1;
      }
    }
    else
    if (pin == pin2)
    {
      if (val == LOW)
      {
        *out2 &= ~bit2;
      } else
      {
        *out2 |= bit2;
      }
    }

    SREG = oldSREG;
  }
  else  //normal clumsy digitalWrite operation
  {
    SREG = oldSREG;   //Enable interrupts again
    timer = digitalPinToTimer(pin);
    bit = digitalPinToBitMask(pin);
    port = digitalPinToPort(pin);
    if (port == NOT_A_PIN) return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
//    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    out = portOutputRegister(port);

    oldSREG = SREG;
    cli();

    if (val == LOW) {
      *out &= ~bit;
    } else {
      *out |= bit;
    }

    if (p1)        // Save this port, bit and out, also atomic
    {
      pin1  = pin;
      bit1  = bit;
      out1  = out;  // save the pointer, not the value
    }
    else
    {
      pin2  = pin;
      bit2  = bit;
      out2  = out;  // save the pointer, not the value
    }
    p1 = !p1;
    SREG = oldSREG; //enable interrupts
  }
}

//**********************
int digitalRead(uint8_t pin)
//**********************
{

uint8_t
  oldSREG,
  timer,
  bit,
  port;

static uint8_t pin1 = 0;

bool           readBit;

static uint8_t // Store 2 sets of port/out adresses static

//          timer1, //now exclued. Safety threat?
              port1,
              bit1;

  oldSREG = SREG;
  cli();
  if (pin == pin1)
  {
    readBit = (*portInputRegister(port1) & bit1);
    SREG = oldSREG;
    return readBit;
  }
  else
  {
    SREG = oldSREG;
    timer = digitalPinToTimer(pin);
    bit = digitalPinToBitMask(pin);
    port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
  //  if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    oldSREG = SREG;
    cli();
    pin1 = pin;       //Atomic operation pin - bit combi must be correct
    bit1 = bit;
    port1 = port;
    SREG = oldSREG;

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
  }
}


text:
How to Change the Output Resolution of Sine Wave Controller
I have code that receives values from a serial connection, then uses those values to generate sine wave points. These sine wave points are used to position multiple servos.
I am currently trying to decrease the resolution of the sine wave points so there is more time for the servo to reach its given position.
The only way I can think of to accomplish this is by increasing the time between writing servo positions. As far as I can tell, I have implemented this correctly, however it results in a sine wave of a lower frequency.
The method I am using to alter the resolution is by changing the variable sine_time, which is used in the conditional statement if(currentMillis - previousMillis >= sine_time), near the bottom of the program.
/*
This is a program that recieves sine wave parameters from a serial connection in a single string.
The string is parsed and converted into numbers, which are plugged into 8 sine equations to generate
positions for each joint of the robot.
*/

#include <Servo.h>

Servo SB, SF, HB, HF, EB, EF, KB, KF;
int iAmp, iF_offset, iB_offset, iFk_offset, iBk_offset, pos[] = {0,1,2,3,4,5,6,7};
unsigned int t = 0;
unsigned long previousMillis = 0;
float fKnee_amp, fAfreq, fPhase, fGait;

void setup(){
  //Start serial stream at 115200 baud
  Serial.begin(115200);

  //Connect servos to Arduino
  HB.attach(2);
  KF.attach(3);
  SB.attach(4);
  EB.attach(5);
  HF.attach(6);
  KB.attach(7);
  SF.attach(8);
  EF.attach(9);

  delay(3000);
}

void loop(){
  char c, buffer[10];
  String readString, amp, knee_amp, afreq, gait, phase, f_offset, b_offset, fk_offset, bk_offset;
  //change the resolution of the sine wave (lower value is higher resolution)
  //digital servos refresh at a rate of 50Hz which is 0.02s
  float sine_time = 100;

  while (Serial.available() && readString.length() < 37){
    //delay to allow buffer to fill
    delayMicroseconds(10);
    if (Serial.available() > 0){
      //get one byte from serial buffer
      char c = Serial.read();
      //creates the string "readString"
      readString += c;
    }
  }

  if (readString.length() > 36){
    //see what was received
    Serial.println("The string is: " + readString);
    Serial.println(readString.length());

    //parse serial string into separate parameters
    amp = readString.substring(0, 3);
    knee_amp = readString.substring(3, 7);
    afreq = readString.substring(7, 11);
    phase = readString.substring(11, 15);
    gait = readString.substring(15, 20);
    f_offset = readString.substring(20, 24);
    b_offset = readString.substring(24, 28);
    fk_offset = readString.substring(28, 32);
    bk_offset = readString.substring(32, 36);
    /*
    //Print to serial monitor to see parsed results
    Serial.println("Hip Amp: " + amp);
    Serial.println("Knee Amp: " + knee_amp);
    Serial.println("Afreq: " + afreq);
    Serial.println("Gait: " + gait);
    Serial.println("Phase: " + phase);
    Serial.println("F Offset: " + f_offset);
    Serial.println("B Offset: " + b_offset);
    Serial.println("Fk Offset: " + fk_offset);
    Serial.println("Bk Offset: " + bk_offset + "\n");
    */
    //convert string values to numbers
    iAmp = amp.toInt();

    knee_amp.toCharArray(buffer, 10);
    fKnee_amp = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    afreq.toCharArray(buffer, 10);
    fAfreq = atof(buffer)/100;
    memset(buffer, 0, sizeof(buffer));

    phase.toCharArray(buffer, 10);
    fPhase = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    gait.toCharArray(buffer, 10);
    fGait = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    iF_offset = f_offset.toInt();
    iB_offset = b_offset.toInt();
    iFk_offset = fk_offset.toInt();
    iBk_offset = bk_offset.toInt();

    //clear strings
    readString="";
    amp="";
    knee_amp="";
    afreq="";
    gait="";
    phase="";
    f_offset="";
    b_offset="";
    fk_offset="";
    bk_offset="";
  }

  //if the joints should be oscillating
  if (fAfreq > 0){
    //determine joint positions
    pos[0] = iAmp * sin(fAfreq*t) + 1500 + iF_offset;
    pos[1] = iAmp * sin(fAfreq*t) + 1522 - iF_offset;
    pos[2] = iAmp * sin(fAfreq*t + fGait) + 1500 + iB_offset;
    pos[3] = iAmp * sin(fAfreq*t + fGait) + 1446 - iB_offset;

    pos[4] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fPhase) + 1500 + iFk_offset;
    pos[5] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1500 - iFk_offset;
    pos[6] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fGait + fPhase) + 1500 + iBk_offset;
    pos[7] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fGait + fPhase) + 1538 - iBk_offset;
    /*
    //print parameter variables
    Serial.println(iAmp);
    Serial.println(fKnee_amp);
    Serial.println(fAfreq);
    Serial.println(fGait);
    Serial.println(fPhase);
    Serial.println(iF_offset);
    Serial.println(iB_offset);
    Serial.println(iFk_offset);
    Serial.println(iBk_offset);

    //print servo positions
    Serial.println(pos[0]);
    Serial.println(pos[1]);
    Serial.println(pos[2]);
    Serial.println(pos[3]);
    Serial.println(pos[4]);
    Serial.println(pos[5]);
    Serial.println(pos[6]);
    Serial.println(pos[7]);
    */
    //get time in milliseconds
    unsigned long currentMillis = millis();

    //if the time threshold has been passed
    if(currentMillis - previousMillis >= sine_time){

      Serial.println(currentMillis - previousMillis);

      previousMillis = currentMillis;

      //write servo positions
      HB.writeMicroseconds(pos[2]);
      KF.writeMicroseconds(pos[6]);
      SB.writeMicroseconds(pos[0]);
      EB.writeMicroseconds(pos[4]);
      HF.writeMicroseconds(pos[3]);
      KB.writeMicroseconds(pos[7]);
      SF.writeMicroseconds(pos[1]);
      EF.writeMicroseconds(pos[5]);

      //increment time parameter
      t+=1;
    }
  }
}

Your sine waves depend on “time” via appearances of fAfreq*t in lots of places.  However, t actually is a pass counter, rather than reflecting true elapsed time.
Instead of incrementing t by 1, increment it by a value that's proportional to elapsed time.  Or, more directly, set t equal to a multiple of elapsed time.  For example, whenever you start over, record current time via basetime = millis().  Then, just after your //determine joint positions comment, say t = speedratio * (millis()-basetime);.

authors: خالد الهزازي