How can I connect multiple different sensors that uses the same pins? I'm doing a project on Arduino Uno and it requires me to connect 3 different sensors together: Waveshare 2.9 E-paper, MFRC522 RFID Reader and a ESP8266 wifi module. problem is, The e-paper and RFID uses the same multiple digital pins. How can I connect all of them together in a beardboard?

Edit:
The E-Paper uses:

e-paper 3V3 -> Arduino 3V3
e-paper GND -> Arduino GND
e-paper DIN -> Arduino D11
e-paper CLK -> Arduino D13
e-paper CS -> Arduino D10
e-paper DC -> Arduino D9
e-paper RST -> Arduino D8
e-paper BUSY -> Arduino D7

The rfid uses:

SDA --> Digital 10
SCK --> Digital 13
MOSI --> Digital 11
MISO --> Digital 12
IRQ --> unconnected
GND --> GND
RST --> Digital 9
3.3V -->3.3V

The wifi uses:

GND --> GND
VIN --> 3.3v
Enable --> 3.3V
TX --> RX
RX --> TX

I'm very new to electronics so i'm sorry if something does not make sense

I'm using library, code and instructions from this 3 websites:

E-paper ( Waveshare 2.9 E-paper): https://www.instructables.com/id/Getting-Started-With-E-Paper-Display-Modules/

RFID (MFRC522 RFID Reader): https://randomnerdtutorials.com/security-access-using-mfrc522-rfid-reader-with-arduino/

Wi-Fi (ESP8266 wifi module): https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e

Thanks!

You are lucky, the two devices creating the conflict both use the same pins because they both use the same interface, SPI to be precise, which allows to have multiple devices connected using different Chip Select pins, abbreviated as CS.

Of the two libraries, one allows to define the CS pin (RFID module), the other has it hardcoded (ePaper). So, when declaring your RFID library, you should use the constructor that allows to define the chip select pin:

void PCD_Init(byte chipSelectPin, byte resetPowerDownPin);

This means in your code you should use:

PCD_Init(6,8) rfid;

The above also implies one of your RFID connections must be changed: what was previously SDA --> Digital 10 is now going to be SDA --> Digital 6. Please note I picked pin 6 randomly among the pins that seem unused by your code, but any other unused pin will be a good choice, including analog pins.

BTW, the web page about the RFID module uses a pin naming which causes a lot of confusion because it mixes up SDA with MISO and MOSI: those names are used in two different types of interface, the former is called I2C or TWI, the latter SPI. On Arduino the two interfaces share a couple of pins, but they are very different in many different ways.

In your case both modules use SPI, which is good for you.


Receiving live astronomical coordinates on Arduino Mega using telnet and ESP8266 wifi module I'd like to receive on my arduino live coordinates of planets of solar system. Because there are already websites listing every planet coordinates, I thought it would be easier to just use a wifi module (in my case an ESP8266) and connect the arduino to one of these website.

I have the option of getting it from this website, but I have no idea how to do that.

The other way of doing it may be to connect to Horizon via their telnet server at this adress :telnet://horizons.jpl.nasa.gov:6775

Though I know how establish a connection with this server on my computer using Putty, I have no idea how to connect my arduino to it, execute commands, and, more importantly, get data (RA and DEC) of every solar system main objects.

This is my first time using Arduino wifi module, so I have no experience with it, and I don't know what it is capable of.

Thanks a lot for your attention,

Thomas

That telnet interface is an interactive service. Getting an Arduino to interact with it is not an easy task - certainly not a task for a beginner with no experience of network programming.

A much easier task is to scrape the website since that just returns text which you then need to search through a bit at a time looking for the information you need.


Good way to get automatically generated code into a sketch Situation:

Mac OS, Arduino IDE 1.5.6r2

I've got a sketch with several files, all classic .cpp and .h source and header files except the main sketch file. As the project goes more complex I started to generate code automatically by another program. Now I have hard times integrating the generated code it into my sketch. The arduino IDE seems to load the code on opening the sketch. After that, the source files aren't beeing checked for external changes by the IDE (as I would expect it from a real editor like vim). On top of that, when I verify my code the IDE seems to save the files from RAM into a temporary build directory ignoring the contents of the sketch directory further. So if I let my code generator change a source file while the sketch is opened in the IDE, the changes won't reach the build. I had to close the IDE and reopen it. The next thing I tried is to include my autogenerated file from an existing and opened code file inside the IDE. But the IDE ignores files, which aren't opened completely. Hence, the file is missing in the build directory.

Is there a trick to let the IDE take the code unknown to itself along into the build directory? Or how else can I deal with this situation? I don't want to close and open the IDE a hundred times a day.

According to the release notes starting with V1.5.2 of the IDE you can verify and upload from the command line.

You could use your favorite editor and then use the command line to do the arduino build/upload instead of the IDE.

See: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc

I have not used it so I can't say if it work well or not.


Circuit with buzzer not working :( so I have a circuit with a buzzer and a resistor:

This circuit should be working, but for some reason the buzzer doesn't sound. I pushed the buzzer into the breadboard as hard as I could, I put the + side to positive and the - side to negative but it still doesnt work :(. How can I fix this?

Quick curiosity question: When I was doing electricity in school, the teacher just called the buzzers 'buzzers' but when I started doing arduino I noticed that the arduino community seems to call them 'Piezo buzzers/piezo speakers'. Is there any significance in the word 'Piezo' and should I start referring to them as 'Piezo buzzers' myself?

There is two kinds of buzzers - active and passive

Passive buzzer means they can be operated by applying  just logic high to + and low to ground.

Digitalwrite function will do this job

Active buzzers needs pulses to make sound. Sound produced depends on the frequency.  Your buzzer might be a passive one. You can make a symphony by applying different frequencies..

'tone' function will help you for this


What minimal resistance should be between an input and output pin not to burn Arduino? So, I'd like to put a button between input and output pins to read when button is pressed. What minimal resistance should I add to the scheme not to burn Arduino when the button is pressed? Does this value depend on Arduino model?

Looking towards the high end of recommended (vs absolute maximum) current and considering Ohm's law at a 5v difference if two outputs are trying to drive each other to opposite values, you would probably get away with as little as 250 ohms.  But in most cases that would needlessly waste power, and in the case of multiple instance you could start totaling towards the limit of power supply current for the chip overall.

Typical values for external pull up resistors are more in the range of 1K-10K though higher is not uncommon - the internal pullup which you can optionally activate by setting the output state of an input pin high has a value of several tens of kilo ohms.  Lower values will consume more power, higher values may be less reliable in a noisy situation.


switching two relays without delay using millis I have an Arduino-uno and two relays. Each relay has two switch on for two seconds at regular intervals.
total loop time relay 1 and relay2 is 1800 seconds.
relay 1 - 2 on,360 off,2 on,600 off,2 on,430 off,2on,402 off.
relay 2 - 12 off, 2 on, 358 off, 2 on, 606 off, 2 on, 478 off, 2 on, 338 off.
Can somebody help me on a code for this please.

this is a typical application for Blink Without Delay


Unable to find arduino on device manager I have just got a new Arduino robot for Christmas and I have plugged my robot into my computer and I have read the instructions from the manual that the robot was provided with and told me to go to the device manager in the control panel and look under unknown devices, unfortunately I was unable to find it. However I looked under ports and I found that there were 3 ports, I eventually found out that if I took the Arduino plug in and out of my PC that port COM5 was the Arduino, the problem I am having now is to know how to get this port to recognise my Arduino

one error that always comes up when trying to upload the code onto COM5 is this:

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa1

This is what the arduino looks like

Link for where I brought the arduino kit from:
https://www.amazon.co.uk/ELEGOO-Tracking-Ultrasonic-Intelligent-Educational/dp/B01M6YHRJ4/ref=sr_1_1_sspa?keywords=elegoo+robot&qid=1577982862&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyVjVXTk9VMDlUTTg1JmVuY3J5cHRlZElkPUEwMjc4NjYwOEVGNEoxM1Y0QzIwJmVuY3J5cHRlZEFkSWQ9QTA4OTA1NzAzTTNBVFJMV09aVjJRJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==

This is what shows up on the arduino IDE when I select COM5 (which should be my arduino)

It seems your computer recognize the serial port of the Arduino device, but doesn't know how to 'talk to it'.

In most USB to TTL devices (that are included in Arduino and ESP8266 boards) you need to install their driver (like CH341 driver) BEFORE you plug in your device.

Please try to find/identify the 'USB to Serial' chip you have on the board, and install its drivers.

Good Luck!


Arithmetic mean for sensor This is the code I am currently using, but I want to add an arithmetic
mean to it. My goal is: when the pin A0 reads 5 values, I get the average
on which the fan and led will depend to be turned on and off, instead of
5 separate measurements.

int tempPin = A0;
int fan = 3;
int led = 8;
int temp;
int tempreal;
int tempMin = 20;
int tempMax = 30;

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

void loop()
{
  temp = analogRead(tempPin);
  tempreal = temp * 0.48828125;
  delay(1);
  if(tempreal > tempMax)
  {
    digitalWrite(fan,HIGH);
    digitalWrite(led,LOW);
    delay(1);
  }
  else if (tempreal < tempMin)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,HIGH);
    delay(1);
  }
  else if (tempreal >  tempMin && tempreal <  tempMax)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,LOW);
    delay(1);
  }
}

Edit by Edgar Bonet – The OP added in a comment to my answer:

“I tried [averaging consecutive readings]. It worked as you would expect
but it still does not solves my problem. My sensor is only getting right
values in the beginning of the scanning and then it varies. That is why
I wanted to make average value but it still does not work. Sadly I think
I wont be able to change sensor, but is there any other way to
camouflage this problem?”

Below is a screenshot showing both correct (✓) and incorrect (✗)
readings:

A fixed sampling window can be hard to manage, especially if you want the calculation to be recursive, for space and speed considerations.

You can achieve similar results via exponential smoothing.

Yn = (1−α) Yn−1 + α Xn

Where Yn is the smoothed outcome, Xn is the current measurement, and α is the weight.

With some thoughts, it can be done with integers and without loss of precision.

