Is volatile needed when variable is accessed from > 1 ISRs, but not shared outside ISRs? It's clearly documented that when global data is shared with an ISR and the main program, the data needs to be declared volatile in order to guarantee memory visibility (and that only suffices for 1-byte data; anything bigger needs special arrangements to guarantee also atomicity). Here we have good rules:

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

But is volatile needed when the variable is accessed from > 1 ISRs, but not shared outside ISRs? For example, I have a function that maintains internal state using a static variable:

void func() {
    static volatile long counter; // volatile or not?
    // Do stuff with counter etc.
}

That function is called in two ways: from pin interrupt, and from TimerOne library:

attachInterrupt(0, func, CHANGE);
Timer1.attachInterrupt(func);

There are no atomicity problems, since when an ISR is entered, interrupts are automatically disabled, but this volatile is more of a compiler question: what is cached and what is not.

Better safe than sorry, of course...

volatile only informs the compiler's code generator that the variable may be modified by something other than the code being generated, so not to assume any copy of it remains accurate.

ISR code must be written/generated under the assumption that it has no context at entry, and preserve the CPU's context around its (ISR's) own operation. So, as with the indivisbility of non-atomic operations, volatility depends, in this case*, on whether or not interrupts are allowed to nest. If non-nesting is guaranteed, the shared variable can not change by other than this ISR during its own execution. If your ISR might someday be used in an environment where interrupts are allowed to nest, then that constraint will no longer hold.

* in this case:
I'm assuming a software-maintained variable here. If we're talking about a variable that can be updated by a hardware event, a timer register for example, all bets are off: the variable is volatile no matter what.


How to increase the frequency of data transmission of SIM900A GSM Module connected to Arduino Uno? I have a SIM900A GSM Module hooked onto an Arduino Uno board. The Arduino is connected to a MPU6050 Accelerometer which is constantly monitoring data at 1 second interval. I am trying to transmit the gathered data to ThingSpeak server. I have successfully established the connection with the server and the transmission is occurring. However, the interval between two transmitted readings are very large, varying between 1 to 3 minutes. That interval is too large to use the data. Is there any way I can enhance the transmission frequency so that the data points are close enough? At least to a few seconds distance?

There does not appear to be a complete description of how ThingSpeak throttling works.  However there is this text on the Thing Speak License FAQ web page:

As a reference, one unit provides the ability for a device sending
data to ThingSpeak at once per second to send data to ThingSpeak for
one year.

Assuming your code is working as expected and the ThingSpeak throttling is to suspend your service for 15 minutes, it may be that you are sending data faster than ThingSpeak will allow.
To test this, try to send messages slower than once per second.


Best way to power an Arduino using the Vin pin I have a powerbank rated 5v. The battery is actually 3.6v, powering the built-in SMPS to give out 5v. I have stripped one end of the USB cable coming from the power bank, powering a motor driver and the Arduino in parallel. The positive end of the power bank, which is 5v, is going into the Arduino and the motor driver IC's Vcc.

I heard that 5v is not enough to drive the Arduino from the Vin pin. And there is only one power out from the powerbank, so directly connecting the Arduino through the USB would leave nothing to drive the motor driver IC.

A USB splitter would be the obvious solution, but is there anything else I can do? The power source has to be mobile. Can I power the Arduino through the Vin with those 9v batteries commonly used in electronics hobby projects?

You have a powerbank which has a USB output, right? Why not just plug a cable from that into the Arduino USB port? That will connect the 5V directly into the 5V pin of the Arduino (probably via a switching MOSFET). Then you can connect to your motor driver from the 5V pin on the Arduino (and Gnd of course). There may be some limitations on how large a motor you can drive (based on the capacity of the power bank, and to an extent also the thickness of the traces on the Arduino board).

As others have commented, Vin is not intended for that purpose (ie. to supply 5V). You should supply 7V or more to Vin to force the switching MOSFET to disconnect the USB input. In your case you don't have 7V from the powerbank.

Here is how the Uno Rev3 power system works:

The input jack (circled in blue) goes through a diode (D1) to the Vin line.

Vin then goes through the 5V voltage regulator (U1) to provide +5V.

However on the top left you see 2 x 10K resistors (RN1A and RN1B) which make a voltage divider from Vin to Gnd. This is compared to the output of the 3.3V voltage regulator by U5A op-amp (circled in red). If higher, then T1 (circled in green) will turn off, disconnecting USBVCC from the +5V line. If lower, then USBVCC is connected to +5V. The nett effect is that if Vin in greater than 6.6V (because of the voltage divider) then the circuit chooses to use Vin, otherwises it uses USBVCC (USB power).

That's why they recommend to use 7V or more into Vin.

Note that you lose around 0.7V through the diode, which is why you need something like 7.3V at the input jack to allow for the loss of the 0.7V before the op-amp compares it to 6.6V.


Non intrusive current sensor with unreliable (strange) readings I have a project where I will mount 6 non intrusive current sensor model SCT013 (100A/50mA) manufactured by yhdc.com on an Arduino Mega.

Virtual ground and Burden resistors are 1% tolerance.

To start testing I mounted 2 sensors using the principles of connection found at (http://www.homautomation.org/2013/09/17/current-monitoring-with-non-invasive-sensor-and-arduino/). Code below.

#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon0;                   // Create an instance
EnergyMonitor emon1;                   // Create an instance

int Calib = 60;

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

  emon0.current(A0, Calib);             // Current: input pin, calibration.
  emon1.current(A1, Calib);             // Current: input pin, calibration.

   }

   void loop(){

double Irms0 = emon0.calcIrms(1480);
double Irms1 = emon1.calcIrms(1480);

Serial.print("Sensor0: ");
Serial.print(Irms0);
Serial.print(" Amps ");

Serial.print("Sensor1: ");
Serial.print(Irms1);
Serial.println(" Amps ");

}
//------------end------------

The code I found is for UNO and a single sensor and I just added a second, it works fine and sensors do independent readings well.

Both sensors are mounted on the same test live wire so I have to get more or less the same readings most of the times and it is precisely the case with readings floating between sensors on the order of 100s of miliamps.

My problems are:

Even with no load I get, on both sensors, a reading that varies from 270 to 320mA
When I connect a hair dryer that consumes in one mode 10A and in
another mode 5A the readings are a lot closer to the expected (I am
also checking with a clamp meter)

The problem seems to be the no load condition and the imprecise readings at low currents.
I could exclude readings under a certain value on my code to solve the no load problem but them I would be ignoring real electrical measurement situations.

Every time you use a real clamp meter, you should zero it out before measuring.

The hall effect sensors you describe are the same way. There's magnetic pull from the earth and other sources that need to be corrected for. When you draw 5 or 10 amps, that noise is masked out. They are likely still apart roughly the same # of ma as the baseline reading.

Once you subtract the no-load load from each, maybe on startup, you should get a lot better readings in terms of accuracy and precision.


Arduino will not recognise USB ports on my Mac running Sierra Arduino will not recognise USB ports on my Mac running Sierra
I am a teacher who helps teachers to use LilyPad. I used to be able to plug in my LilyPad Arduino and see the USB port. I have read all the answers and dowloaded the drivers from Spark fun and another driver from Github. Nothing is working and i am not technical enough to find the answer myself.  I have spent three hours today trawling through the answers to this problem and still cannot fix it myself. I am a luddite who needs a simple step by step remedy. Apple support had no idea when I rang them and told me it was an Arduino problem and to talk to them. you cant talk to anyone at Arduino you can only go to the forums. the forums tell you to read others answers before you post. I have. it's still not working. i need help. And not a lecture about being on a forum asking dumb questions.

I even mucked around in terminal and am hoping it's not a 'terminal" problem because I have no clue what i am doing. If you can explain in plain speak please respond. i have to teach this stuff in 4 days.

This is the message I get when I try to upload a sketch

I spoke to a very clever friend who has had similar problems. The answer lay in downloading the FTDI helper package not just the driver.  If anyone else is having a similar problem the website is

https://www.ftdichip.com/Drivers/D2XX/MacOSX/D2xxHelper_v2.0.0.pkg

I downloaded it and now my lilypad and USB port is recognised by the Arduino software.

Just in time for Thursday.

Thanks to all who tried to help.

K


There's an error I don't know how to fix I basically have a bread board with an rgb led and a peizo buzzer with a photocell.

I have the codes for both. If I put a code for the rgb, it works. If I put the code for the peizo, it works. Once I paste both codes onto it it says there's an error because "void setup" and "void loop" are already defined. What do I do to get both things to work?

rgb led code:

/*
Adafruit Arduino - Lesson 7. RGB Fader
*/
int redLEDPin = 11;
int greenLEDPin = 10;
int blueLEDPin = 9;
int redSwitchPin = 7;
int greenSwitchPin = 6;
int blueSwitchPin = 5;
int red = 0;
int blue = 0;
int green = 0;

void setup()
{
  pinMode(redLEDPin, OUTPUT);
  pinMode(greenLEDPin, OUTPUT);
  pinMode(blueLEDPin, OUTPUT);
  pinMode(redSwitchPin, INPUT_PULLUP);
  pinMode(greenSwitchPin, INPUT_PULLUP);
  pinMode(blueSwitchPin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(redSwitchPin) == LOW)
  {
    red ++;
    if (red > 255) red = 0;
  }
  if (digitalRead(greenSwitchPin) == LOW)
  {
    green ++;
    if (green > 255) green = 0;
  }
  if (digitalRead(blueSwitchPin) == LOW)
  {
    blue ++;
    if (blue > 255) blue = 0;
  }
  analogWrite(redLEDPin, red);
  analogWrite(greenLEDPin, green);
  analogWrite(blueLEDPin, blue);
  delay(10);
}

peizo code:

int speakerPin = 12;
int photocellPin = 0;

void setup()
{
}

void loop()
{
  int reading = analogRead(photocellPin);
  int pitch = 200 + reading / 4;
  tone(speakerPin, pitch);
}

Putting all other possible issues aside such as pin and timing conflicts.

Rename the sketch setup() and loop() functions, for instance, rgb_led_setup() and rgb_led_loop(), and peizo_setup() and peizo_loop(), then rewrite:

void setup() {
  rgb_led_setup();
  peizo_setup();
}

void loop() {
  rgb_led_loop();
  peizo_loop();
}

Cheers!


Changing pins used in ArduinoISP example I have built my own ATTiny programmer, but made a bit of a mistake along the way - I didn't align the headers properly, and now instead of them plugging into pins 10, 11, 12 and 13 as per the ArduinoISP example - they now plug into pins 8, 9, 10 and 11.

If I use some jumper cables to wire the pins to match the ArduinoISP example, it all works fine, meaning the wiring on the actual board is OK, however, I want to be able to just plug my board I have made straight in, and thus need to get the bootloader burning and the uploading to work via pins 8, 9, 10 and 11 instead.

I have tried modifying the example myself by replacing the references to RESET, MOSI, MISO and SCK with my own pin numbers, but this doesn't seem to suffice. When I try to burn the bootloader now, I get the following error:

avrdude: stk500_program_enable(): protocol error, expect=0x14, resp=0x50
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51

If I try to upload a sketch using my version which has the custom pin numbers, I get this error:

avrdude: stk500_getsync(): not in sync: resp=0x00

The wiring of my programmer is the same as can be found here: http://highlowtech.org/?p=1706 except I want the programmer sketch to work with different pins.

Thanks

You can't change the pins.

ArduinoISP uses the SPI interface on pins 10-13 which is provided by the underlying AVR hardware.


Sending MPU6050 data over serial to Java/C# Program I am using a MPU6050 Accelerometer/Gyro breakout (GY-521) to retrieve data and send it to a java program. I have tried several ways, but I couldn't find a way to send the float values calculated from the Arduino over Serial. Could you please let me know a good way of serial communication with Arduino and a Java Program? Thanks in advance.

UPDATE:

Thank you for your comments and replies. What I have tried is the I2Cdev library code. I could work with it without any issue. Code is in this link. I also could run the processing code to get a visual output. But the problem I have i that I'm not able to send the accelerometer and gyro data to a Java/C# program and process it from there. I tried sending an array of FIFO bytes from the Arduino and convert it from the C# code and processing code, but it didn't give me correct results. Now what i did was, just to send a string of values and receive it from the C# program. But I don't know whether it's good method. I would be glad if you could help me in this. Thanks again.

Arduino

#ifdef OUTPUT_TEAPOT
        // display quaternion values in InvenSense Teapot demo format:
        teapotPacket[2] = fifoBuffer[0];
        teapotPacket[3] = fifoBuffer[1];
        teapotPacket[4] = fifoBuffer[4];
        teapotPacket[5] = fifoBuffer[5];
        teapotPacket[6] = fifoBuffer[8];
        teapotPacket[7] = fifoBuffer[9];
        teapotPacket[8] = fifoBuffer[12];
        teapotPacket[9] = fifoBuffer[13];
        Serial.write(teapotPacket, 14); //Serial.write(buf, len)
        teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
    #endif

    #ifdef OUTPUT_ACCEL_STR_RAW
        mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

        String accelGyroRaw = "STX,";
        accelGyroRaw += ax;
        accelGyroRaw += ',';
        accelGyroRaw += ay;
        accelGyroRaw += ',';
        accelGyroRaw += az;
        accelGyroRaw += ',';
        accelGyroRaw += gx;
        accelGyroRaw += ',';
        accelGyroRaw += gy;
        accelGyroRaw += ',';
        accelGyroRaw += gz;
        accelGyroRaw += ',';
        accelGyroRaw += "ETX";

        Serial.println(accelGyroRaw);

    #endif

C# Code

class Program
{
    static SerialPort port = new SerialPort("COM7", 115200);
    //static int serialCount = 0;
    //static int aligned = 0;
    //static char[] teapotPacket = new char[14];
    //static float[] q = new float[4];

    static void Main(string[] args)
    {

        Console.WriteLine("****** Serial Console Read ********");
        port.Open();
        port.DataReceived += port_DataReceived;

        Console.Read();
    }

    static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        string s = port.ReadLine();
        string[] accelGyroVals = s.Split(',');
        string[] accl = new string[3];
        string[] gyro = new string[3];

        if (accelGyroVals[0] == "STX" && accelGyroVals[accelGyroVals.Length - 1] == "ETX\r")
        {
            accl[0] = accelGyroVals[1];
            accl[1] = accelGyroVals[2];
            accl[2] = accelGyroVals[3];

            gyro[0] = accelGyroVals[4];
            gyro[1] = accelGyroVals[5];
            gyro[2] = accelGyroVals[6];

            Console.WriteLine("a : " + accl[0] + " , " + accl[1] + " , " + accl[2] + "\t g : " + gyro[0] + " , " + gyro[1] + " , " + gyro[2]);
        }

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        if (port.IsOpen)
        {
            port.Close();
        }
    }
}

Sorry for this for lengthy code and if my question is unclear. It's my first time to work with an IMU. Thank you.

You may find RXTX java library helpful.

You can format the data (float as calculated at Arduino side) in any mannner that you desire. RXTX library will send the data. It will then up to the Java program (non Arduino side, like PC, etc.) how to interpret the data and extract the values.

http://playground.arduino.cc/interfacing/java

Hope this helps


SSD1306 / U8glib display fonts and commands I cannot seem to find any reference for the SSD 1306 or U8glib display font library or any command reference, like all the options for display() etc. For my fonts I been going into the utility folder and scrolling through notepad for the U8glib library but its very croweded with numbers and code. is there any reference for both libraries online that is user friendly?

First, u8glib is superceded by u8g2

Second, the u8glib wiki has a command reference and font reference.

As does the u8g2 wiki.

Neither reference lists a display() command.


Help with a rather specific implementation of FFT Library? So, I guess what I'm trying to do here is properly understand the FFT library posted here by Open Music Labs, done in C++. I believe I understand the Fourier transform, but the FFT has some nuance that I'm not quite familiar with. From what I understand, the FFT takes a amplitude vs. time signal and transforms it into its constituent frequencies like a normal Fourier transform, but it only does so at given points that break down the signal into the Arduino's clock speed divided by the number of bins decided on, for the sake of efficiency. Thus each bin actually accounts for a number of frequencies that is also equal to the clock speed divided by bin number. I'm correct so far, right?

So here's my question. I have a very specific application of the FFT that requires reading only frequencies at roughly 0-100 Hz. Everything else I don't need, and I want to know how to achieve such high resolution. I imagine that because the number of bins seems to be capped at around 512, that there must be some sort of way to decrease the clock speed to an exorbitantly low number in order to read these frequencies. How might I go about doing that? Or maybe there is a better way to apply the transform to the data at such low frequencies through some other method outside of FFT?

Second, I'm wondering how performing multiple FFTs simultaneously will affect performance, and if there is some way I can export this data to another program in order to do the heavy lifting regarding data storage, seeing as I imagine performing many FFTs all at once will decimate the available memory on the Arduino itself if all of those values aren't being kept on my computer.

Thanks in advance for any insight you guys might be able to provide

As Edgar has mentioned you are confusing things slightly.

First there is your sampling frequency. According to the Shannon-Nyquist theorem that is at a minimum of 2x the maximum frequency in your signal. So that is 2x100 = 200Hz. That's the number of samples per second in your sample set.

Secondly is your sample size, which is directly related to the FFT bucket size. For every two samples you can get one bucket. The more samples you have the more buckets you have, and the higher the resolution each bucket is. But for FFT to work you need a power-of-two sized sample set. That means 2, 4, 8, 16 etc samples.  So 256 samples would give you 128 buckets. That would be a little under 1Hz per bucket.

To make things cleaner though you can back-apply the last calculation to the first and get them to match. 256 samples at 256 samples per second will give you 128 buckets covering 0-128Hz so 1Hz per bucket.  Double that to 512 samples and you get 256 buckets at 0.5Hz per bucket. Double it again and you get double the resolution again.

The main speed issue that you will come across is not the time taken to do the FFT, but the time taken to capture your sample set. 256 samples at 256 samples per secod will, of course, take 1 second to capture. 512 samples will be 2 seconds, etc. Far longer than a decent FFT takes to calculate.


Does the compiled binary of a sketch include uncalled functions from a library? I am writing a GUI using a TFT display and the Adafruit GFX library and its default font on Arduino Nano.
I want to be memory efficient and I assumed that the 'optimise for size' default setting of the compiler would not compile and include all functions from all included libraries if those functions are never called in the sketch.
However I was reading this memory management guide which advises (on pager 20) to remove 'unused libraries' and 'unused functions' from your sketch to save memory.
So I have 2 related questions:

Does the Arduino IDE compiler include all the compiled binary from these library functions even if they are never called in the source sketch (I know that any global variables in a library will take space even if unused but I am specifically asking about unused functions)?

If that is the case would making my own modified, trimmed down, version of the standard libraries save space?

Thanks.

In general only the functions actually used by your code are included in the final linkage of the binary.
However it's not always possible for the compiler to know what is used and what isn't.
In the case of simple functions and classes there's no problem - the linker is intelligent enough to work it out and only link in the functions that are actually used.
However when it comes to more complex systems with polymorphism or when working with function pointers there are times when the compiler won't really know what is needed and what isn't so sometimes some code gets included that isn't actually wanted.
As the compiler advances those times are getting fewer and farther between, so unless you really have a dire need to reduce your code size there's really nothing much to gain. If you do have that need then you would gain more by reducing the complexity of the code in general and collapsing any polymorphism rather than removing unused functions.
BTW: the "optimize for size" has nothing to do with what code is included / excluded. Instead it controls such things as which function are selected for inline, and what loops are unrolled or not, amongst other things.


Why the bootloader burn on ATmega328 rather than Atmega16U2 in Arduino Uno I have been researching about the reason why we have a second MCU in arduino UNO for a while now. finally i understood that its been use as  USB to serial converter. the question that really bug me now, why is the boot-loader is burn on the main ATmega328 not Atmega16U2 ?

The purpose of the bootloader is to get the firmware through the serial
port and burn it into the flash. The 16U2 has no access to the 328's
flash. The job has to be done in the 328 itself.


Cannot control servo with button. I am unable to get a button on my arduino board to control a servo. I'd like the servo to rotate 90 degrees on button push, but it is unresponsive.

Is there a flaw in my code or is it wiring?

#include <Servo.h>  // servo library

const int button1Pin = 2;  // pushbutton 1 pin
Servo servo1; // servo control object

void setup()
{
  pinMode(button1Pin, INPUT);
  servo1.attach(9);

  // Set servo 1 to output?
}

void loop()
{
  int button1State;
int position;

button1State = digitalRead(button1Pin);

if (button1State == LOW);
{
  servo1.write(90);  // move servo
}

}

The problem is that servo1.write(90) does not do what you think it does.

servo.write(angle) tells the servo to go to that position, not to move by that many degrees. What you need is to set one angle when the button is not pressed, and a different angle when the button is pressed.

Normal hobby servos can move about 180 degrees. Where 0 is depends on how the servo horn is positioned. Which direction of rotation is positive depends on the manufacturer.