edit: i ran a comparison of exponential smoothing vs. (fixed window) moving average. The moving average algorithm was written to be recursive for maximal speed.

the sampled data is a simulated sine wave:

1000 * sin(2pi*n/100) + 100 * noise. n = 0..19999, and noise = -0.5...+0.5.

So snr = 1000 / 50 = 20:1, or about 5 digits. far worse than what you would encounter in a 10-bit adc.

the window I picked is 4.

As you can see, both approaches closely resemble each other. exponential smoothing uses much less ram and is also much faster. older data has lower weight on the output, something generally desirable in most applications.


Best way to protect a digital output? I am looking for a way to protect my Arduino's digital outputs from unwanted, outside voltages. My project uses about 20 different outputs, each connected to a wire (run) that can range from 20 to 100 feet (I used cat5 cable, with each inner wire (randomly chosen) dedicated to a single digital in, out, +5, +9 or ground.)  There is a good change that outside voltages could impact these digital outs (or any other pin or power wire.)

I have a good resource on protecting digital in's but I ma not sure how to protect the digital outs.  Each needs to be able to both pull a connect component to ground, and push it up to 5 volts (am I saying this correctly?)

This should be able to protect the digital outs from shorts or 12v spikes.

How can I build this circuit?

Edit: it is difficult for me to describe this problem without mentioning the danger to all components.

Note that ways of protecting digital inputs is HERE.

Some good results you can get with optocouplers.

It's electrically disconnects one part of your circuit from another.

For example, here is my IoT-ish device, which is detects water leaks in my bathroom:

I use the transformer (T1), which have two separate output windings, so, that windings does not connected electrically, only magnetically. The block in border "Sensing unit" doesn't have any wires with other scheme - only magnetic field, which is gives it power, and infrared light in the optocoupler (u2, PC817), which informs ESP01 about leak presence.

How does it work? Very simple! When the water shorts JP1 (long naked wires on the floor), Q1 opens and lights-up the IR diode in PC817. Light from this diode opens another transistor - and pulls the RxD PIN of ESP01 down.

Small sketch, written on Arduino for ESP8266 periodically sends pin state by HTTPS on my web server, where monitor software, Nagios, checks the information age and the pin state, and send to me notifications, when something goes wrong.


Linking Arduino With Twitter My project is having Arduino with my WiFi shield connect to Twitter and look for any messages that other users have tweeted at me that contain a certain color, (I.E. @myTwitterHandle I want red) and then changes an RGB LED to become that color.

I have been searching online for different methods, and found a few different solutions which I could use as a starting point. However, these apparently call to an old Twitter API that is not supported anymore (support stopped mid 2013).

One solution I came across was to use node-red as well as MQTT.  I am not too familiar with these programs.

Does anyone know how to have Arduino parse a twitter account for mentions containing certain strings and have it print to LED? Any help with be appreciated

The new Twitter 1.1 API requires OAuth authorization over SSL, for which Arduino is under-powered.

You will need to write a proxy application, which would parse the tweets and then send a RGB color value to your Arduino.

You should split your project into three parts.

Retrieving tweets with the Twitter API.
You can get some library to do it for you.
Communicating with your Arduino.
Just try to send an arbitrary color to your Arduino over internet.
And finally joining first two pieces of code together.

And if you get stuck somewhere, you can always ask for help here on StackExchenge.


Specific ports on Teensy 3.6 not reading correct bit resolution using ADC library? I have a basic circuit, where I'm reading analog values from 14 infrared receivers.

I set the bit resolution to 16 but specific ports are returning 10 bit values (from 0 - 1024) instead of 16 bit values (from 0 - 65536).

I can confirm this is not a problem with my circuitry because when I've tested reading each individual sensor with a port that "works" and the correct range is returned every time.

Here is my code:

#include <ADC.h>

ADC *adc = new ADC();
const int* RECIEVERS = (int[14])
{
    A15, A16, A17, A19, A20, A21, A22, A1, A2, A3, A6, A7, A8, A9
};

void setup() {
    Serial.begin(4608000);
    adc->setAveraging(16); // set number of averages
    adc->setResolution(16); // set bits of resolution
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS);
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED);
    for (int i = 0; i < 14; i++) pinMode(RECIEVERS[i], INPUT);
}

void loop() {
    for (int i = 0; i < 14; i++) {
        Serial.print(adc->analogRead(RECIEVERS[i]));
        Serial.print(" | ");
        delay(1);
    }
    Serial.println("");
}

Is there a problem with my code or is my Teensy damaged?

The Kinesis 66 (the chip on the Teensy 3.6) has two ADC modules. Each one talks to different pins.

By default the configuration functions in that library configure ADC0, so unless you tell it otherwise, you will only be configuring half the ADC pins.

You should call each of the configuration functions twice, once for ADC0 and once for ADC1:

adc->setAveraging(16, 0); // set number of averages
adc->setResolution(16, 0); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 0);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 0);

adc->setAveraging(16, 1); // set number of averages
adc->setResolution(16, 1); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 1);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 1);


Powering Arduino Mega 2560 from a Raspberry Pi Usb I have a Raspberry Pi B+ running 7x24. I have to connect an Arduino Mega 2560 to its USB. The Arduino has only one nRF24L01-PA-LNA powered from its 3V3.
Can I power the Arduino from the Pi's USB?

If you are powering your RPi from power supply 5V/2A at least there should be no problem. USB hub on the RPi should not give more than 500mA to power Arduino. Also there is a fuse on Arduino's board to prevent any damage from USB power.

Check both Arduino and RPi schematics for more details about modules used there:

Arduino
Raspberry


Using Keyboard library for ISO-UK layout I am creating a keyboard and the PC I use it with is configured for UK so the keyboard layout it expects is this

I've highlighted the ISO-UK vs ANSI-US differences but the only key I am having real problems with is the backslash key.
My physical layout is actually this (ortholinear "Planck") but it's essentially the same except with two logical layers and variation in positioning.

The above is a fully functional UK-layout keyboard with the exception of the "\" key.
The sketch I am using is too large and distracting to post here but the following test sketch
#include "Keyboard.h"

byte keylist[] = { '`', '2', '3', '\'', '#', '\\' };

void setup() {
  Keyboard.begin();
  delay(1000);

  // unshifted
  for (byte i = 0; i < sizeof(keylist); i++) {
    Keyboard.press(keylist[i]);      delay(100);
    Keyboard.release(keylist[i]);    delay(100);
  }

  Keyboard.press(KEY_RETURN);
  Keyboard.releaseAll();

  // shifted
  for (byte i = 0; i < sizeof(keylist); i++) {
    Keyboard.press(KEY_LEFT_SHIFT);
    Keyboard.press(keylist[i]);
    delay(100);
    Keyboard.releaseAll();
    delay(100);
  }
}

void loop() {
  delay(1000);
}