try something like this to set one position when the button is pressed and a different one when it is not:

if (button1State == LOW);{
    servo1.write(45);  // move servo
}
else {
    servo1.write(135);
}


Fritzing PCB design review/questions I've designed an PCB and due tot the delivery times, I kinda want to order it right now.
I don't yet have the components, so I haven't actually tried it on a breadboard.

Now I'm unsure if the PCB would work, as this also is my first try in PCB design.

It's a single-sided PCB.
All parts (should be) through hole.
I would be using SoftwareSerial since the ATTiny does not have serial (Rx/Tx).

[TL:DR] Would this PCB work?

Some points of which I'm unsure, or might be a problem:

Is the spacing of the board/lines to other components/side big enough?
Should I use a copper/ground fill? Which and why?
Are the rounded-off traces actually better as sharp edges?
It says: 36mm by 15mm isn't this too small to fit all those components?
Can I actually use the RESET pin as other functions (without changing fuse bits)?
Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Breadboard

Schematic

Layout

File

If someone needs the file:
It's opensource, no restrictions. Would be nice to give me some credits/donation, but you can freely use it for even commercial projects.
Download below:

https://www.dropbox.com/s/lggjg5fxd6s3kqc/ATTINY485.fzz?dl=0

Some credits to Nick Gammon, I've used his schematics as a reference (especially on the TX enable pin, which was quite smart, using only 1 pin).

Version2!

Changes:
 - replaced the "V" shape.
 - pull-up on the reset pin.
 - decoupling capacitors

EDIT: It's better not to use a pull-up resistor on the reset line. The ATtiny85 has this internally.

Would this PCB work?

Possibly, sometimes, under some conditions. See below.

  Is the spacing of the board/lines to other components/side big enough?

Plenty.

  Should I use a copper/ground fill? Which and why?

For your circuit there is no real electrical reason to use a ground plane. However, many fab houses like you to use at least a copper fill in the empty areas since it means less copper has to be etched off the board, and so their etchant lasts longer before it needs to be replaced.

  Are the rounded-off traces actually better as sharp edges?

Yes. Always try to avoid right-angles. Sharp corners radiate EMI noise, mitred corners radiate a lot less.

  It says: 36mm by 15mm isn't this too small to fit all those components?

Not in the slightest.

  Can I actually use the RESET pin as other functions (without changing fuse bits)?

You can only disable the RESET functionality of the RESET pin using the fuse bits - and then it becomes somewhat difficult to program: you need a HVSP (High Voltage Serial Programmer) to get it back into programming mode again.  This blog post details how it is done.

  Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Your circuit isn't complete.  There are a couple of things missing that you need to add, and some that you might want to add.

The things that are missing:

Decoupling capacitors (100nF) on the power pins of both chips
You should have one larger (10µF typical) reservoir capacitor at the power entry to the board
(Assuming RESET is enabled) Pullup resistor on the RESET pin

The things you might want to add:

RS-485 bus termination resistors

The latter are optional depending on where in the bus your module is. You need termination resistors at both ends, so it is common to have them on the boards but with jumpers to enable/disable them.


Trouble with i2c on ESP8266 I have used with partial success I2C with the ESP8266.  When it works, it works well, with many devices on the bus.  I've examined the signals on a 'scope to assure Vlo, Vhi, Tr, and Tf.

However, often it works not at all.  No I2C devices (even if there is only one connected) are detected.  This condition is determined by some unknown factor, and it stays in this condition for some time (days?) before it starts working again.  Power cycle, reset-by-button, and reset-by-reflashing do not restore operation until it works again.

This has occurred with at least three ESP8266 modules from two different manufacturers with different pinouts.  It affects all connected I2C devices.  They are all slaves to the ESP8266.

What should I try next?

The signals had looked good, but I did not examine them closely enough.  When I removed extra pullup resistors I had added on SCL and SDA, I2C worked.


Scroll String Only On Second Line Using 2x16 LCD I'm trying to scroll a string in the second row of the LCD while letting the string on the first row stay intact. I use Serial to run that part of the code as you can see. It work at first but when I try to make it run again it doesn't display anything on the second row.

I borrowed the code from :

http://code.nishantarora.in/arduino-lcd-projects/src/3f10686e7464665c5c59d7be772c00af7a4a93e8/scrollOneLine/scrollOneLine.ino?at=master

And made some changes:

// include the library
#include <LiquidCrystal.h>

// init the lcd display according to the circuit
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

// it's a 16x2 LCD so...
int screenWidth = 16;
int screenHeight = 2;

String line1;
String line2;

int stringStart, stringStop = 0;
int scrollCursor = screenWidth;

String CompleteString;
String stringArray[] = {"s=Plane", "i=Car", "h=Boat", "u=Rocket", "d=Jet",  "p=Submarine", "l=Truck", "b=Bicycle", "m=Skate", "enter=Train"};

String string1 = "String";

int countMovement=0;
int arraylimit = 9;

void setup() {

   lcd.begin(screenWidth,screenHeight);
   Serial.begin(9600);

}

void loop(){

   char ser = Serial.read();

   if ( ser == 'c' ) {
     CompleteString="";

     for (int i = 0 ; i <= arraylimit; i++) {
        CompleteString += stringArray[i] + " "; // Convert String Array To Single String
     }

     roop(string1,CompleteString);
  }

}

void roop(String line1, String line2) {

  countMovement = 0;

  while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

     lcd.setCursor(scrollCursor, 1);
     lcd.print(line2.substring(stringStart,stringStop));
     lcd.setCursor(4, 0); // 1 = word eat array of words very cool
     lcd.print(line1);
     delay(300);
     lcd.clear();

     if(stringStart == 0 && scrollCursor > 0){
        // Serial.println(scrollCursor);
        scrollCursor--;
        stringStop++;
     } else if (stringStart == stringStop){
        stringStart = stringStop = 0;
        scrollCursor = screenWidth;
     } else if (stringStop == line1.length() && scrollCursor == 0) {
        stringStart++;
     } else {
       stringStart++;
       stringStop++;
     }

     countMovement++;

  }

  lcd.setCursor(4, 0);
  lcd.print(line1);

}

From what I can see using Serial as debugging is that the problem resides in the function "roop" and in specific the line:

 if(stringStart == 0 && scrollCursor > 0){

It seems that the statement is being pass on and so it doesn't move the string as it's suppose to. I could be wrong but placing a Serial call in there yields no result the second time the function is called but the first time it did.

Any help would be much appreciated! And I know the community will be grateful too since it's difficult from what I can see in post to achieve this and make it autonomous so that no big modifications needs to be done.

You need to reset the stringStart, stringStop and scrollCursor at the beginning of the roop function.

void roop(String line1, String line2) {

  countMovement = 0;
  stringStart = 0;
  stringStop = 0;
  scrollCursor = screenWidth;

  ...

I think you also need to move the lcd.clear up. Or else the screen will be blanked when the roop function is done scrolling.

...

  while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

     lcd.clear();
     lcd.setCursor(scrollCursor, 1);
     lcd.print(line2.substring(stringStart,stringStop));
     lcd.setCursor(4, 0); // 1 = word eat array of words very cool
     lcd.print(line1);
     delay(300);

...


Execute code only once I am trying to create an if statement that only runs once, the very first time the void loop is started and switches to another code after that. But the following only executes stepper1a(). Any help would be great. Thx !

int var;
int var2;
bool executed = false;

const int M1dirpin = 4; //Stepper Dir Pin
const int M1steppin = 5; //Stepper Step Pin

void setup() {

pinMode(A2,INPUT);
pinMode(M1dirpin,OUTPUT);
pinMode(M1steppin,OUTPUT);
Serial.begin(9600);

}

void stepper1() {
  int j;
    delayMicroseconds(10);
    digitalWrite(M1dirpin,HIGH);
  for(j=0;j<=200;j++){
    digitalWrite(M1steppin,LOW);
    delayMicroseconds(10);
    digitalWrite(M1steppin,HIGH);
    delay(2);
  }
}

void stepper1a() {
  int j;
    delayMicroseconds(10);
    digitalWrite(M1dirpin,HIGH);
  for(j=0;j<=1600;j++){
    digitalWrite(M1steppin,LOW);
    delayMicroseconds(10);
    digitalWrite(M1steppin,HIGH);
    delay(2);
  }
}

void loop() {

if (executed == false) {
var = analogRead(A2);
delay(10);
if (var > 500) {
  stepper1a();
  delay(2000);
  executed = true;
  Serial.println("turned 1600");
  Serial.println(executed);
  }
else if (executed == true) {
 var2 = analogRead(A2);
delay(10);
if (var > 500) {
  stepper1();
  delay(2000);
  Serial.println("turned 200");
}
}
}
}

Updated void loop:

void loop() {

    static bool yes_we_did_the_one_time_job = false;

    if (yes_we_did_the_one_time_job) {
        var = analogRead(A2);
        delay(10);
        if (var > 500) {
            stepper2();
            delay(2000);
            Serial.println("turned 1600");
        }
    }
    else {
        var2 = analogRead(A2);
        delay(10);
        if (var > 500) {
            stepper1();
            delay(2000);
            Serial.println("turned 200");
            yes_we_did_the_one_time_job = true;
        }
    }
}

This works now, thx !!!:

void loop() {
  static bool yeswedid = false;

  if(yeswedid) {
    if(analogRead(A2) > 500) {
    stepper1();
    stepper2();
    }
  }
  else {
    if(analogRead(A2) > 500) {
    stepper1();
    yeswedid = true;
  }

  }
}

Generic solution:

void loop() {
    static bool yes_we_did_the_one_time_job = false;
    if (yes_we_did_the_one_time_job) {
        do_the_other_jobs();
    } else {
        do_the_one_time_job();
        yes_we_did_the_one_time_job = true;
    }
}


Where do serialport names come from? I'm currently writing a tool that automatically detects connected arduinos and provides a one-button solution for flashing new firmware.
I've got a couple of arduinos at home (Diecimilla, Uno R3 SMD and some nanos from china) and each type presents with a different serial port name.

Questions

Can someone explain where these port names come from?
Can I assume that /dev/cu.usbserial-A9UPDRZB is, atleast in most cases, an arduino nano?
Are there other ways to identify the type of the board?
Is the name of the serial port some kind of hash generated from informations retrieved from the device?

You cannot assume anything about serial port names. It's a choice of the operating system, and even if you find the algorithm, there's no guarantee it won't change in the future.

As a reference implementation, the Arduino IDE 1.5.x uses VID (Vendor ID) and PID (Product ID) to identify a board.

Because accessing such information depends on the underlying operating system, the IDE uses three strategies: on windows, it runs a program called ListComPorts.exe, on macosx it uses CLI tool /usr/sbin/system_profiler, on linux CLI tool udevadm


Use Wii Remote and Arduino to emulate a keyboard for Windows 10? Is it possible to use an Arduino to communicate with a Wii Remote, connect the Arduino to a Windows 10 computer, and have the Wii Remote inputs be translated into keyboard keys for Windows 10?

I've used several Wii Remote Windows 10 apps, such as WiiUSoft, but I find such programs very unreliable.

Thanks for any help.

The Arduino Leonardo and Arduino Micro (as well as other third-party boards, such as the Teensy and the chipKIT Lenny) can be directly programmed to emulate a keyboard.  There are examples in the IDE that show how to do this.

It is possible with an Uno, but that requires replacing the firmware on the USB interface's ATMega32U4 chip with special HID firmware. This is a non-standard setup, though, and may make programming of the Arduino through the USB port impossible.  So I wouldn't recommend doing that, and would instead go for a board that can directly emulate a keyboard.

There are plenty of tutorials on the web for connecting a Wii Remote with an Arduino, (including a library), so couple that with the examples in the IDE and a suitable board and you are good to go.  From then on it's just a Simple Matter of Programming...


Getting wrong values from serial.read() connected to a Raspberry Pi I set up a serial connection and sending integers from a Raspberry Pi to an Arduino.

This is the Python code in my Raspberry Pi:

import serial
ser = serial.Serial('/dev/ttyACM2', 9600)
ser.write(str(x_value));

And this is the command line output for x_value:

  -38 -38 -38 -40 - 38 - 39 - 40 - 12 18 26 25 49...

They are x coordinate values I generated and they range from -100 to 100. And here's the Arduino code for receiving serial data:

int ByteReceived;

void loop() {
  while(1) {
    if (Serial.available() > 0) {
      ByteReceived = (Serial.read());
      Serial.print(ByteReceived);
      Serial.print("\n");
    }
  }

On the serial monitor I'm receiving these numbers:

  46 45 51 48 45 53 52 45 49 52 45 52 55 55....

They are numbers between 40-60 and no way proportional to the values I sent from serial.write.

I'm really confused right now. Can someone help me to figure out what caused this problem?

Thank you so much.

ser.write(str(x_value));

Writes the string representation of the integer x_value, which is a sequence of ASCII characters.

ByteReceived = (Serial.read());
Serial.print(ByteReceived);

Reads a character (byte) and prints to the value (again as a sequence of characters).

45 51 48 45 53 52 45 49 52 45 52 55 55....

45 is ASCII character value for the character '-', 51 is the character '3', 48 is '0' and so on.

Cheers!


Is digitalWrite(pinnumber,LOW) different from ground pin I am using Tinkercad simulator, but an unusual thing happened. When I connect one wire of dc motor to pin 9 with digitalWrite(9,HIGH) and other wire to ground, the motor runs with rpm of 5555.

void setup()
{
  pinMode(9, OUTPUT);
}

void loop()
{
  digitalWrite(9, 1);
}

But instead if I connect the other wire to pin 13(say) and set digitalWrite(13,LOW) the motor runs at an rpm of 3846.

void setup()
{
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(9, 1);
  digitalWrite(13,0);
}

Can anyone explain this?

Yes, it is different.

First: Never run a motor directly from IO pins - you will damage your Arduino. Not only can a real Arduino not supply enough current, but motors generate a lot of back-EMF that will kill an Arduino.

Secondly a pin doesn't connect direct to GND or VCC - it is connected through a MOSFET that performs the switching.  That MOSFET has an ON resistance, which causes a voltage drop across it determined by the current being sourced or sunk through the pin.

You can read more about GPIO pins here.


USB host shield help Hello, I apologise for being such a noob but can someone help with this.
I am having trouble working with this. When I insert the arduino's pins into my new usb host shield , there is no indication light and when I plugged my Xbox receiver into the shield it does not turn on as it would with my desktop. Any thoughts? Please post below

Posting the clear photo is helpful because it shows the USB host board has the following problem.


How to manage dependencies? I want to include a dependency like Logging. On its page it says:

Download zip file
Put the Logging folder in "libraries\".

I don't want to believe (with a Maven mindset) that this is the way we manage dependencies in Arduino projects. That means, everybody who checks out my package would have to repeat those steps locally (or do you include "libraries\" in the version control) What's the best practice for dependency management?

Arduino is meant to be easy way for non-technical people and so it hides as much as it can from plain view to be simple.

For simple project it works at the cost of overhead of copying libraries here and there and using Arduino's "IDE". Calling programs "sketches" and manipulate it to hide, that it is in C++. And so on and so on.

If you want to make more complicated projects, version control, good environment and such, you need to leave "simply Arduino way" and start using more powerful and complicated tools.

I personally use
https://github.com/sudar/Arduino-Makefile
https://github.com/ladislas/Bare-Arduino-Project
and have it in GIT repositories.

This way I can share libraries between projects in group, also links to libraries outside the tree works, as well as gits submodules, both allowing you to have updated libraries from 3rd party aviable to all projects, also those old ones.

I still use a lot of Arduino (like setup/loop, digitalRead and such), but also I use "normal" g++ constructs on the way. Later I will diverge even more to plain C/g++/.. code probably, using some RTOS or so, but now my needs are not so far yet. (google "arduino rtos" I am currently reading https://github.com/greiman/NilRTOS-Arduino )

Arduino is not meant to be "best practice" anyway. It is meant to be "fast and easy way to do something, when you know nothing". And it works, as anybody and his dog can start with Arduino and if interested, he can go more far on his own, or he can stick with easy and have fun anyway.


Cheap medium range wireless communication with a linux PC I have a project that's currently using Arduino Uno with a cheap class-2 bluetooth serial adapter from ebay to send and receive data and control a LED light strip.

However, it struggles to establish connection at distances more than couple meters. I'd like to expand that range a bit - 15 meters with two load-bearing walls in the way. Bandwidth requirements are next to none - it should just move couple integers around.

Any suggestions how to do that on the cheap? From what I've seen, class-1 bluetooth adapters go for ~60$, two xbee modules + usb adapter end up costing even more, and wifi solutions seem to reside in the same price range. At that price point, it seems better to get a raspberry pi, wifi dongle and a couple beers for the software re-write. Am I overlooking some solution?

Since one end is a PC I would look into a Wifi shield for the arduino. That way you would not need any extra hardware on the PC side.

You can get a Wifi shield for less than 2 xbee modules. But using wifi will require changes to your code since it won't be using the serial port for communication.

Another wireless option that I have no personal experience with is NRF2401 modules -- you can get them dirt cheap on ebay (caveat emptor) but they use an SPI interface so you can't directly interface with them directly on the PC side.

Be aware that depending on the LED strip you may not be able to drive it directly from a raspberry pi.  For example WS2811 driven LEDs (AKA adafruit NeoPixels) need precise timing that you can't get (or is tricky to get) with the raspberry pi.


Unsure if my NEMA 14 stepper motor wiring is correct So I'm pretty brand new to Arduino's in general so I do apologize if its a simple mistake. But basically I'm trying to use the <Stepper.h> library to control my NEMA 14 motor on an arduino with a CNC shield and a A4988 driver. Specifically at this moment I am testing out this code:
/*
 Stepper Motor Control - one step at a time

 This program drives a unipolar or bipolar stepper motor.
 The motor is attached to digital pins 8 - 11 of the Arduino.

 The motor will step one step at a time, very slowly.  You can use this to
 test that you've got the four wires of your stepper wired to the correct
 pins. If wired correctly, all steps should be in the same direction.

 Use this also to count the number of steps per revolution of your motor,
 if you don't know it.  Then plug that number into the oneRevolution
 example to see if you got it right.

 Created 30 Nov. 2009
 by Tom Igoe

 */

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken

void setup() {
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one step:
  myStepper.step(1);
  Serial.print("steps:");
  Serial.println(stepCount);
  stepCount++;
  delay(500);
}

Now unfortunately when I run this code I can hear the motor whirring, but it doesn't revolve. I'm guessing that either I wired the motor incorrectly, or because I'm using a CNC shield the pins in the code should be different. Also, I've checked the voltage going into the driver in accordance with this website. I've also attached pictures below of my setup to just to make everything clear:

Picture of CNC shield atop Arduino board with wires connected as follows:

Picture of Stepper motor I'm using:

Specifications of the NEMA 14 motor I'm using:
Can be seen here

I'm sorry for the convoluted post but I am kind've stuck so any help would be greatly appreciated and if there's any more info needed to help clarify my problem I will update the post or reply to your comments. Thanks!

I would first check with a multimeter which pins from the the shield have voltage. Draw on a piece of paper the sequence of pin activated by the driver and check your motor connection. Probably you have just inverted two wires, this would also explain the whirring sound.


How to utilize SPI Serial bus on a ATSAMD21G18? Like the title suggests, I have a ATSAMD21G18 microcontroller that I want to interface with a LTC6803-4 chip, but I'm not sure how to set up the SPI bus on the microcontroller, and the datasheet proved too confusing for me to understand.

Use the SPI API provided by Arduino (https://www.arduino.cc/en/Tutorial/SPITransaction) and the command format that the chip wants you to use based on the datasheet. Here's a bit of example code for SPI transaction. Though untested, it's what I understood from reading the datasheet. Written for an Adafruit Feather M0 express (uses SAMD21G18 MCU). For pinout see https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/adafruit2-pinouts#logic-pins-2-8.

Also note that Analog Devices does provide Arduino-Code for similiar devices like LTC6803-2 but not for the -4. Still, you can look how they implemented a driver. See here

#include <Arduino.h>
#include <SPI.h>

/* pin setup */
int chip_select_pin = PIN_A2;
/* SPI pins labeled "SCK" "MO" "MI" on the Adafruit Feather M0 express board
 * are used implicitly.
 * PIN_SPI_MISO (22),  PIN_SPI_MOSI(23), PIN_SPI_SCK(24),
 * */

#define LTC6803_4_MAX_SCLK_FREQ 1000000
#define LTC6803_4_USED_SCLK_FREQ (LTC6803_4_MAX_SCLK_FREQ/2)

SPISettings settings(LTC6803_4_USED_SCLK_FREQ, BitOrder::MSBFIRST, SPI_MODE3);

void start_voltage_adc_conversion(){
    SPI.beginTransaction(settings);
    digitalWrite(chip_select_pin, LOW);
    //STCVAD
    //Start Cell Voltage ADC Conversions and Poll Status, with Discharge Permitted
    uint8_t tranfer_buf[2] = {
            0x10, //CODE
            0xB0 //PEC
    };
    SPI.transfer(tranfer_buf, 2);
    //wait for conversion, just a static time. at least 12 milliseconds.
    delay(20);
    digitalWrite(chip_select_pin, HIGH);
    SPI.endTransaction();
}

void read_voltages_1_to_4(){
    //trigger voltage conversion
    start_voltage_adc_conversion();

    SPI.beginTransaction(settings);
    digitalWrite(chip_select_pin, LOW);
    //transfer buffer must have 2 bytes for command
    //and 6 bytes for response (four 12-bit ADC values encoded in 6 registers CVR00..CVR05)
    //plus 1 byte for PEC from chip
    //Read Cell Voltages 1-4, "RDCVA", page 22
    uint8_t tranfer_buf[2 + 6 + 1] = {
            0x06, //CODE
            0xD2 //PEC
    };
    SPI.transfer(tranfer_buf, 9);
    digitalWrite(chip_select_pin, HIGH);
    SPI.endTransaction();

    //recover 12-bit ADC value from C1V[0]..C1V[11] from register values CVR00 and CVR01
    //see datasheet page 24
    uint16_t adc_cell_1 = tranfer_buf[2] | ((tranfer_buf[3] & 0B1111) << 8);
    //adc value to voltage conversion according to page 15
    float voltage_cell_1_millivolt = ((int)adc_cell_1 - 512) * 1.5f ;
    Serial.print("Cell voltage 1: ");
    //print with 5 digits accuracy
    Serial.print(voltage_cell_1_millivolt, 5);
    Serial.println(" mV");
}

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

void loop() {
    read_voltages_1_to_4();
    delay(2000);
}


Problem on Arduino Interrupt and RTC I am doing an experiment. In this experiment I want to start the RTC by presing the external Push Button which is connected with Aquino's pin 2 and take varites of action according to Time. For interrupt I have made a ISR and in this interrupt I wrote my main logic. But this things is not working.
The schematics is

and The code is

`include <Wire.h>
#include "RTClib.h"
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 9);

RTC_DS1307 rtc;
int k = 0;
int led =13;
int pin =2;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
 lcd.begin(16, 2);
 rtc.begin();
 Serial.begin(11520);
 pinMode(led,OUTPUT);
 pinMode(pin,INPUT);
 attachInterrupt(0, Time  , LOW);
  // Print a message to the LCD.
  if (! rtc.begin()) {
    lcd.print("hello, world!");
    while (1);
}

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }
}
void loop()
{}

void Time()
   {
    {DateTime now = rtc.now();
    lcd.setCursor(0, 0);
    lcd.print(now.year(), DEC);
    lcd.print("/");
    lcd.print(now.month(), DEC);
    lcd.print("/");
    lcd.print(now.day(), DEC);
    lcd.print(" ");
    lcd.print(daysOfTheWeek[now.dayOfTheWeek()]);
    int c = now.second();
    lcd.setCursor(0, 1);
    lcd.print(c);
    if(c==58)
      {
        k=k+1;
        lcd.setCursor(5, 1);
        lcd.print(k);
        if(k==4)
          {
            digitalWrite(led,HIGH);
            k=0;
          }
     }

    }}`

please help me.

Well, for example Arduino's delay needs interrupts to be working and as you may not know it's disabled inside of ISR handler.

Never ever use anything like while (1), delay(1000) and so on inside of ISR! And also do not reenable interrupts either! Set a simple volatile flag and use it inside of loop function instead.

Basically something like this:

constexpr int8_t button = 2;
volatile bool      flag = false;

void setFlag() {
  flag = true;
}

void setup() {
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), &setFlag, FALLING);
}

void loop() {
  if (flag) {
    // it's running, you can do something here

    // and you can reset the flag here either
  }
  //delay(100); // if needed
}


NeoPixel Blink/Glitch I'm having this weird effect where my NeoPixel will blink/glitch after every cycle of a fading sketch. I'm not certain whether the issue is hardware or in my code. The blinking only occurs during the if statement portion of the code and not during the else statement which blinks red. I have tried multiple sources of power, 5V 2amp, 9V 1 amp, 12V 1amp and a Mac Usb and the problem persists on each power supply.

Any suggestions or ideas would be greatly appreciated.

#include <Adafruit_NeoPixel.h>
#include <DistanceGP2Y0A21YK.h>

#define PIN 6
#define PIXEL 16

Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL, PIN, NEO_GRBW + NEO_KHZ800);

DistanceGP2Y0A21YK Dist;
int distance;
int R = 0;
int G = 0;
int B = 0;

void setup() {
  strip.begin();
  strip.show();
  strip.setBrightness(127);

  Serial.begin(9600);
  Dist.begin(A0);
}

void loop() {
  distance = Dist.getDistanceCentimeter();
  Serial.print("\nDistance in centimers: ");
  Serial.print(distance);
  delay(2); //make it readable

  if (distance > 10) {

    for (R && G && B; R < 150 && G < 150 && B < 150; R++ && G++ && B++) {
      for (int i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(R, G, B));
        strip.show();
        delay(1);
      }
      delay(2);
    }

    // fade off
    for (R && G && B; R > -1 && G > -1 && B > -1; R-- && G-- && B--) {
      for (int j = 0; j < strip.numPixels(); j++) {
        strip.setPixelColor(j, strip.Color(R, G, B));
        strip.show();
        delay(1);
      }
      delay(1);
    }

  } else {

    for (int j = 0; j < 256; j++) {
      for (int i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(255, 0, 0));
        strip.show();
      }
      delay (1);

      //blink off
      for (int j = 64; j > 0; j--) {
        for (int i = 0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, strip.Color(j, 0, 0));
          strip.show();
        }
        delay (2);
      }
    }
  }
}