Creates this output (in a Notepad window)
`23'£#
¬"£@£~

I did try switching focus to a keyboard diagnostic tool - KeyHitter by Elite Keyboards which showed different results
12:31.0675 ` (0xDF, BIOS 0x29) DOWN
12:31.0771 ` (0xDF, BIOS 0x29) UP -> 100ms
12:32.0772 2 (0x32, BIOS 0x03) DOWN
12:32.0871 2 (0x32, BIOS 0x03) UP -> 100ms
12:33.0872 3 (0x33, BIOS 0x04) DOWN
12:33.0972 3 (0x33, BIOS 0x04) UP -> 100ms
12:34.0972 ' (0xC0, BIOS 0x28) DOWN
12:35.0072 ' (0xC0, BIOS 0x28) UP -> 100ms
12:36.0072 LShift (0x10, BIOS 0x2A) DOWN
12:36.0082 3 (0x33, BIOS 0x04) DOWN
12:36.0172 LShift (0x10, BIOS 0x2A) UP -> 100ms
12:36.0182 3 (0x33, BIOS 0x04) UP -> 100ms
12:37.0172 \ (0xDE, BIOS 0x2B) DOWN
12:37.0272 \ (0xDE, BIOS 0x2B) UP -> 100ms
12:38.0271 Enter (0x0D, BIOS 0x1C) DOWN
12:38.0273 Enter (0x0D, BIOS 0x1C) UP -> 2ms

...
So the Arduino Keyboard library translates '#' into shift+3 which is unhelpful for UK users but I'm mystified why Keyhitter sees that '\\' produces the expected \ but other programs see it producing #! I guess Keyhitter intercepts keystrokes at a lower level than normal applications - for example it correctly shows Win being pressed but prevents Windows opening a start-menu.
The result in Notepad is typical of the effect produced in normal applications. So that's probably more relevant.
I can work around the '#' producing a shift+3 since '\\' produces # but how then do I generate a \?

The USB keyboard protocol has no concept of characters. It doesn't know and doesn't care what character a key represents. Instead each code represents the location of the key on the keyboard, and it's down to the software on the computer to map those locations into characters through its own keyboard map.
So the Arduino has to do the opposite when you want to "print" text through the keyboard - convert that text into the locations of the keys on the keyboard. And it does that through the _asciimap array in Keyboard.cpp.
To use any other keyboard layout than US you need to modify that map so that each ASCII value points to the correct location for that character as defined in your computer's keyboard map.
You can find the list of keyboard location codes (named in this document after the US keycap decals) here (page 53) which you can then use to map any changes.
For example in _asciimap a double quote is listed as:
     0x34|SHIFT,    // "

Which maps to Keyboard ' and " in USB. But for UK you want that to be shift-2, which is Keyboard 2 and @ in a US layout.  That entry is hex 1F.
So changing the quote to be a shifted 0x1F should give you the quote you desire:
    0x1F|SHIFT, // "

You would need to do the same to all other characters that need re-mapping (including ). Some may take a little trial and error to work out what the equivalent key on a UK keyboard is, since some keys are in physically different locations (most notably there is no key to the left of Z on a US keyboard, but there is an extra one to the right of ]).
Unfortunately the Arduino Keyboard library doesn't provide a way for a user to give their own keyboard map. Instead you have to modify the source code of the library itself.


Are hardware interrupts used while controlling an LCD screen using the LiquidCrystal library? I'm working on a tone generator project that uses Mozzi to make sound (sine waves mainly). As I understand, Mozzi can glitch if used along with hardware interrupts.

The plan is to use the classic 2x16 LCD screen, but I don't know the guts of the library or interface. Are hardware interrupts used while interfacing with an LCD screen, or by the LiquidCrystal library?

The LiquidCrystal code shows that delays are used. That can cause audio glitches in the sound.
The LiquidCrystal library does not use interrupts.

You could try to change the LiquidCrystal code according to the instruction on the Mozzi page.


Thingspeak Library returns 0 using ESP8266 on Arduino I have tried using the thingspeak-arduino library and tested some of the examples:

#include <WiFi.h>
#include <WiFiClient.h>
#include <SPI.h>
#include <ThingSpeak.h>
char ssid[] = "Benok4G";    //  your network SSID (name)
char pass[] = "password";   // your network password
WiFiClient  client;

unsigned long myChannelNumber = 344468;
const char * myReadAPIKey = "xxxxxxxxx";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  WiFi.begin(ssid, pass);
  ThingSpeak.begin(client);
}

void loop() {
  // put your main code here, to run repeatedly:
  float voltage = ThingSpeak.readFloatField(myChannelNumber, 1, myReadAPIKey);

  Serial.print("Latest voltage is: ");
  Serial.print(voltage);
  Serial.println("V");

  delay(30000);
}

When i run this code, I get this on the Serial Monitor.

Why is it 0.00? It's supposed to be 24.0

http://184.106.153.149/channels/344468/fields/1/last

Did I do something wrong? I am very frustrated because I've tried a lot of methods already just to fetch the data from ThingSpeak to my Arduino using ESP8266. I can send but when receiving I am really lost and confused.

#include <WiFi.h>

From the WiFi library reference page:

  With the Arduino WiFi Shield, this library allows an Arduino board to connect to the internet.

From the Arduino WiFi Shield product page:

  It is based on the HDG204 Wireless LAN 802.11b/g System in-Package. An AT32UC3 provides a network (IP) stack capable of both TCP and UDP.

But you're not using an Arduino WiFi Shield or anything compatible. You're using an ESP8266 which is completely different. Thus you can't use the WiFi library for your project.

Instead you will need to use the appropriate ESP8266 library. If you are programming the ESP8266 directly that will be the ESP8266WiFi library, which is bundled with the ESP8266 core for Arduino. If you are using the ESP8266 as a WiFi module controlled via AT commands that will be the WiFiEsp library


Powering a stepper motor I'm working on a project where I need a high torque stepper motor. The stepper motor being used is rated at 12 - 24 volts and when I used a 12 volt battery supply composed of 8 AA batteries it appeared to work fine.

Because I wanted higher torque I set the pot on the Easy Driver to 0.5 amps which is within what was recommended for the motor, and used a Lithium Ion battery originally being used for a power drill rated at 18V and 1.5Ah.

When I connected the battery to the easy driver the motor got very hot and would shake when I tried to turn it but not turn. Now the motor will not work with the 8 AA batteries either. Heres a link to the motor US Ship OSM 5:1 Planetary Gearbox Nema 8 Stepper Motor Samll Size High Torque.

What did I do wrong and how can I fix it?

P.S. I am using a photon as the micro controller and the motor is being controlled using the Blynk app I eliminated the chance of it having to do with the photon or Blynk App.

I found out that the battery I'm using is the Makita BL1815 and it is really composed of 2 batteries which are both rated at 15C. I am not sure if C-rating adds or stays the same when you are using two batteries. When I measure the Voltage on the test points I get 4.27V and when using a formula to find current for the Easy Driver I get 0.480A.

How did you set the amps on the http://www.schmalzhaus.com/EasyDriver/ to 0.5A?   What was the voltage at the test point?  The EasyDriver v4.5 schematic says the formula for coil current is A = V/6.  So rearranging, V=A*6, and to get 0.5A, the voltage should be 0.5*6=3V at the motor driver's test point.

The linked motor spec is 0.6A max per coil, and if things went wrong, you could have overloaded a motor.  The 18V battery could have easily provided 1.8 amps to the 10ohm coil in the motor for a bit, before 3x the rated current of the coils would burn it out, or the easydriver went into thermal shutdown or something.

The easydriver looks like it would be capable of controlling the current adequately, but if misconfigured, could easily overcurrent the motor.


Malloc with Objects in Arduino libraries My understanding of using dynamic memory on the arduino is that new/delete are not available, only malloc realloc and such C functions, as mentioned here:

C++ & the AVR

I am creating a library that defines an object type that needs to contain a dynamic list of other objects. In C++ I would define it something like this:

class Container
{
std::vector<otherObjectType> otherObjects;
};

which obviously does not work in the arduino without the C++ standard library.

My next choice would be to create a dynamic array using new, ie

otherObjects = new otherObjectType[3]
{
    {   (arguments to constructor...)
    },
    {   (arguments to constructor...)
    },
    {   (arguments to constructor...)
    }
};

But this does not work as well, since new is not supported...

finally I could try to use malloc as laid out here, but that also wont work without new.

I am wondering if I should just rewrite everything as structs, since that wont require me to worry about whether the constructor for the object was called when the memory was allocated in malloc.

new actually does work in arduino. it is defined in arduino/hardware/arduino/avr/cores/arduino/{new.h, new.cpp} using malloc. It is not part of avr-libc though (which your link concerns) and has not always been added by arduino.

Both of these work for me:

namespace{ //namespace to deal with .ino preprocessor bug
    class foo{
    public:
        int bar;
        foo(int a){
            bar = a;
        }
    };
}
...
//using new
foo *a = new foo[3]{{1},{2},{3}};

//How I would probably do this with malloc
foo *b = (foo*) malloc(sizeof(foo)*3);
b[0] = foo(2);
b[1] = foo(4);
b[2] = foo(8);

Placement new is not defined right now. I know that copying isn't quite the same, but it should work in most cases.

Of course, if you know exactly how long you want the array to be at compile time, you should probably make it a static/global variable so that you avoid using dynamic memory and the sketch ram usage number will be closer to correct.


Shared 5v power for Due dedicated application I would appreciate input on this situation:

I plan to power a fairly high current, 5 volt supply, 3.3v signal, device from a suitable wall wart. I would like to power the due that controls it through the due's usb port by tapping the 5v from the wall wart into a suitably modified USB cable (leaving the signal pins unused). No significant external power demands would be made on the due's 3.3v or 5v headers.

So there are two devices sharing the wall wart: one device that uses high current, and the other device is the due.

Yes it is possible. You just need to connect both Grounds


PC Fan Speed Control I am working on a project to blow air gently through a number of pipes and variable speed. I would like to use a standard PC case fan and have control of whether the fans are on/off and also what speed they spin at. My hope is to attach temperature sensors later and eventually blow are depending on the temperature.

It appears that PC fans on 3-wire and 4-wire systems provide variable speed by changing input voltage ranging from 3-12V  (linear voltage regulator) or with PWM set to 3.3V or 5V. Furthermore, it looks like inexpensive products exist to split/copy a single signal to multiple fans (see here).

I am hoping to control 4-8 fan speeds, as independently as possible while using as simple/standard a case fan as possible. What is the best way to drive PC case fans using the Arduino?

Reference: https://en.wikipedia.org/wiki/Computer_fan_control

To put the comments into an answer:
You can drive most PC fans (which have at least 3 pins) with any PWM source and change their speed through the duty cycle. The Arduino Uno itself has 6 PWM channels. If you want to control more fans, you have to use an extra chip, that provides PWM. You can use the breakout board from Adafruit, but also any other external PWM chip (they are often marked as servo drivers, since servos use PWM signal too).
The speed of most fans can also be changed through providing a different input voltage, but this is not intended for direct variation. Instead this is normally used to set the speed interval, in which the fan should run. For example some PC fans have extra adapters, which lower the supply voltage to let them run more silent. For short term variation you should definitely use PWM. If your fans are too fast at their nominal voltage, you can provide them with a lower voltage permanently.
As dandavis pointed out, the 4th pin is usually connected to a feedback loop. They provide a defined number of pulses per full rotation, so that you can really measure the speed, instead of just estimating. When you don't need this functionality both kinds of fans (3 pin or 4 pin) are good for you.


How can I do this sentence show me in arduino How can I do this sentence show me in arduino."WARNING: Category 'USB' in library Mouse/keyboard is not valid.Setting to 'Uncategorized'

Your question is unclear.

Note that Mouse and Keyboard libraries are suitable for use with Arduino Due and Zero boards, or with 32u4-based boards like Arduino Leonardo or Micro.   They are not relevant when using an Uno.


Issues with AltSoftSerial I have my arduino connected to my PC and another serial device.
This serial device sends a 3 line piece of info on bootup then if I trip a zone it will send information regarding the radio transmission.

When I first power up the device I see the information from the device in the serial monitor (SELFTEST-PASS) however that is the last information I receive from it until I powercycle the device.

I have connected it directly to my PC comport and verified information is being sent via Serial however the arduino seems to quit after the first bit of info... any idea where to proceed from here?
PS I have tried both SoftwareSerial and NewSoftSerial
Here is an example of the data sent from the serial device as viewed by hyperterminal:

<1234 #3F->0000 1234->FFFF D_ALARM>
<FFFF #3F->1234 FFFF->1234 P_ACK>
<1234 #40->0000 1234->FFFF D_ZREST>

Code that is currently not working:

 #include <AltSoftSerial.h>
 AltSoftSerial portOne;

void setup() {

                Serial.begin(4800);
                while (!Serial) {; // wait for serial port to connect. Needed for native USB port only
                }
                // Start each software serial port
                portOne.begin(4800);

              }

// the loop function runs over and over again forever
void loop()
{
  if (portOne.available())
  {
    Serial.write(portOne.read());
  }

  if (Serial.available())
  {
    portOne.write(Serial.read());
  }
}

Try SoftwareSerial rather than AltSoftSerial.

I don't see the point in these lines, I think you can remove them:

 if (Serial.available())
  {
    portOne.write(Serial.read());
  }

  I have connected directly to a pic and verified the radio I'm connecting to does indeed continue to send data.

If that is the case, that it sends data anyway, then you could just use HardwareSerial. Connect the radio to Rx (D0 on the Uno) and leave Tx unconnected. Then just read from Serial, and write to Serial. You should see the results on the Serial Monitor. (Disconnect this wire when uploading new versions of the sketch).


Where is PORTB defined? On Arduino I can set digital pins by setting special variables PORTB and PORTD (or maybe they are not variables?). Where are those variables defined? I grepped /usr/share/arduino, but found nothing.

grep -r 'PORTB' /usr/share/arduino/

PORTB is defined by the "toolchain". It is not defined by Arduino.
For instance in my setup the Arduino Uno uses "toolchain" avr-gcc\4.9.2-amtel3.5.3-arduino2\avr.

If you grep that folder (location dependent on tool and installation options) you will find a file called iom328p.h that defines

#define PORTB _SFR_IO8(0x05)

This is a mapping to a physical address of the cpu.


How to detect if LED is switched on in external circuit using Arduino NANO? I want to detect when an LED is powered on using an Arduino NANO. The LED is part of an external circuit. The LED uses about 1.8V. Would the circuit below allow me to detect when the LED is switched on? Is this the correct method of doing it? (The LED in the diagram represents the external circuit).

I'm afraid your circuit does not work.
In fact, the base of the transistor is always connected to the power, regardless the LED being ON or OFF. Therefore the BJT would be always in the ON-state. Also a current limiting resistor in series to the LED is missing (but I think that it was just for sake of simplicity).

Assuming that:

you can mount in series something to the LED
an additional 1.3-1.5V voltage drop will not cause too much issues (to be short: if the external circuit power supply is "large enough", and if you will not be too much upset if the LED luminosity will be smaller).
You want to sense a signal LED, i.e. let's say with a current smaller than 20 mA.

Then, the safest way would be to use an optocoupler, such as 4N25-4N35. Put the LED of the optocoupler (transmitter side) in series to the LED you want to "sense", and use the phototransistor side to sense the LED status: it's emitter goes to the GND to your Arduino Nano, the collector to any input, with pull-up (The pull-up is mandatory!).

In this way, when current flows across the LED, it will also flow in the optocoupler LED, therefore the optocoupler phototransistor will be ON.

Also, using the optocoupler the two systems are electrically insulated each other (and you won't need to share the grounds).

Below you can find an example.

EDIT:
If you cannot wire the optocoupler LED in series (e.g. not enough voltage headroom because the power supply is too close to the LED Vf, or your LED is already on a PCB), you can connect the optocoupler in parallel.
Assuming the LED current is much larger than 1mA, you can use the following circuit. Choose RO so that the current flowing on the optocoupler will be 1mA (390-470 Ohm in your case). Usage of high current-transfer-ratio (CTR) optocoupler is suggested, but this might work also with a 4N25 or 4N35 (you'll be pretty close to the limit...)


Adding a custom board to the Arduino IDE I would like to know what is the procedure for adding a custom board to the Arduino IDE?

My custom board is similar to the Arduino Zero. Instead of using the ATSAMD21G18, my board is based around the ATSAMC21G18. I also have the Atmel/Microchip SAMC21 Xplained development board.

I have found some open source code where the author has adapted/forked the Arduino SAMD21 code and made it work for the SAMC21 Xplained board (here). The author has stuck to the Arduino hardware folder structure and has added the SAMC21 Xplained to the board.txt file.

As a test, when I install the Arduino SAMD21 from the Arduino Board Manager, I noticed that it installed the hardware files in the following directory:

 %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\samd\1.6.19\

I have read that to add hardware files to the board manager I need to create a .json file with the appropriate details. More information here. However, as far as I can tell, this requires me to zip the SAMC21 hardware files into a tarball and provide a URL to that tarball. I also need to generate and insert a SHA in the .json file.

Am I on the right path with the .json file?

Or should I just download the SAMC21 hardware files and place them in the %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\samd\ folder next to the 1.6.19 folder?

My last resort would be to just copy the files into the existing SAMD21 hardware folder?

I have looked into the following Arduino SE questions but they do not answer the question satisfactorily.

upload.tool not used in custom boards.txt?
Arduino Due custom platform for school and library installation (I would prefer not to use the Arduino IDE in portable mode.)

The simplest clean way to add your board using an existing core is to add the variant to your sketches folder's hardware subfolder. Only boards.txt and files for the board variant are added.

In your sketches folder create a 'hardware' folder. In this folder create a folder with the name of your boards package and a subfolder with the architecture name and a subfolder for variant and a name of the variant. for example hardware/my_boards/samd/variants/samc21x

In your variant folder (variants/samc21x) put the files for your variant based on variant files of the closet variant in the referenced hardware package. In your case perhaps a mkrzero would be a good example.

In your package's root (hardware/my_boards/samd/) add boards.txt file with entries for your board.

For boards.txt take the options for a similar board in referenced package. Change the names and settings and prefix build.core value with the name of the vendor of the referenced package. For arduino/samd it would be arduino:. For example samc21x.build.core=arduino:arduino

My custom and customized boards definitions https://github.com/jandrassy/my_boards


Is Ticker.h really safe to use? I have this code

#include <Ticker.h>  //Ticker Library
Ticker blinker;
/* ... */

//blinker.attach(1, []() { digitalWrite(LED,!digitalRead(LED)); }
while(!client.connect(laptop,port)) {
   Serial.println("Connecting...");
   delay(1000);
}

Which works fine, tries connecting, then eventually connects.

If I uncomment the line attaching to this 'blinker' Ticker, then I get a crash right after the first 'Connecting...' print. When I look at the stack trace, it mentions that the crash happens during the delay(1000) in my while loop (which is presumably the moment when the program yields and the blinker can do some work)

Is there anything I can do to make this timer work better?

Update: the original question mentioned timers, so this answer is for a hardware timer interrupt handler. It doesn't apply to Ticker, which is what the question is now about.

The callback that you attach to blinker will be called as an interrupt handler, so it's important to make sure it's already loaded into executable instruction memory (iRAM) on the ESP8266. When you pass anonymous function inline to blinker.attach() it won't tagged to be stored in iRAM.

Try this instead:

void ICACHE_RAM_ATTR blinker_handler(){
    digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
}

...

blinker.attach(1, blinker_handler);

ICACHE_RAM_ATTR tells the system to keep the code in the instruction RAM. There's not a lot of iRAM (32Kbytes) so you don't want to do this too often, but it's important for interrupt handlers (another reason to keep them short and sweet).


Can the official arduino GSM shield library be changed to work with hardware serial on mega I have a complex requirement that uses a number of libraries that depend on timing I.e. OneWire. When using the official GSM shield on a mega, it loads a version of software serial to talk to the GSM. I want to make it use a spare hardware serial port on the MEGA for more timing stability. How should I modify the GSM library to (optionally) auto detect a MEGA and then use a nominated serial port. I am happy to jumper the correct pins from the mega serial hardware port to the bent outwards pins 2 and 3 of the GSM shield ( pin 2 is already bent out if you use a MEGA anyway).

Before we start, note that it might not be the right pinout for the GSM shield to use a hardware serial port on the Mega. Beware of some nasty wiring.

Poking around on Github, I found this is the directory for the GSM library. Ladies and gentlemen, it's time to break something important get our hands dirty! Draw your  chairs close for a tale of touching code you shouldn't touch!

Click on the src folder to open it up. When I first opened this up, I was somewhat scared by the number of files. However, I had a plan:

Find the name of the SoftwareSerial instance. I'm guessing that they would use only one object to do this to prevent redundancy. In addition, I'm going to guess that most serial data is handles though a single file, but I'll have to confirm this.
Remove instances of the SoftwareSerial Object.
Clean up any remaining issues with the "port"

After more poking around, I noticed that the library actually uses a unique version of the SoftwareSerial library, so it will be even harder to do this. Yay us! On the upside, we know exactly what code to replace. Fasten your seatbelts, this is about to get pretty nasty.

Okay, take a step back here and figure out what we want to modify. First of all, it's a terrible idea to modify the libraries directly in the directory that the Arduino IDE uses.

So, if you were to make a copy from the src folder for the GSM library into the Arduino "libraries" folder, it wouldn't be enough. The Arduino IDE would get confused when there would be two identical header files to use. You will need to rename the main header file and use just that one instead to include into your projects. In addition, most of the files in the library probably reference that file, so make sure to rename any references within the library to that one file. A quick CTRL + SHIFT + F on the Atom text editor will search the entire project I'm working on. I'm not entirely sure if a folder name would mess up the Arduino IDE, but it'd be a good idea to rename the folder to whatever your library is called, at least for readability purposes.

Before we continue, let's make sure that the library still compiles without us playing with the code. Import the new library into a basic GSM example sketch and see if it compiles and works normally.

It compiles? Great. Let's go on!

The file that does serial is the GSM3SoftSerial.cpp file. Without actually porting it, I can't give you a ton of advice here. Look through and see when variables are created, used, and modified. If you're not sure, I'm in chat sometimes: feel free to ask there on minor questions and ping me with @AnnonomusPenguin or leave a comment on this post.

I'd also advise to leave everything in there that you're not sure of, make sure it works with hardware serial, and line by line start removing that variable and see if anything breaks. A great too for this would be to use a tool like Git/Github (or other version control software) to help you revert changes that broke something or to see, overall, what you've changed.

So, after replacing the code inside the functions (finalWrite, the ISRs, and the begin/clear seem like the ones you should touch), compile the code and see if it works!


Arduino Object Oriented Programming Can anyone send me a link tutorial about Arduino Object Oriented Programming? I want to learn Arduino, I am just a beginner.

"Arduino" is just plain old C++ with (in some cases) bits removed and some helper functions and classes.
For the smaller (lower powered AVR for example) there is no full STL in the C++ library, and some functions are of a reduced complexity (such as no floating point support in the printf family of functions by default).
For OOP you don't need to know anything "Arduino" - it's just C++. Any C++ OOP tutorial will teach you what you need to know for Arduino OOP.


Coding a Stirrer with Different Speeds I'm in charge of creating a code for my class using Arduino an Arduino UNO Board. There are 7 switches total: One acts as an start/stop, which allows it to have power when other settings are chosen. There are 3 switches for the speeds: slow, medium, and fast. There are 3 other switches for interval sizes (space between it spinning again): short, medium, and long. The user has to select one option from each set of 3 switches for it to work (9 total combinations). Somehow I have to code a pulse width modulator into it as well to control the motor speeds. Can someone point me in the right direction with pseudocode or something? Also I have no clue what to do with the PWM. Thank you so much, any help would be very appreciated.

The above comments are spot on.  It sounds to me like you are new to the Arduino, so the very first thing to do is go to the Arduino Reference page https://www.arduino.cc/reference/en/.  That shows you the basic tools you will need to work with.  It's not obvious from that page, but analogWrite() is what you use for the PWM, as explained if you click on that topic.  Note that it only works on certain pins.  Don't worry about controlling a motor at first, just control the brightness of an LED until everything is debugged.
You mention 3 different intervals.  Are each of these to give equal on and off times, and just keep repeating until you turn the stirrer off?  Or will you have a separate fixed run time and the buttons selects one of 3 different off times per cycle?  Or is there only one cycle, and the buttons just select how long it will be before automatically shutting off?  The answer will determine how you set up the timing.  Assuming that the UNO doesn't need to do anything other than control the stirrer, you can probably do all timing with the delay() function.
You can start with the famous "blink" code.  Once you get that working, change it to use one of the pins that supports PWM (not the built-in LED on pin 13).  The code has separate delay() values for on and off times, which you can set for one of your 3 intervals.  Then change the digitalWrite() commands to analogWrite(), of course with the proper parameters. Now you have the basic system, and can work on the switching logic.


expected `}' at end of input int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup() {
    Serial.begin(9600);
    pinMode(6, OUTPUT);
    pinMode(9, OUTPUT);
 }