for (int j = 0; j < 256; j++) {

  ...

  //blink off
  for (int j = 64; j > 0; j--) {
    ...

Notice that you are re-declaring the variable j.


Lifecycle hook in Arduino to know if Arduino is reset or powered down I am new to Arduino programming and I'm really fascinated with its working. Is there a way to know if an Arduino is getting switched off or being reset? Like a function would be called before the Arduino gets switched off.

I want to detect this event to preserve a value, where a user resets his Arduino, or switches it off. Is it possible?

EEPROM has a limit of 100,000 write/erase cycles, so we cant do more than that

You have 1k bytes of EEPROM and they survive a minimum of 100,000 writes. So that's 102,400,000 writes you could potentially do, if you are saving one byte. Even at one write a second that would be around 3 years.
However the EEPROM page size is 4 bytes, so that is actually 25,600,000 writes you could get away with (of 4 bytes at a time). Still, that is quite a lot of writes.
A while back I tested one of my chip's EEPROM and found that it greatly exceeded the 100,000 writes specified before it starting misreading the data back.
Also, if you refrain from writing if the value hasn't changed (hopefully that's a lot of the time?) then you could probably extend the life to 100 years.

Like a function would be called before the Arduino gets switched off.

No, that's impossible. How would it possibly know it is about to be switched off? Once it is switched off, functions are hardly going to be able to run.

Is there a way to know if an Arduino is getting switched off or being reset?

Once you hit Reset the processor starts again. It doesn't run any functions "just before" or "just after" being reset (using the original variables). That would mean that the reset doesn't actually reset it.

If you are designing some gadget that lets you configure it (eg. with a volume control) then simply save the new setting to EEPROM when it is changed. This is hardly going to happen 24 hours a day.


Getting the DS18B20 detected and temperature read I'm quite new with the electronics part of Arduino, but I thought that this was the basic way to get the DS18B20 temperature device hooked up. However, I can't detect it in my program using OneWire and DallasTemperature.

This is an image of my connections:

Basically my approach was like this:

Connect ground on ground on the DS18B20.
Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).
Between the 5V and the two yellow cables, I connected a 4.7K resistor.
Vdd on the DS18B20 is not connected to anything.

Anyone have any idea why this is not working as expected for me?

Thanks in advance!

Vdd on the DS18B20 is not connected to anything.

According to the datasheet:

  When the DS18B20 is used in parasite power mode, the VDD pin must be connected to ground

  Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).

That means port 2 would always be high, right?

According to Temperature Sensor DS18B20 this is the wiring for non-parasitic power:

If you want the two-wire version (parasitic power) it would be:


Communication between Arduino Uno and Mega I am working on a project which uses a set of sensors (HC-SR04). These sensors use pins 2 to 13 of the Arduino Uno. Here you can find the board:

.

I also want to add an MP3 shield (VS1053B) to it and it fills all the pins on Arduino. So I decided to add an Arduino Mega and add the sensors to it and use the Arduino Uno and MP3 shield. The problem is with connecting these two Arduinos. As I said the MP3 shield fills A4 and A5 pins too, so I can not use them to communicate with the Mega. What other options do I have?

You can multiplex the trigger line. With 3 pins you can address up to 8 sensors. If you multiplex the reply line as well (so you can abstract out the latency) you only need 2 additional pins for the actual trigger and reply.


home automation - What's a compact way to control a light switch with Arduino without interacting with high voltage? To be clear, this question is not about physically wiring into the light switch to control the lights - simply pressing on the switch from the outside. I apologize in advance if my electrical vocabulary isn't up to par - I'm very new to this.

I have been developing an Android app that allows me to control Particle Photon boards over the internet, and I have already installed a board that turns my computer on and off. However, I am researching ways to automate the lights (ceiling lights, not lamps) without interacting with high voltage. I have not been able to find any good information.

Does anybody have any advice?

you can glue an LED controlled by an MCU into the sensor hole of a dusk to dawn sensor. these are available in socket and outlet shapes, are UL certified, and require no messy wiring. I've been able to switch an outlet model by duct-taping an ESP8266's built-in LED against the window; can it get any simpler?

Here's a working example's parts, exploded for easy identification.

You can spot an inline socket-to-outlet adapter, a dusk-to-dawn sensor, a bulb, a cheap nodeMCU ESP8266 devboard, a short micro usb cable, a USB wall wort, and an RGB LED module attached to dupont wires. I'm wiling to bet anyone here can figure out how these pieces fit together to make a $10 "smart bulb". You can get most of these parts at the local home center, and everything shown on amazon/ebay.

Of course you won't get a lot of respect from EEs, but you will get the job done quickly and safely, and the opto-isolated controls work with any platform. I have cheaper/smaller build i've moved onto, but i still have several of these switch builds in-place for years and they work great.

I would recommend getting a dusk-to-dawn switch that is labeled as being compatible with LED bulbs; they tend to use a lower-"bleed" IGBT instead of the older/cheaper diac/triac combo which causes some low-energy bulbs to flicker when off.


Unexplainable int behavior in encoder/LED project I am trying to use a rotary encoder to cycle through the brightest versions of R, G & B. And it works! Red goes to blue just fine. Then G happens. For some reason, the int for green goes completely haywire. And it does this the same way on two Arduinos.

So my question is this: why would two, identically assigned variables treat ++ completely differently? After hours (and hours and hours) of looking, I'm completely out of possible answers.

#include <Encoder.h>
#include <FastLED.h>

/* Encoder */
Encoder myEnc(2, 3);
const int swPin = 4 ;
long oldPosition  = -999;

/* LEDs */
#define LED_PIN     7
#define NUM_LEDS    150
CRGB leds[NUM_LEDS];

/* RGB Loop */
volatile int cycle = 1;
volatile int brightness = 0;
volatile int r = 127;
volatile int g = 0;
volatile int b = 0;

void setup() {
  pinMode(swPin, INPUT);
  Serial.begin(9600);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
}

void loop() {
  // Read from rotary encoder.
  long newPosition = myEnc.read();

  if (newPosition != oldPosition) {
    oldPosition = newPosition;
    Serial.println(newPosition); /* Sends elsewhere */
  }

  /* Will eventually move this inside the above if
   * statement so the color shift is controlled by
   * a rotary encoder.  Down here for debugging.
   */
  delay(50);
  updateColor( );
}

void updateColor(  ) {

  Serial.println(" "); // For readability.

  if ( brightness >= 127 ) {
    brightness = 1;
    if ( cycle > 6 ) {
      cycle = 1;
    } else {
      cycle++;
    }
  } else {
    brightness++;
  }

  if ( cycle == 1) {
    b++;
  }
  else if ( cycle == 2) { /* rb --> b */
    r--;
  }
  else if ( cycle == 3) { /* b --> bg */
    g++;
  }
  else if ( cycle == 4) { /* bg --> g */
    b--;
  }
  else if ( cycle == 5) { /* g --> rg */
    r++;
  }
  else if ( cycle == 6) { /* g --> rg */
    g--;
  }
  else {
    Serial.print("==================== ");
  }

  /* Debugging */
  Serial.print("brightness:");
  Serial.print(brightness);
  Serial.print("   cycle:");
  Serial.print(cycle);
  Serial.print("   r:");
  Serial.print(r);
  Serial.print(" g:");
  Serial.print(g); // goes completely bonkers
  Serial.print(" b:");
  Serial.print(b);
  Serial.println(" ");

  for (int i = 0; i <= NUM_LEDS; i++) {
    leds[i].setRGB( r, g, b );
  }

  FastLED.show();

}

spits out the following in the serial monitor :

brightness:1   cycle:1   r:127 g:0 b:1

brightness:2   cycle:1   r:127 g:127 b:2

brightness:3   cycle:1   r:127 g:32639 b:3

brightness:4   cycle:1   r:127 g:32639 b:4

brightness:5   cycle:1   r:127 g:32639 b:5

brightness:6   cycle:1   r:127 g:32639 b:6

Red and blue are doing exactly what I want. Green is off on Mars.

Any/all help would be enormously appreciated.  Thanks in advance.

Here:

CRGB leds[NUM_LEDS];

you are defining an array of NUM_LEDS objects of the CRGB type.
Valid indices for this array range from 0 to NUM_LEDS-1.

Here:

for (int i = 0; i <= NUM_LEDS; i++) {
  leds[i].setRGB( r, g, b );
}

you are accessing the array elements at indices 0 to NUM_LEDS. The
last iteration is an out-of-bounds access, which is causing memory
corruption. You should instead write

for (int i = 0; i < NUM_LEDS; i++) ...


Multiplexing potentiometers Is it possible to have two rotary potentiometers read from a single analog input pin?

The analog input is 10 bits (0-1023), so each pot would have 5 bit precision (0-15).

Least significant bits for pot 1 and most significant bits for pot 2.

A SPI/I2C ADC IC (eg. MCP3008) is an option if this is not possible.

Edit:

The two pots do not need to be read at the same time.
It seems full 10 bit precision could be achieved if I use a digital pin to enable each pot before it is read.

There are a few ways of doing what you want.  One would be to use an analog multiplexer as in this answer: Expanding analog inputs to the Arduino

Another would be to use digital I/O pins to control the power and ground to the potentiometers.  Note that both sides of the pot need to be controlled, not just one, since any connection of one will interfere with the other.

So you will need four IO pins - one for the +5v and one for the GND of each potentiometer.

In this example set D3 to OUTPUT and HIGH, D4 to OUTPUT and LOW, and D5 and D6 both to INPUT.  You will now be reading from the top pot.

Then change D3 and D4 to both be INPUT, and D5 to be OUTPUT and HIGH and D6 to be OUTPUT and LOW.  You will then be reading from the bottom pot.

A bit wasteful of IO pins though.


Printing elements of char array from PROGMEM Given:

const char* PROGMEM names[] = {"Foo","Bar"};
Serial.print(names[0]);

I get garbage output. Is there some function that will print the string from PROGMEM? E.G.:

Serial.print(<function name>(names[0]);

Among many others, check out pgmspace.h utilities at
AVR-libc


Multiple Wire.write() not working for Arduino Nano I2C Code for Master
#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
}

void loop()
{
    Wire.beginTransmission(9);

    Wire.write('c');
    Serial.println('c');
    Wire.write('a');
    Serial.println('a');
    Wire.endTransmission();
}

In my case Wire.write('c') is performing the task which is assigned to 'c' in slave board.
Then its printing 'c' in serial monitor as intended.
But, Wire.write('a') line is being neglected and nothing happens on slave board.  But again, it's printing 'a' in serial monitor as per code.
Why is that Wire.write('a'); is neglected? Both boards are Arduino Nano.
Code for Slave
#include <Wire.h>
#define RED 8
#define GREEN 10
int x = 0;

void setup() {
  pinMode (RED, OUTPUT);
  pinMode (GREEN, OUTPUT);
  Wire.begin(9);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
}

void loop() {
    if (x == 'a') {
        digitalWrite(RED, HIGH);
        digitalWrite(GREEN, LOW);
    }
    if (x == 'b') {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, HIGH);
    }
    if (x == 'c') {
        digitalWrite(RED, HIGH);
        digitalWrite(GREEN, HIGH);
    }
    if (x == 'd') {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
    }
}

Important information: Wire.write() does NOT send anything over the I2C lines. It just puts the data into the libraries internal buffer. The actual transmission is then done by Wire.endTransmission().
I2C is packaged transmission protocol. That means, that the transmission is done in confined data packages. In your master code you are calling Wire.write() two times before Wire.endTransmission(). That means you are sending 1 package with 2 data bytes in it.
Now for your slave code: You are using a callback function for the onReceive event. This callback function is called once per transmission. In there you can read all the data of that transmission. After that the data is thrown away (I think actually it gets deleted, when a new transmission is received). You are only reading once with Wire.read(). So you only ever read the first byte of every transmission, which is always the letter 'c'.
What to do know? This depends on how you want the code to behave. Since you are setting 2 LEDs based on the received byte it would be better to only send 1 byte transmissions. For that, you can change your master code. For example like this:
#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
}

void loop()
{
    // Send the command c
    Wire.beginTransmission(9);
    Wire.write('c');
    Wire.endTransmission();

    // Wait 1s, so that we can see the LEDs state accordingly
    delay(1000);

    // Send command a
    Wire.beginTransmission(9);
    Wire.write('a');
    Wire.endTransmission();

    // Wait 1s, so that we can see the LEDs state accordingly
    delay(1000);
}

This code will change between 'c' and 'a' every second. You need a delay there to actually see the LEDs light up. Otherwise they would change too fast for you to see it.
Note: Actually you need to declare the variable x as volatile, because the onReceive callback is called from an ISR. With that keyword you are telling the compiler, that x can change at any time (by the ISR of the corresponding I2C interrupt). It might be, that your current code works, because the compiler was smart enough to see that, but in general you should always use volatile with every variable, that can change in an ISR. Declaration then looks like this:
volatile int x = 0;

And to handle the ISR data really correct, you would need to make the usage atomic, because the ISR can happen in the middle of the comparison for the if statements. An int is two bytes, so the first byte might be updated and the second byte not. That would corrupt your data. There are two ways to handle that in your case:

Make the reading of x atomic: Normally one would turn of the interrupts, read the volatile variables into local variables (as a copy) and then turn the interrupts on again. That way the interrupt cannot corrupt the data in the variable during reading. The further calculation/comparison would then be done with the local variable.

Use a single byte as volatile data: The described problem does not apply to variables, which only use 1 byte (since on the 8bit Arduinos like the Nano the reading of a single byte cannot be interrupted). So just make x of type char (or uint8_t or byte).

You should use the second option.


AVR ATmega328p-pu operating circuit? I used to work with PIC micro-controller so i know what it needs to work from operating circuit to crystal oscillators needed and other components to power it up , my question here where can i find the operating circuit for ATmega32p-pu and other AVR models . or all i need to do is to give it +5v and gnd and it will work ?

You're looking for this I think? How to set up an Arduino on a breadboard.


How can I best control various high power LEDs without using PWM I want to be able to dim various high powered (20mA) LEDs in an array (8X12 LEDs). I do not need individual control, but would like to be able to dim each row (or two rows together) so that I can create gradients.

An important caveat is that I can't use pulse width modulation (PWM) as there should be no flashing whatsoever, even if it is invisible to humans.

How can I best achieve this?
(I do not care about energy efficiency)

The fist thing I found which seemed to be the right solution in the beginning is using digital potentiometers as explained in this tutorial. However they only support low currents so I can't use one channel for 8 or 16 LEDs.
Maybe I could use various digipots in parallel with one Arduino, each powering 1 LED per channel? But that sounds overcomplicated and a nightmare to wire up. Is there a more elegant solution?

The figure below illustrates a method of current control.  It shows four LEDs in a 2x2 arrangement; one  would adapt the number of LEDs in series or parallel in accord with how one's array is wired, what voltages are available, LED current requirements, transistor power limitations, etc. [Edit: See transistor-power example calculation at end.]

Each separately-controlled group of LEDs would need one such circuit.  Each circuit needs one control voltage (eg, from a DAC or a digital potentiometer voltage divider circuit) and needs one transistor per series chain.

Circuit Operation:

Suppose the following conditions hold.

Q1 and Q2 are equivalent transistors and Vbe is 0.7 V typ. (one diode drop)
D1, D2, D3, D4 are equivalent LEDs
Resistors R1, R2 are small and equal (eg 1–30Ω)
V1 is some fixed DC voltage, eg about 1 V
V > 2*Vf + Vbe + VR where Vf = typical forward voltage of D1...4