void loop(){
 sensorVal = analogRead(A1);

 Serial.print("Sensor Value: ");
 Serial.print(sensorVal);

 float voltage = (sensorVal*5.0)/1024.0;
    Serial.print("Volts: ");
    Serial.print(voltage);

 float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
 float pressure_bar = pressure_pascal/10e5;
   Serial.print("Pressure = ");
   Serial.print(pressure_bar);
   Serial.println(" bars");
   Serial.print("Pressure = ");
   {
 for(int a = 255; a>=0;a--)
 {
   analogWrite(6,a);
 if (pressure_bar = 1600){
   analogWrite (6, a);
 if (pressure_bar > 1600){
   analogWrite (6, a);
 }
 for(int a = 0; a<256; a++)
 {
  analogWrite(6, a);
 {
 if(pressure_bar < 1600){
  analogWrite (6, a);
 }
 for(int b = 255; b>=0;b--)
 {
 analogWrite(9, b);
 {
 if (pressure_bar == 1600){
   analogWrite (9, b);
 if(pressure_bar < 1600){
   analogWrite (9, b);
}
 for(int b = 0; b<256; b++)
 {
   analogWrite(9, b);
 {
if (pressure_bar > 1600){
   analogWrite (9, b);
   }
  }

Some guidelines for programming:

Start each statement on a new line

int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup() {
Serial.begin(9600);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
} void loop(){
sensorVal = analogRead(A1);

Serial.print("Sensor Value: "); Serial.print(sensorVal);

float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: "); Serial.print(voltage);

float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
float pressure_bar = pressure_pascal/10e5;
Serial.print("Pressure = ");
Serial.print(pressure_bar);
Serial.println(" bars");
Serial.print("Pressure = "); {
for(int a = 255; a>=0;a--) {
analogWrite(6,a);
if (pressure_bar = 1600){
analogWrite (6, a);
if (pressure_bar > 1600){
analogWrite (6, a); }
for(int a = 0; a<256; a++) {
analogWrite(6, a); {
if(pressure_bar < 1600){
analogWrite (6, a); }
for(int b = 255; b>=0;b--) {
analogWrite(9, b); {
if (pressure_bar == 1600){
analogWrite (9, b);
if(pressure_bar < 1600){
analogWrite (9, b); }
for(int b = 0; b<256; b++) {
analogWrite(9, b); {
if (pressure_bar > 1600){
analogWrite (9, b);
} }

Use brackets and align them

.. so each pair of { and } is on the same column and align code with brackets to be indented 2, 3 or 4 spaces

int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
}
void loop()
{
  sensorVal = analogRead(A1);

  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: ");
  Serial.print(voltage);

  float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
  float pressure_bar = pressure_pascal/10e5;
  Serial.print("Pressure = ");
  Serial.print(pressure_bar);
  Serial.println(" bars");
  Serial.print("Pressure = ");
  {
    for(int a = 255; a>=0;a--)
    {
      analogWrite(6,a);
      if (pressure_bar = 1600)
      {
        analogWrite (6, a);
        if (pressure_bar > 1600)
        {
          analogWrite (6, a);
        }
        for(int a = 0; a<256; a++)
        {
          analogWrite(6, a);
          {
            if(pressure_bar < 1600)
            {
              analogWrite (6, a);
            }
            for(int b = 255; b>=0;b--)
            {
              analogWrite(9, b);
              {
                if (pressure_bar == 1600)
                {
                  analogWrite (9, b);
                  if(pressure_bar < 1600)
                  {
                    analogWrite (9, b);
                  }
                  for(int b = 0; b<256; b++)
                  {
                    analogWrite(9, b);
                    {
                      if (pressure_bar > 1600)
                      {
                        analogWrite (9, b);
                      }
                    }

Remove superfluous brackets

As you can see, you are having some superfluous/missing brackets. What you want is probably something like:

int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
}
void loop()
{
  sensorVal = analogRead(A1);

  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: ");
  Serial.print(voltage);

  float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
  float pressure_bar = pressure_pascal/10e5;
  Serial.print("Pressure = ");
  Serial.print(pressure_bar);
  Serial.println(" bars");
  Serial.print("Pressure = ");

  for(int a = 255; a>=0;a--)
  {
    analogWrite(6,a);
    if (pressure_bar = 1600)
    {
      analogWrite (6, a);
    }
    if (pressure_bar > 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int a = 0; a<256; a++)
  {
    analogWrite(6, a);
    if(pressure_bar < 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int b = 255; b>=0;b--)
  {
    analogWrite(9, b);
    if (pressure_bar == 1600)
    {
      analogWrite (9, b);
    }
    if(pressure_bar < 1600)
    {
      analogWrite (9, b);
    }
  }
  for(int b = 0; b<256; b++)
  {
    analogWrite(9, b);
    if (pressure_bar > 1600)
    {
      analogWrite (9, b);
    }
  }
}

Remove duplicate code

In the if statement, you perform twice the same code (both you send an analogWrite with the same value, so the code (from the for loops can be reduced to:

  for(int a = 255; a>=0;a--)
  {
    analogWrite(6,a);
    if (pressure_bar >= 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int a = 0; a<256; a++)
  {
    analogWrite(6, a);
    if(pressure_bar <= 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int b = 255; b>=0;b--)
  {
    analogWrite(9, b);
    if (pressure_bar <= 1600)
    {
      analogWrite (9, b);
    }
  }
  for(int b = 0; b<256; b++)
  {
    analogWrite(9, b);
    if (pressure_bar >= 1600)
    {
      analogWrite (9, b);
    }
  }
}

Unclear

What is unclear why you first write an analog value, and directly afterward (in each if) you write the same value. I'm not sure what you really want here. Either you want to write to a different pin, or you want a delay (to have the value having some effect), I'm just not sure.


send configuration commands with arduino I am using ublox zed F9P multi GNSS module. I have to program it for its configuration messages. Like I have to run a specific configuration of my receiver with the help of Arduino. I know arduino parse the GNSS sentences but can anyone tell me how to write code for ublox configuration commands such that that command can change setting of the receiver upon burning it in Arduino. Also, that code should retain in the receiver even if arduino is disconnected (closing arduino IDE console). Please help

Here you find a standard library from arduino.
https://www.arduino.cc/reference/en/libraries/sparkfun-ublox-arduino-library/
You can find the documentation here:
https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library


Arduino IDE compiling for non-arduino AVR boards Using:

Arduino IDE 1.8.2
the board manager from https://mcudude.github.io/MiniCore/package_MCUdude_MiniCore_index.json
an ATmega168P MCU in TQFP

I was able to run my code successfully by modifying the file

[ardunoIDE]\hardware\arduino\avr\variants\standard\pins_arduino.h

building and then flashing the MCU with avrdude.

Is there any way to have Arduino IDE build system pick its pins_arduino.h file from somewhere else ?

Yes, MiniCore is a self-contained hardware package. After installing MiniCore select one of the MiniCore boards in the Arduino IDE's Tools > Board menu and the Arduino IDE will automatically use the pins_arduino.h file included with MiniCore. There is no need to modify any file in the Arduino IDE folder or any other folder.


How to wire a three-pin on-off-on switch for reading input? I would like to read the output of an on-off-on switch with my Leonardo board, but I have very little knowledge of electronics and don't know how to wire it up.
This is the switch in question: E-Switch 200MSP4T1B1M1QE
The switch has three pins. Generic three-pin SPDT wiring diagrams I've found suggest that the two outer pins should be connected to separate lights and the middle pin should be connected to the power source. Those lights also have a ground connection.
I don't want to power anything in a literal sense, I only want to have the Leonardo read the output of the switch. The end goal is to have the two ON positions read as separate button presses (eventually using a joystick library, in case that changes how the switch needs to be wired).
My questions are:

Is the above wiring example correct for my use case?
Is the output of the switch considered digital or analog?
Is a wire from the switch to GND not required?

One final note - I'm not using a breadboard, but connecting the wires directly from the switch to the board.

I suggest this simple circuit:

simulate this circuit – Schematic created using CircuitLab
Set both inputs to INPUT_PULLUP. If the input reads LOW, that means it has been grounded by the switch.

Edit: Per Duncan’s request, here is the alternative circuit with the polarities inverted. With the switch’s common connected to Vcc, the inputs should be set to INPUT_PULLDOWN. However, most Arduinos do not support this mode, for lack of internal pull-downs. Then one has to use external pull-downs instead, and set the pins to INPUT.

simulate this circuit
With this circuit, a pin reads HIGH when it is connected to +5V by the switch.


CC3000 gets wrong address when connecting to wireless AP I tried using both the SparkFun and Adafruit CC3000 libraries first with what I actually wanted as a program, but when that didn't work, the examples for those libraries, and I always seem to get the same problem.

The CC3000 will connect to my AP, which uses a private address in the range 172.24.1.1/24, and somehow it will end up with the address 192.168.1.64.

I know that it is connecting, since iw event lists the device MAC address as it connects.

The only changes I have made to the source code at this point are the ssid and password, and changing the interrupt and vbat pins to match the configuration of the tinyduino cc3000 board.

The device has firmware 1.34. Here is the code.

The specific output I get from the arduino is as follows (Note I commented out the disconnect at the bottom):

Connected at 115200

---------------------------------
SparkFun CC3000 - Connection Test
---------------------------------
CC3000 initialization complete
Connecting to: my_wifi_ap
Connected!

CC3000 MAC Address: 70:FF:76:04:B9:5B
IP Address: 192.168.1.62
Subnet Mask: 255.255.255.0
Default Gateway: 192.168.1.254
DHCP Server: 0.0.0.0
DNS Server: 192.168.1.254
SSID: my_wifi_ap

Finished connection test

running iw event -f on my AP before running a connection test gives me the following output:

wlan0: new station 70:ff:76:04:b9:5b

When another device, like my phone, connects to this AP, we get 172.24.1.xx, where xx is whatever number between 50 and 150 that DHCP assigns us.

Edit:
Also, if I comment out the disconnect at the end of the test, I can see the device is sending keepalives every three or four seconds using:

iw dev wlan0 station get 70:ff:76:04:b9:5b  //(inactive time never exceeds 4000ms).

I can't ping 192.168.1.64 because that network is obviously unreachable, but trying to ping 172.24.1.64 gives me a exception:

icmp open socket: Operation not permitted

Output from Adafruit Example:

RX Buffer : 131 bytes
TX Buffer : 131 bytes
Free RAM: 1221

Initialising the CC3000 ...
Firmware V. : 1.32
MAC Address : 0x70 0xFF 0x76 0x04 0xB9 0x5B
Started AP/SSID scan

Networks found: 20
================================================

...

SSID Name    : my_wifi_ap
RSSI         : 83
Security Mode: 3

SSID Name    : my_other_wifi_ap
RSSI         : 67
Security Mode: 3

...

================================================

Deleting old connection profiles

Attempting to connect to my_wifi_ap
Started AP/SSID scan

Connecting to my_wifi_ap...Waiting to connect...Connected!
Request DHCP

IP Addr: 192.168.1.62
Netmask: 255.255.255.0
Gateway: 192.168.1.254

The actual device being connected to is a Raspberry Pi AP, which was set up with DNSMASQ and hostapd. The configuration works, and has been proven to work with other embedded networking devices.

I realized that I was using firmware v 1.34 on the board, which is what it was configured with when I got it, and decided I would try to downgrade it to one of the fir;ware sets supplied by adafruit to see if that would work.

The firmware modifying program didn't actually compile on the desktop version of the arduino ide, so I decided to use codebender instead.

I'm not sure whether or not I should be disappointed or relieved, but downgrading the firmware actually made it work. I used the file titled driverpath_1_11, which I believe the libraries refer to as firmware version 0x113 or 0x118, which identifies itself as firmware version 1.24, which somehow actually worked.

The solution is here: https://codebender.cc/sketch:318229

The pins have been changed to correspond with the fixed pings used by the tinyduino.


DIY Arduino with USB port I am planing on making Arduino from scratch. I found many examples on internet, but they all need another Arduino for programming. How can I make Arduino with USB interface for programming and serial data transfer? Would I need something called FTDI? Basically I want same Arduino you can buy, just build it from separate parts.

There are two critical things that make an "Arduino". There is the hardware, and there is the bootloader.
The hardware is nothing special. It's just an MCU and the required minimal support hardware. What really makes it an Arduino is the bootloader which allows it to be programmed over the serial connection (via USB usually).
Without that bootloader the only way to program the MCU is over the hardware programming interface (typically ICSP for an AVR MCU), and for that you need some form of hardware programmer.
And of course that means the only way to put the bootloader onto the chip is to use a hardware programmer.
So you have two options:

Program the bootloader into the chip using a hardware programmer (which you can make with an Arduino), or
Buy an ATMega328P chip with the bootloader pre-programmed.

Once you have the bootloader installed then yes, you can program the chip over UART (through USB with a USB to UART adaptor such as an FT232).


fast memory buffer and setting output state I'm intending to set up a digital delay using a circular buffer (in SRAM) with an Arduino Due (@84MHz). The lenth of the buffer determines the delay. I need about 1us resolution and the delay needs to be dynamically settable between 0 - 500us. I'll probably use most of the memory just for the buffer.

I've got a very basic setup going (with a fixed delay, no buffer), that just updates a temporary variable with the current state of the input signal and then writes the whole word to another port in order to set the state.

Next up is designing the buffer so I can add some delay to the output of the signal.

Filling the buffer using interrupts watching signals on the same port shouldn't be too difficult but I am wondering:

a) taking speed in consideration, which buffer method will have the least processing overhead? Memory stack or an array[], or someting else?

b) is there a way to read a port and set an output port in one clock cycle? I am now using REG_PIOD_ODSR=outbyte; but ideally it needs to point to a memory address directly.

I would use an array, they're about as simple as it gets. 84 clock cycles per sample is very tight, but definitely possible. I'm guessing that's too close to the line to do any sort time testing - you will probably have to set up your loop to take exactly 84 instructions. This means you will probably need to hand-code in assembler. Be very mindful of branching instructions - both branches will need to take the same number of clock cycles.

The Uno (AtMega328) runs most (all?) instructions in one clock cycle, I don't know if the same applies to the Due. You would need to hand-code the assembler, check out how many cycles each instruction takes, and pad it out (there is a do nothing "NOP" instruction, which typically takes one cycle.

HOWEVER -

You can get all this work done for you by using a chip made for this purpose. This is called a Digital Delay Line, http://en.wikipedia.org/wiki/Digital_delay_line (or Analog Delay Line if you want analog values, e.g. for sound playback).


ESP8266 WiFiClient connection always returns 0 I am trying to use a NodeMCU as a station to connect to a webserver, however, the WiFiClient connect function always returns 0 for no reason. I am able to connect the NodeMCU to my home WiFi, but it just cannot connect to any server (either with IP address or with URL).

If anyone is interested, the following is the testing code (I did not include the libraries intentionally for the clearness of the code).

int status = WL_IDLE_STATUS;
IPAddress server(74,125,115,105);  // Google

// Initialize the client library
WiFiClient client;

void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting to AP specified during programming");
  WiFi.begin("mySSID", "myPassword");
  while (WiFi.status() != WL_CONNECTED) {delay(500); Serial.print("."); }
  Serial.print("\r\nWiFi connected IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

void loop() {
  Serial.println(client.connect(server,80));
}

I had the same problem with my esp-01. Just download ESPWenServer library from here.

  https://github.com/esp8266/ESPWebServer

And from this try HelloServer.ino example code. If it still does not connects-
1.Either your WIFI is not working
2.You are typing wrong SSID and PASSWORD
3.Spacing between SSID name or PASSWORD is the issue.

For the 3rd one if possible change your Wifi password or name if it has spaces between it.


How to get data from a device using ethernet connection with arduino I have a question,
I know how to flush the result of a device(using PIN mode) / control a device with help of an Ethernet shield of arduino.

Now, the thing I want is I need to read a device which communicates only via Ethernet. so i have now connected the device with a router and I have the IP address of the device. I need to read the data from the device using arduino + Ethernet shield.

In fine: How to read data from a device connected to a arduino + Ethernet Sheild via lan cable and flash the result in web server or serial portal. Doesn't matter.

Please suggest a solution or help me with code.

regards,
J

You are out of luck: The device talks SMP (Static Managment Program), which is a close-source product of the same vendor.

The protocol used by SMP is not documented. The only way to access it is via the vendor own Windows software management.

Decoding the protocol is out of question.


How convert eight hex characters to uint32_t using strtol() function? I want to control 4 pins using hexa code like this ff00ff00 (255, 0, 255, 0).

strtol() function works fine with three pins like 00ff00, but when i add two extra caracters to &payload[1] variable like this ff00ff00.
((rgba >> 24) & 0xFF) is equal to 127 when it should be 255.
How to make this work?

each analog pin should be set from 0 to 255

    analogWrite(LED_WHITE,  ((rgba >> 24) & 0xFF));
    analogWrite(LED_RED,    ((rgba >> 16) & 0xFF));
    analogWrite(LED_GREEN,  ((rgba >> 8) & 0xFF));
    analogWrite(LED_BLUE,   ((rgba >> 0) & 0xFF));

    uint32_t rgba = (uint32_t) strtol((const char *) &payload[1], NULL, 16);

The function strtol() is not able to convert numbers that are larger than LONG_MAX and smaller than LONG_MIN as it uses signed numbers.

You should use the function strtoul() instead (for unsigned long integers).

Cheers!


Recovering from lost USB connection (Leonardo to Raspberry Pi) I have several Arduino Leonardos connected to a Raspberry Pi (running Ubuntu) via USB. They appear as /dev/ttyACM0, /dev/ttyACM1, etc.

Occasionally, one will disappear and even pressing the Arduino's reset button won't bring it back. Is there any way to "refresh" or "reinitialize" the ttyACM* devices to make them reappear without having to reboot the Raspberry Pi?

The USB devices are created dynamically. You might find this question and answer from the SE Raspberry Pi helpful: How to force rescan of USB serial devices?.

You can use the dmesg(8) command on the Pi to see the messages generated by the USB sub-system. Watch the output to see if there are errors associated with the Arduino dropping off the bus. This is what the output will look like (roughly, this is from an Uno connected to a Raspbian system), note the last line which is a disconnect from unplugging the Uno from the Pi. Resetting the Uno did not do anything that the Pi saw. I would guess that that is because the reset button on the Uno doesn't reset the 16U2 (the processor handling the USB port).

[  459.936719] usb 1-1.3: new full-speed USB device number 5 using dwc_otg
[  460.051182] usb 1-1.3: New USB device found, idVendor=2a03, idProduct=0043
[  460.051212] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[  460.051229] usb 1-1.3: Product: Arduino Uno
[  460.051245] usb 1-1.3: Manufacturer: Arduino Srl
[  460.051262] usb 1-1.3: SerialNumber: 75431343334351F061E2
[  460.088018] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device
[  460.089250] usbcore: registered new interface driver cdc_acm
[  460.089270] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
[  534.212365] usb 1-1.3: USB disconnect, device number 5

From reading that question and its answers it appears that some versions of the Leonardo may have problems that can cause this behavior.

Another thing that might be worth looking into is the power supply for the Leonardos. If they are being powered by the Pi through the USB interface that might be pushing the capability of the Pi to provide power.


How can an Arduino do multiple actions in parallel without interfering with each other? I am working with my son (9) and we are having a great time learning. But, we've run into a problem and could use your help.

We have two separate loops that we want to run without interfering with the other. Currently we have two LEDs that are blinking in a sequence that has delays built in to keep them on/off.

We also have a Photocell circuit that turns another LED on/off depending on the light.

The problem is, the photocell circuit is lagging 1/2 second due to the light sequence from the other loop.

How do we fix this?

// this is declans photo cell and led program

const int photoCell    =  0;  // photo cell variable
const int ledLightButt = 11;  // Led light variable assignment

int lightCal;                 // idk what dis iz
int lightVal;                 // this is the reading from photo cell I think

void setup() {
    pinMode(13, OUTPUT);
    pinMode(12, OUTPUT);

    pinMode(ledLightButt, OUTPUT);
    lightCal = analogRead(photoCell);
}

void loop() {

    lightVal = analogRead(photoCell);

    if (lightVal < lightCal - 50) {
        digitalWrite(ledLightButt, HIGH);
    }
    else {
        digitalWrite(ledLightButt, LOW);
    }

    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
    delay(250);

    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
    delay(250);

}

The root of this behavior is that when the program runs delay() function - nothing else could run (digitalwrites, checks, conditions, etc.) until the delay() time is passed.

The effective solution for this is avioding the delay() function, and getting the same results (without the side-effect) using timers (like millis()) or other ways.

Googling "How to avoid delay()" will give you lot of information about how-to do it, one example can be found here:
Arduino Playground - How and Why to avoid delay() function.

Good luck with that, and enjoy your programming experience!


Why isn't there bus contention on the MISO line during SPI-based programming? Consider this image from sparkfun:

Let's say I have this setup, a master and n slaves, plus a programmer connected to the SPI lines.

When I program the master (Arduino), the Arduino is reset. This means that all the data pins go low.

Since SS is active low, all the SS pins on the slaves go active.

I believe this means that all the slaves start driving the same MISO line (blue arrow from slaves to master), either high or low.

Doesn't this result in bus contention on that line? If not, what's the mechanism that prevents bus contention from happening?

Yes, you can get SPI bus contention when using multiple SPI slave devices. It is up to you, the designer, to ensure that each SPI slave device has its chip select (CS or SS) asserted only when no other devices are driving MISO. Normally that is achieved by:

initialize all of the CS pins high (inactive) during setup
in the code that accesses SPI device #1,

assert SPI device #1 CS1 low (active)
perform SPI transfers on SPI device #1
release SPI device #1 CS1 high (inactive)

in the code that accesses SPI device #2,

assert SPI device #2 CS2 low (active)
perform SPI transfers on SPI device #1
release SPI device #2 CS2 high (inactive)

SPI bus contention can also occur during device programming (loading the bootloader or firmware image), if there is an attached SPI slave device, and its chip select (SS) is not pulled inactive by a pullup resistor.

I had a problem with this on one of my designs a few weeks ago. I was trying to burn the bootloader into some blank ATmega328-AU chips post-assembly, and my device programmer wasn't able to successfully program the chips because my one slave device had its chip select connected only to an ATmega328 pin.

I had previously breadboarded this design using an Arduino Pro Mini board, and it was working fine; but when I moved to first prototype PCB there was bus contention on MISO -- the blank ATmega328 wasn't driving the slave device's chip select high or low, but it floated low (active), causing MISO contention.

My solution (workaround) was temporarily contacting the chip-select to VDD 3.3V through a 10kohm resistor. This made my SPI slave device inactive, allowing the device programmer to successfully load the bootloader.

I think there would be no harm in leaving the pullup resistor on chip select (since it's an active-low signal), but it was only really necessary when using the device programmer. After I had the prototype boards initialized with the bootloader image, I was subsequently able to load firmware images as usual.

(One minor unrelated issue was that my assembler purchased ATmega328-AU when I had specified ATmega328P-AU -- they are almost the same, and it doesn't make a difference for my application, but it was annoying that I had to use a slightly different command line argument than then one I used with the Arduino Pro Mini board.)


When Raspberry Pi is preferred over Arduino We are doing some projects in class. One of my friends is doing a weather and humidity station using raspberry Pi with a couple of sensors and LCD. I have a little experience in Arduino. So I asked her, why doesn't she do it using an Arduino? She said Pi is more 'powerful'. In what aspects, is it more powerful than Arduino? When should I go for Raspberry Pi over Arduino?

The claim that the Pi is more "powerful" is a bit misleading. What does "powerful" really mean? And is it relevant to making a weather station?

I made a temperature and humidity sensor as described here using an Atmega328P (the processor that is in the Arduino Uno). The estimated average power consumption is 42 µA which has allowed it to run from 3 x AA batteries for a couple of years before they needed replacing. I think you'll find that the Pi with its more "powerful" processor and extra components would not be able to do that.

I see from a quick search that the Pi consumes 80 mA to 240 mA when idle (depending on the model). This would make a Pi-powered weather station eat through batteries 2000 times as quickly. Perhaps that would be a consideration.

The Pi is really a Unix PC on a board, which means it goes through the normal boot sequence with a possibility of errors occurring during booting. To see what those errors are you need to connect up a keyboard and screen, or connect via a network to it from another PC.

I don't want to run down the Pi - it's a nice cheap Unix computer on a small board. But the Arduinos (many of them) are somewhat simpler to program. You don't need to worry about the operating system for a start. For a weather station, taking a reading every 5 minutes, who cares if the Pi can take the reading "50 times faster"?

Speed of recovery from sleep

I have an answer about letting serial data wake an Arduino - after some experimenting I was able to get the Atmega328P to wake from its deepest sleep (260 nA - yes 0.260 µA!) within 6 clock cycles (750 ns). I doubt you could achieve that on the Pi, either the low power consumption, or waking up in under a microsecond.

This was fast enough to detect the start bit in serial data at 9600 baud, process the start bit, and then the rest of the incoming byte without losing data.


What will happen if I set ARef to 3.3V and try to use adc connected to 5V What will happen, if I try to measure voltage higher than ARef?
For example, my ref is 3.3V, and I try to measure 4.5V. Will it damage adc?

The datasheet of the Atmega328P does not give a direct answer to this, but

  Single ended channels that exceed V REF will result in codes close to
  0x3FF.

(Datasheet Chapter 24.5.2)

sounds, as it would not destroy the ADC, but only result in a value very close to the maximum. I also found another side, where this is also stated. They linked to the Arduino forum, where a similar question is handled in this thread.

So all in all it should be save to provide more than the reference voltage at the ADC pins, as long as it does not exceed the supply voltage (for the UNO 5V).

As Majenko pointed out in his answer, the datasheet states, that it is safe to provide VCC+0.5V at any pin (except for reset). I just wasn't sure, if this can easily be applied to this special hardware, but it seems, that it can.


What is the difference between python and arduino programming? I am a Python programmer and want to learn Arduino programming so want to know what are the main differences between Python and Arduino C++ programming?

Is Arduino C++ more complex than Python programming?
Are there any similarities that will help me?
Are there any formatting  restrictions like in Python?
Etc...

According to this page(printing hello), Aurdino programming looks easy to me.

Arduino uses a language that is derived from Processing, which looks like C++.

Python is a different language, although both have similarities (both Object Oriented for example).

What is 'complex' depends on what your background is. C++ is in general more complex than Arduino, but most people using Arduino program in C++, so most examples can be found in C++, which makes support from other users easier.

If you are new to programming, I suggest using the 'standard' Arduino IDE.

To be complete, Arduino is not a programming language, it is a platform. In general, every language can be used to write Arduino code, but only a few have compilers for creating Arduino (machine) code.


Problem with Arduino driver! Port option not visible. How to resolve it? I am not able to upload sketch because my Windows 8.1 PC is not able to recognise it. It used to work fine but suddenly my driver disappeared from my device manager and no light is shown on the Arduino uno led also.

I tried to uninstall and install the Arduino IDE again but still didn't work.

Note:- whenever I connect the USB cable to my PC, I see a dim light glowing for few milli seconds.

Update:- Also my Arduino board is not dead since it worked when connected to other pc but not working with my windows pc.

What could be the problem? How do I install the port driver back?

Sometimes Windows will disable a given USB port if it think's the attached device is malfunctioning.  Try using a different USB port on your PC.  If that does't work try
rebooting your PC.


Wait for serial input otherwise start with preconfigured options I need to input config parameters from serial input. After a period (1 min) with no input I would like the program to start with preconfigured parameters.

Currently in the loop() section I use Serial.available, which stops until it receives new data.

How can I implement that?

void loop() {
  // read serial input
  if (Serial.available() > 0) {
    inChar = (char)Serial.read();
    inputString += inChar;

The Serial.available function does NOT block execution. If you want to try, upload this

unsigned long lastTime;
#define LED1 5
#define LED2 13

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

void loop() {
  if (Serial.available() > 0)
  {
    Serial.read();
    digitalWrite(LED1, !digitalRead(LED1));
  }
  if ((millis() - lastTime) > 500)
  {
    lastTime = millis();
    digitalWrite(LED2, !digitalRead(LED2));
  }
}

You will see led on pin 13 to turn on and off even if the serial port buffer is empty.

Maybe your problem is somewhere else. Anyway what you want can be solved this way:

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

    // Wait for one minute - millis is started at 0, so there's no
    // need to store the initial value of the waiting time
    boolean receivedConfiguration = false;
    while ((!receivedConfiguration) && (millis() < 60000))
    {
        if (Serial.available() > 0)
        {
            // There's some data; parse it

            if (__receivedDataIsComplete)
            {
                __myConfiguration = __configurationFromSerial;

                receivedConfiguration = true;
            }
        }
    }
    if (!receivedConfiguration)
    {
        __myConfiguration = __defaultConfiguration;
    }
}

In this setup function, the microcontroller waits for one minute. If it receives the data it ends the waiting time and uses that configuration, otherwise restores the default one and goes on. In your loop you can then use the configuration.

Please note that the variables starting with a double underscore (__) are false variables, you will have to fill with the proper code and/or variables


Arduino Serial.println() keeps transmitting data even when conditions are imposed I am using Arduino UNO and a bluetooth module.  I have used an if condition so that Serial.println() happens only once but it keeps on printing.  Please help. Below is the code.

//Begin CODE
char str;
String fnal;
int i;

void setup()
{
  Serial.begin(9600);
  fnal="";
  i=0;
}

void loop()
{
  i++;
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

According to this code # and 1 should be printed only once but in serial monitor the printing continues infinitely.

If you had put a Serial.print inside loop you would have seen the problem. Debugging displays are very helpful. Like this:

void loop()
{
  i++;
  Serial.println (i);   // <---- debugging
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

Since you are adding 1 to i each time around the loop, how long do you think it will go before i overflows? It will go up and up, get to 32767 and then become -32768, and then count back to 0. During that time it will be less than 2, and it will do the printing of "#1".


I2C MCP4725 DAC connection speed I'm trying to use the MCP4725 DAC from Adafruit (https://www.adafruit.com/product/935) to output some waveforms over a frequency range up to about 50kHz. At the moment, I'm simply sending values to the DAC via the Wire library and through the DAC's onboard library. It appears that the values are only being sent at 7kHz. Is this due to the added weight of the libraries I'm using? Is there some way I can increase the transmission speed?

You cannot get 50kYz from a DAC running on I2C on an Arduino.

The maximum rate for I2C (if you select fast mode) is 400kbps. Setting the DAC takes three bytes plus start/stop/ack bits (total 29 bits).

At 400kbps that equates to (400000/29) 13793 settings per second.

Add to that the time taken to actually create and process the data, running the instructions to do everything, you can expect about half that - which is the 7kHz you're getting.

To get 50kHz from a DAC you really need a CODEC and run something like I2S, which you are never going to do on an Arduino.


5V Trinket only outputting 3.3V? Unless my multimeter is on the fritz, it would seem my 5V Adafruit Trinket is only outputting 3.3V when connected w/ DC power.

When connected via USB, totally fun. Full 5V. But if I disconnect that and connect a 9V wall adapter, the output of the 5V pinout is just giving me 3.3V.

Is that even possible?

I noticed the issue b/c my program wasn't running properly when connected via the DC adapter (but ran just fine via USB). So I tested the voltage and sure enough, 3.3V all around at basically every +/- connection.

Any ideas?

Unfortunately I do not have the ability to comment. What I can suggest is to look at the small 5 pin regulator and look at its markings. If the IC is marked with "QT33" then adafruit has stupidly soldered the wrong chip onto your trinket board. If it says "QT50" then the regulator is not at fault.


MIDIUSB - Why is the command put twice? Consider this function:

void noteOn(uint8_t pitch) {
  midiEventPacket_t noteOn = {0x09, 0x90 | 9, pitch, 127};
  MidiUSB.sendMIDI(noteOn);
}

midiEventPacket_t is defined as:

typedef struct
{
    uint8_t header;
    uint8_t byte1;
    uint8_t byte2;
    uint8_t byte3;
}midiEventPacket_t;

The first nibble of the first byte of a MIDI message is the command: 0x90 ["note on"] and the second nibble is the MIDI channel: 9, so what's sent over the wire should be 0x99 meaning "Note On, channel 9", with the two more bytes representing the pitch and the velocity.

My question is, why do all of the examples start with: {0x09, 0x90 | 9,? I'm not understanding the use of the struct here. Intuitively, I thought I would need: {0x90 | 9, pitch, 127, 0}. Why do all of the examples have that seemingly strange syntax?

EDIT

After getting a great explanation below, here's my new function!

void noteOn(uint8_t pitch) {
  midiEventPacket_t noteOnPacket;
  noteOnPacket.header = USB_CABLE_NUMBER | (MIDI_NOTE_ON >> 4);
  noteOnPacket.byte1 = MIDI_NOTE_ON | CHANNEL;
  noteOnPacket.byte2 = pitch;
  noteOnPacket.byte3 = MIDI_BUTTON_ON_VELOCITY;
  MidiUSB.sendMIDI(noteOnPacket);
}

From the specs:

  The first byte in each 32-bit USB-MIDI Event Packet is a Packet Header contains a Cable Number (4 bits)
  followed by a Code Index Number (4 bits). [...]

  [...]

  The Cable Number (CN) is a value ranging from 0x0 to 0xF indicating the number assignment of the
  Embedded MIDI Jack associated with the endpoint that is transferring the data. The Code Index Number
  (CIN) indicates the classification of the bytes in the MIDI_x fields. The following table summarizes these
  classifications.

  CIN | MIDI_x Size | Description

  [...]

  0x9 | 3 | Note-on

  [...]

No rationale is given why the CIN is required if the full message is also included, but it could be used for quicker routing of the event to the routine that will process it.


How do I reset an ESP8266 with an FTDI and no reset button? How do I reset an ESP8266 with an FTDI and no reset button? I assume that it has something to do with the reset pin on the ESP8266, but I cannot find a step-by-step usage of the pin online.

Pull the reset pin up by connecting it to 3.3v with a 10k ohm resistor, then to reset the ESP you temporarily ground the pin, bringing it down to 0v/GND.
I'd recommend putting in a button for that :)


Can I change Arduino program on-the-fly? I have Arduino which is programmed to do something. Is it possible that I could allow it to change behaviour by changing program on-the-fly without the need to reprogram Arduino via the computer.

What I need is to send the message via MQTT which will Arduino receive and change its behaviour by it. I managed to change the frequency of messages published or to add some new data, but what if I want to change how decisions are made. What if I want to change some Arduino code, to add some if or another state, can that be done on the fly?

Update: Changing device behaviour on the fly or after restart is acceptable. I am not strict with using arduino, nodemcu is and option. I just need a way to add new functionality to device if I need.

Replacing or modifying the existing code during run-time will require some form of uploading and over-writing the old code. This is deliberately not made straightforward or easy for these kinds of micro-controllers.

But you can change the program's strategy on the fly, if you anticipate the potential changes and include the code for each of the possibilities.

For example, write a set of functions that each embody one of the various ways of operating, and, at run-time, select which function the program should use. You can change the selection by setting a value from the keyboard or the program could sense some external trigger such as a button-press, or a temperature reading and respond by changing the selection - the value of an int, perhaps. A switch statement can use that value to call the appropriate function at the appropriate time:

uint8_t strategy = 0;           // init to the default strategy

switch( selector ){
case(1):                // has event 1 happened?
   func1();
   break;

case(2):                // has event 2 happened?
   func2();
   break;

case(3):                // has event 3 happened?
   func3();
   break;

default:                // none of the above or undefined selector value
   funcDefault();
   break;
}

This does mean that all of the code for the possible operating strategies must be included at upload-time and share the program-memory space, but unless your job is very complex, even an Uno should be capable enough.

Update:

  I need to be able to update the device with some new functionality.

There is another approach which may or may not fit in an Uno but would be doable with a Mega 2560 or other larger-RAMmed machine: interpreted code.

Define a set of operations that includes whatever you'll need to operate your external device(s): the necessary I/O operations to read your sensors and control your hardware; to make logical and/or arithmetic tests and conditionally branch or call a function based on the test result; to listen for a user-signal from the terminal (for example) and return to the arduino program. This will be the "language" in which you write your control program.
Define a concise coding scheme to specify each operation and whatever data it needs, such as reading a temperature sensor and storing the result in a named place. If your control programs won't be too complex, you can get away with pre-defining A, B, ..., Z to be data registers of some appropriate type.
In C++, write an interpreter for this new language. It's program will consist of the codes you just defined. But this code will be seen as data by the interpreter. This is the key - this pseudo-code will live in RAM, where your interpreter - a collection of C++ functions - can read and execute it, and the Arduino program can download a new one, over-write the old one, and run the interpreter again.

Caveat: Like the Greek mythological Hydra, this is a job that can grow new challenges as you address the current ones, but it is doable if you keep it simple as possible and include only what you must have to make it work.

Run-time-interpreted code can take 10 - 50 times as long to execute as a natively coded application, so anything that can be pre-coded in C++ should be. The finer and more flexible your interpreted instructions, the more expressive you can be when writing the control program, but the interpreter will be more complex to write, slower to execute, and harder to debug. Design your language to be only as flexible as it must be to allow you to write new control algorithms.

If you try to invent an entire pseudo-computer, completely flexible and capable of being programmed for any and all purposes, you'll drive yourself crazy. Whole businesses have folded after sinking money and time into inventing a new and better computer and got so bogged down they couldn't recover. Don't go that route.

Start with the grossest, least flexible operations you can live with and get that much working. Discover its limitations and address those, and only those, one at a time, until you have a sufficiently flexible system in which to control your device.