Under these conditions, V1 will drive current into the bases of Q1 and Q2, causing transistor-amplified current to flow through R1 and R2 and maintain the condition V1 = Vbe + VR1 = Vbe + VR2.

Here is a concrete example:  Suppose we want 23 mA through each LED and that R1=R2=17Ω. VR = IR = 0.023 mA · 17 Ω = 0.391 V.  If Vbe is about 0.7 V, then we set V1 = 0.7 + 0.391 V or about 1.09 V to get 23 mA through each LED.  More generally, to get current I through the LEDs we solve V1 = Vbe + VR = 0.7 + IR = 0.7 + I·17.

Base current:

The amount of current required from the V1 voltage source depends on transistor hFE or β.
Eg, if β is about 100 and ILED is 20 mA then each transistor will need about 20/100 mA or about 200 μA of base drive.  This amount of current probably could be delivered by a voltage divider based on an AD5206 (the digital potentiometer chip that's used in the SPIDigitalPot tutorial mentioned in the question).

Power Dissipation:

The AD5206 digital potentiometer datasheet shows an absolute maximum rating for Package Power Dissipation of  (TJMAX-TA)/θJA.  If ambient TA is 25℃ and θJA is 70°C/W (as for a SOIC package) this gives (150-25)/70 = 1.8 W max package power.  However, it would be reasonable to limit dissipation to under half a watt.  In the 10 KΩ version of the AD5206, that means a little less than 2.9 mA maximum per channel.  [I = √(0.5 W /(6 channels * 10000Ω)).]  If several low-beta transistors are used to drive several strings of LEDs, 2.8 mA might be marginal.

Voltage-divider Linearity:

Only a small fraction of the current through a voltage divider can be drawn off without upsetting the division ratio.  A unity gain buffer amplifier [as in the following figure] can be used to increase linearity of voltage-divider output by providing a high-impedance connection to the divider.

(In the figure above, R1 and R2 are not related to R1 and R2 of the previous figure.  Here, R2 represents a digitally-variable resistor.  Choose R1 and R3 so that V1's range is from slightly below Vbe to slightly above  Vbe + ImaxR, where Imax is the maximum LED current desired.  For example: Suppose V=5 V, that R2's total resistance is 10 KΩ, that R is 15Ω, that Vbe is 0.7 V, and Imax is 25 mA.  Let RT = R1+R2+R3.  Now R3/RT = Vbe/V = 0.7/5 = 0.14, and R1/RT = (V - Vbe - ImaxR)/V = (5 - 0.7 - 0.025·15)/5 = 3.925/5 = 0.785.  Thus R1+R3 = 0.925·RT, whence 0.075·RT = R2 = 10 KΩ, giving RT = 133 KΩ, R1 = 105 KΩ, and R3 = 19 KΩ.  With these R1 and R2 values, each digital pot step should give a change in LED current of 25/256 mA, or about 98 μA.)

[Edit:  When V1 is set to less than VBE, no current will flow through the LEDs.  That is, to turn off the controlled LEDs, set V1 to VBE or less.]

PWM with RC filter:

It may be worthwhile to experiment with using a PWM-driven low pass RC filter to supply V1, possibly avoiding need for buffer amplifiers and digital potentiometers.  See eg “Arduino’s AnalogWrite – Converting PWM to a Voltage”
by Scott Daniels at provideyourown.com, and also see the filter-calculation page it refers to.  You might need an oscilloscope to verify the design and its quality of results, and might need to use several RC filter stages in a row to adequately filter out ripple, but it can be done, at the cost of slower response to control changes.

Transistor-power example calculations:

Letting  VCE, ICE, VBE, and IBE represent collector-to-emitter and base-to-emitter voltages and currents, transistor power dissipation is VCE·ICE+VBE·IBE.  Because VBE·IBE is likely to be sub-milliwatt, we ignore it in following, taking P ≅ VCE·ICE.

In the LED-driving circuit,  VCE = V – VLEDs – Vsense, where VLEDs is the series voltage across the chain of LEDs the transistor controls, and Vsense is the voltage across the sense resistor (ie, across R1 or R2 in the top figure).

In general, it is a good idea to keep Vsense small (under a volt) to allow a wider compliance range – ie, so that LED current is the same over a wider range of variation of supply voltage V.  Thus, the approximation  VCE ≅ V – VLEDs is reasonable.

Here is a concrete example: Suppose we have eight LEDs in series, and they are white LEDs with about 3.6 V forward drop at 20 mA. [LEDs of different colors may have different drops; eg see LED color chart at oksolar.com.]  Then VLEDs = 8·3.6 V = 28.8 V. We need V(BR)CEO > V > VLEDs + VBE + Vsense, where  V(BR)CEO = collector-emitter breakdown voltage (which is 40 V min. for 2N3904 or 2N2222).  Allowing a volt for Vsense and 0.7 V for VBE we have V > 28.8 + 0.7 + 1 = 30.5 V.  Let's suppose V=32 V.  Then P < (32–28.8)·0.020 W = 64 mW.  Thus a small general purpose NPN transistor will work, for example a 2N3904 (rated at 350 mW to 1 W, depending on package, before derating for ambient and heatsinking) or a 2N2222 (similarly rated).

For a second example, suppose VLEDs = 8·1.7 V = 13.6 V (for, eg, eight infrared LEDs at 50 mA) and V=32 V.  Then P ≅  (32–13.6)·0.050 W = 920 mW, so a larger (and heatsinked) transistor would be needed.  Or, V could be decreased, say to 16 V, giving  P ≅  (16–13.6)·0.050 W = 120 mW, allowing use of a small transistor.

For a third example, suppose eight LEDs are paralleled (rather than seriesed), that VLEDs = 2.0 V at 20 mA, that Vsense is about 0.4 V at desired operating point, and that V=5 V.  The transistor will need to drop 5-2-0.4 V = 2.6 V at 160 mA, which is 416 mW, probably large enough to require a heatsink.  [Note:  if LEDs are placed in parallel and driven by a single transistor, some of them probably will be dimmer than others; “current hogging” may occur in some of the LEDs, making them brighter than the others.  However, many cheap flashlights connect LEDs in parallel without individual current control.]


How to set SPI speed for ATmega1284P? I am using MightyCore and platformio. My config file looks like this
My fuses are set as:
E:FD
H:D6
L:8F

I have controller running at 16 MHz and SCK frequency is 8 MHz.
My display is showing white color and that is it. I know to make it function properly I have to use 1 MHz SPI clocking.
If I program CKDIV8 fuse my controller doesn't start. I dunno why, kind of black magic going on there for me. My lack of knowledge is not helpful there.
I tried to use the following tricks:
Setting SPI speed using TFT library
// earlier in main.cpp
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
// later in setup()
tft.setSPISpeed(1000000); // has no effect on SCK

Trying to set it directly via SPI class instance:
// in setup()
SPI.setClockDivider(SPI_CLOCK_DIV128); // no effect

Or statically:
// in setup()
SPIClass::setClockDivider(SPI_CLOCK_DIV128); // still no effect

Also I tried to pass DEFAULT_SPI_FREQ build flag with frequency preset.
I ran out of ideas.
Schematic is here:

Per this issue setSPISpeed has to be made after initR like this:
tft.initR(INITR_BLACKTAB);
tft.setSPISpeed(1000000);


Can only write 5V or 0V, not something in between I'm working on a bigger project, and needs to give out a voltages between 0 and 5V. I've written this code:

int ledPin = 12;      // LED connected to digital pin

void setup(){
pinMode(ledPin, OUTPUT);   // sets the pin as output
}

void loop(){
analogWrite(ledPin, 255);
delay(2000);
analogWrite(ledPin, 0);
delay(2000);
analogWrite(ledPin, 127);
delay(2000);
analogWrite(ledPin, 128);
delay(2000);
}

If I've understood it right, this should first give about 5V, then 0V, then 2.5V and againg 2.5V. However my voltmeter only reads 5V and 0V, 2 seconds at each. I've attached my voltmeter to pin 12 and ground. The arduino board is also grounded.

The PWM pins output a square wave from 0 to 5V. If you want something more like a DC level, then run the signal thru a Resistor-Capacitor (RC) Lowpass filter.
1K and 10uF should work well to smooth the squarewave.
http://sim.okawa-denshi.jp/en/CRtool.php

On an Uno, pins 3,5,6,9,10,11 are the PWM pins and output at a frequency of ~ 490 Hz or 980 Hz, with a duty cycle from 1 to 254. 0 is full off, 255 full on.


Arduino Nano and SIM300 module for http calls for location I am new to Arduino and SIM300/900 world. But I see that there is a possibility of building a vehicle tracker (approximate locality since I will use GPRS network location) using just these 2 boards.

My question is, is my assumption correct ? Can I build a vehicle tracker using just Arduino Nano and SIM300 mobule ? Is there a board that has both of them on one board so that I dont have to buy them separately ? Cost is a major factor on the decision.

Not really.

Module can read the cell ID by below command. However, only phone company has the list of cell ID and their location. This information is only accurate to serving range of a cell, mostly in range of, 0.1 to 15km, from very dense city to country

Module can also read network ID and know, from public information, the country and network operator name.

Example taken from web:

AT+CREG?

This should give you a result like:

+CREG: 2,1,"1030","639E"

Working through the 4 returned values, the "2" reflects the
current "+CREG" setting (2 means "Enables unexpected network
registration and location information messages"), "1" indicates
that the phone is registered with the network, "1030" is the
Location Area Code (LAC) in hex (4144 decimal), and "639E" is the
CellID (CI) in hex (25502 decimal).


IR not working on Attiny85 After countless attemps on making this thing work i'm not sure what the hell is going on. First of all you can't use the normal IR library because Attiny85 is crap and due to timer isses it wont work. So basicaly you need just the specific part which gets the data from the remote and thats all.
This is what i did but i failed badly again.
This time i used the simplest possible code which works perfectly on the Arduino UNO but it wont do anything on the Attiny85
The code
int irPin     = 4;
int tipPin    = 3;
int start_bit = 2200;    //Start bit threshold (Microseconds)
int bin_1     = 1000;    //Binary 1 threshold (Microseconds)
int bin_0     = 400;     //Binary 0 threshold (Microseconds)

boolean state = 0x0;

void setup() {
   pinMode(tipPin, OUTPUT);
   pinMode(irPin, INPUT);
   //Serial.begin(9600);
   //Serial.println("IR/Serial Initialized: ");
}

void loop() {
   int key = getIRKey();   //Fetch the key
   //Serial.println(key);
   if (key != 0) {
     state != state;
     digitalWrite(tipPin, state);
   }
   delay(400);    // avoid double key logging (adjustable)
}

int getIRKey() {
  int data[12];
  int i;

while(pulseIn(irPin, LOW) < start_bit); //Wait for a start bit

for(i = 0 ; i < 11 ; i++)
  data[i] = pulseIn(irPin, LOW);      //Start measuring bits, I only want   low pulses

  for(i = 0 ; i < 11 ; i++)             //Parse them
  {
    if(data[i] > bin_1)                 //is it a 1?
data[i] = 1;
else if(data[i] > bin_0)            //is it a 0?
data[i] = 0;
else
return -1;                        //Flag the data as invalid; I don't know what it is! Return -1 on invalid data
  }

  int result = 0;
  for(i = 0 ; i < 11 ; i++)             //Convert data bits to integer
    if(data[i] == 1) result |= (1<<i);

  return result;                        //Return key number
}

The ouput values are 3-digit numbers which work OK and i'm not even checking the value here. Just if something came in. And it doesn't bloody work!!!!
Stuff i've already checked

The circuit
If the pin works
If the timers are set correctly
Using adafruits library
Changing every possible core
If the receiver works
The wiring

If you are trying to toggle the LED when a signal comes in, then there is a glitch in the code and I have no idea how the UNO worked for you as I tried and it only spat out Serial, but didn't do anything with the LED.

Try changing this line of code:

state != state;

to

state = !state

you are not actually toggling the LED state with the other line, but instead doing a logical not equal to which won't do what you want.


Curious: What would happen if you connect 5V and GND port directly with a wire Has anyone ever accidentally or inadvertently connected connected the supply port with the ground port with a wire?

Does Arduino provide internal safety to prevent the circuit board from shorting out?

There is some protection.

When powered from the USB port, the UNO has a 0.5 A fuse.  This is a self resetting fuse that will trip when the current is high, and reset when it cools back down.  These fuses are great for peripherals that might be exposed to occasional "oops".  See the data sheet for more details of the part on the UNO.

When powered from the PWRIN plug, the voltage regulator provides some protection.  The device on the UNO contains over current and over temperature protection, which is common for regulators such as this.  The device will get very hot, and the protection will activate to limit the current (see datasheet for details).  By design, the regulator chip should protect itself from being destroyed.

So to first order, if you by mistake connect the +5 on the header to GND, all that will happen is Vcc will be reduced to near zero Volts.

The caveat is that a small spark can be generated when you make this short to ground, especially if you have a bunch of capacitors on Vcc.  That spark may cause a voltage transient that could damage a pin.


ESP8266 Missing data from Serial I'm trying to read all the available access points nearby with an ESP8266 module.

Whenever I try to read all the available data from the ESP module and write it to the Monitor Serial it truncates text. Text often also a bit messed up.

I'm using an Arduino Uno with the following scheme (I'm using pins 2 & 3 NOT 1 & 0):

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

  esp8266.begin(115200);
}

void loop() {
  while(esp8266.available()) {
     Serial.write(esp8266.read());
  }

  while(Serial.available()) {
    esp8266.write(Serial.read());
  }
}

The code prints something like the following:

AT+CWLAP

+CWLAP:(3,#SBanaan",-73,"4c:09:d4:d5:d6:f2",1,,2,0)
+CWLAP:(3,"UPC24923"CH7"0,L5-:d6Ai0:,
,,f5
44"f"CZ7f1
4-"6:0:4-95
,5-3d0

For SoftwareSerial, at 115200 bps data rate is not going to be reliable. Try 9600 bps.


Increasing the numbers of I/O pins on Arduino Uno I want to make a game of Tic-tac-toe using an Arduino, LEDs and bouncy buttons. Hence I need nine inputs and nine outputs. But you see that an Arduino only has 13 I/O pins. So is there a way I can use the analog pins or a way to reduce the number of I/O pins using an ingenious way?

Yes, just use the analog pins. The analog pins are both analog inputs and digital I/O pins. The functions happen to be shared on the pins, in the same way that the interrupt pins are shared with digital I/O, the TX and RX pins are shared with digital I/O and the SPI pins are shared with digital I/O.

Every I/O pin (analog or digital, etc.) can be used as digital I/O.

You can also reduce your required number of I/O pins by using a technique known as multiplexing.

For instance, to read nine buttons you could have them arranged (as in Tic-tac-toe) in three rows of three buttons. You then have three I/O pins for the columns and three I/O pins for the rows - that's just six I/O pins for nine buttons.

The technique is widely used for keypads, but they are just buttons, so the same technique can be applied to any buttons.

The Matrix Keypad how-to

The same can go for LEDs. There are various specialist LED multiplexing techniques that allow for many LEDs to be driven from just a handful of I/O pins.

How to Multiplex an LED Grid... (YouTube)
Charlieplex Library for Arduino


Serial Read Data Loss With Arduino Nano I am trying to use Serial reading from a python serial code (which is running on my Jetson Nano) in my project, but in some loop in my code, my data is receiving wrong.

I use Serial.readBytesUntil() function for interrupt-like reading.
I use standart blue mini-USB cable for communication.
My Arduino Nano also connected a nRF24L01 module with SPI.
Baudrate is 9600 for both devices. I tried 115200 but there is no difference.
The data loss is about %10 of all loops with both test codes (image-1, image-2).
There is no positive difference when I use RX/TX pins on both boards with level shifter.
When I use the test code in my main code with USB connection, the data loss increases %50 of all loops. But Arduino serial monitor is fine like image-3.
When I use the test code in my main code with RX/TX pins, Arduino serial monitor looks like image-4 and Arduino IDE gives error like image-5.

Here is my receiver test code on my Arduino Nano.

void setup() {

  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  while (!Serial) {}

}

void loop() {
  char buffer[4];
  int deger = 0;
  if (Serial.available() > 0) {
    int size = Serial.readBytesUntil('\n', buffer, 4);

    if (size == 4) {
      Serial.print("deger: ");
      Serial.write(buffer);
      Serial.print("  size: ");
      Serial.print(size);

      // Bytes to integer
      deger = (buffer[1] - 48) * 100 + (int(buffer[2]) - 48) * 10 + (buffer[3] - 48);
      if (buffer[0] == '1') {
        deger = -1*deger; }

      Serial.print(" Sayi: ");
      Serial.println(deger);
      }

    if (deger < 0) {
      digitalWrite(LED_BUILTIN, HIGH);
    }
    else {
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
}

And the python serial transmitter test code.

import serial

ser = serial.Serial('/dev/ttyUSB0',baudrate=9600,timeout=10)
while True:
    hata = -58

    if hata > 0:
        hata = str(hata)
        if len(hata) == 2:
            hata = '00' + hata
        elif len(hata) == 1:
            hata = '000' + hata
        else:
                hata = '0' + hata    #Pozitive, Added 0
    elif hata < 0:
        hata = -1 * hata
        hata = str(hata)
        if len(hata) == 2:
            hata = '10' + hata
        elif len(hata) == 1:
            hata = '100' + hata
        else:
            hata = '1' + hata    #Negative, Added 1
    else:
        hata = str(hata)
        hata = '000' + hata

    # For every loop, sends 4 character and "\n"  Example: 1058\n
    gonder = hata + '\n'       # For readBytesUntil function
    ser.write(gonder.encode('utf-8'))
    print(gonder.encode('utf-8'))

image-1: Arduino test code serial monitor screenshot

image-2: Python test code serial terminal screenshot

image-3: Arduino main project code monitor with USB cable screenshot

image-4: Arduino main project code monitor with RX/TX pins on GPIO screenshot

image-5: Arduino main project code IDE error

So, what did i do wrong?
Thank you!

You are overflowing your buffer, and also allowing garbage reads.

First you need 5 bytes for your buffer not 4, and you need to ensure it is zeroed out before using it. This is because you are treating it like a C string, which means it must b zero terminated.

Secondly your use of Serial.readBytesUntil() is flawed.  From the manual:

  The function terminates (checks being done in this order) if the determined length has been read, if it times out (see Serial.setTimeout()), or if the terminator character is detected (in which case the function returns the characters up to the last character before the supplied terminator).

You are sending 5 bytes (1058\n) but telling it to read up to 4. Which leaves the \n in the buffer. The next time through you read another 4 bytes, which gives you \n which is the terminating character.

If you must use readBytesUntil then you need to specify a buffer that is bigger than the whole string including the terminator so that the terminator always occurs before the maximum number of bytes read. Including the trailing zero you would thus need at least 6 bytes in your buffer, maybe a couple more "just in case" (one can never tell with Arduino API functions...)

So to roll it all up:

  char buffer[8]; // <- Bigger buffer
  memset(buffer, 0, 8); // <- Clear it out
  int deger = 0;
  if (Serial.available() > 0) {
    int size = Serial.readBytesUntil('\n', buffer, 7); // <- Tell it to read more leaving room for the terminating NULL
    ... etc ...

if (size == 4) {


Choosing right Sleep state I'm planning on building an LED clock, but I want it to be lit only when I press the POWER button on my remote control. Using an IR receiver, which Arduino sleep mode should I use to reduce the current consumption but still be able to receive this interrupt?

I recommend reading ArduinoSleepCode. Where it demonstrates placing the avr into a sleep state and using an interrupt to awake from the sleep state. In your case you can connect the output of your IR demodulator to the interrupt  pin, to simular awake.

Ken Shirriff's IR library allows you to use any pin as a receive input, so that you can use INT0 or 1 on D2 or D3. If you need to use a different pin, the Microtheron's github fork uses Pin Change interrupts. (I am not sure if stock sleep.h will awake from PCint, like int0 or 1 will, without tweek. Section 10.1 of data sheet says it will.)


how does an 8-bit AVR do 10-bit analog read? I am building a pH meter and having a real close look into the analog components, and reading the Arduino documentation for analogRead().
https://www.arduino.cc/en/Reference/AnalogRead

I see it says the Arduino, in my case an 8-bit AVR ATmega328 Arduino Uno,
yields a resolution between readings of: 5 volts / 1024 units or, .0049.

My question is whether that is accurate, or even possible. How can an 8-bit MCU provide a 10-bit analog read? how does that work?

Shouldn't the analog read be 2^8 or 256?

It can do a 10-bit reading quite simply - because the ADC is a 10-bit ADC.  The CPU register size doesn't dictate what it can communicate with, either internally or externally.  The only thing it dictates is how big a number it can cope with at any one time.  Because of this the 10-bit result of the ADC is spread across two registers - 2 bits in the "high" ADC result register, and 8 bits in the "low" ADC result register.