Can I run more than 2 servo motors smoothly, connecting their power to regulated limit voltage and signal wires to the digital pins of the arduino? Now my next project is going to be about Servo Motors and for that, I don't want to buy any shield or motor driver for Servos. So I have designed a circuit, to drive 12 servos at a time without any interruptions. I haven't got any Servos yet, well my order is shipped already...Keeping that aside lets head down to the connection..

The Screenshot was taken from a circuit designed by me at tinkercad.com.
Parts:

HiWatt Battery (Standard 9 volts battery blue and white coloured)

SG90 Servo Motor
(6v 400mah max)
(Resistance of each of them is 1.4kohm, when connected power and ground of multimeter)

Arduino
(Required amp is 40*12)

The circuit Explanation:

The Orange wires of servos are signal wires connected to the pins of Arduino.

A 750 ohm resistor is connected to the positive terminals of each motor, from which, voltage is regulated for the motor.

The motor grounds have been connected to the ground of the battery.

Ground of Arduino has been connected to the ground terminal of the battery. So now, ground of the battery and the Arduino is same.

All the motors are connected in parallel connections with 750 ohm resistors at the positive terminal of each motors

So now my question is, How many servos will I be able to run when I power them parallel-ly using a standard 9 volts battery (HI-WATT, Blue and white one), if no, Which will be the best battery for doing it?
I need to run 12 Servos uninteruptedly.
Thanks for your precious time....

So now my question is, How many servos will I be able to run when I power them parallel-ly using a standard 9 volts battery (HI-WATT, Blue and white one), if no, Which will be the best battery for doing it?

Unfortunately: Zero motors with your current circuit. Maybe one motor with a better circuit and the same battery. Here is the explanation.

You should ditch the standard 9V block battery. These batteries are made for low power applications (like IR remotes or smoke sensors) and cannot provide enough current for driving all those motors. They might be able to drive one servo, but still will be drained very fast. You should use a battery, that can provide much more current. Which battery you choose also depends on your other requirements. A series of AA alkaline batteries can give you enough current. Or you can directly buy a LiIon or LiPo rechargeable battery (including a fitting charger board). They can provide way enough current.

You cannot just use simple resistors as voltage regulators. That just doesn't work for loads, that can draw a changing amount of current (like a motor).

The voltage, that the motor gets, depends on the current, that the motor draws. When the motors stands still, it will draw very little current. Thus the motor is getting the full 9V in that case. As the drawn current rises, the voltage will go down, until the motor gets not enough voltage to operate correctly.
The resistor of 750 Ohm restricts the current draw of the motor. Even when we (for the sake of calculation) treat the motor as a short circuit, the maximum current through the resistor with 9V will be only 12mA, so way way lower than the 400mA, that you stated in your question. You won't be able to move the motor much with that little current.
Even if you used a smaller value, you need to be careful with the current. I guess you are using standard resistors there, which typically have a power limit of about 0.25W. These are meant for rather low current circuits. With the 400mA @ 6V, that your motors need, you are in the region of 2.4W (that is not necessary the power for the resistor, just a value for you to see the relation). You can easily burn away a little resistor that way. When you need a resistor with a higher power limit, you need to buy one, which can handle it (and these are typically multiple times the size of a standard "signal" resistor and still can get very hot, when used in the realm of their power limit).

Instead you should buy a proper voltage regulator. At that current, buy a switching buck regulator, as they are way more efficient than linear regulators. Which regulator you need to buy also depends on the voltage of the battery, that you choose. Be sure to buy a regulator, that can provide significantly more current, than we need in total for your circuit. This is important, because regulators are typically described with a maximum current, at which they already need extra measures for cooling. When you stay well below that, you can avoid thinking about fitting cooling for it.

So , will it control the motors as good as 16 channel servo drivers?

Yes, it can. Though you need to think about how you are controlling the servos on the Arduino. The standard Servo library supports up to 12 servos with one timer. When you can change the library to use 2 Timers for supporting more servos, then you have it. You could also try to search for other libraries, which support more servos, or write your own library. I would say, using the driver would be simpler. The driver does not switch the power for the servos. It has a chip, which can output 16 servo control signals and is controllable over an interface like I2C or SPI.
If you want to use such a driver is up to you. You might find it more important to have as few electronic parts as possible.


Can i send sensor data from arduino to cloud without sending it via PC I am trying to build a GPS tracker. I need to send the data from GPS sensor on the arduino uno board to cloud directly i.e. without sending it via PC or mobile.
Is it possible and if yes, HOW?

To connect to the cloud directly while the tracker is on the move, you'll need to use GSM & GPRS technology, ie. a SIM card to make a 3G/4G connection to the Internet. GSM gets you connected, GPRS does the Internet traffic. Using WiFi to connect to a router won't work since you'll soon get too far from the router.

I suggest initially investigating the SIM908 and SIM800L (there are others).

Here are 2 projects which both use the SIM908 (GSM, GPRS AND GPS):

Geolocation Tracker (GPRS + GPS) with SIM908 over Arduino and Raspberry Pi

Where is my car? Realtime GPS+GPRS Tracking of Vehicles Using Arduino

The cheaper SIM800 is also popular GPRS/GSM module (no GPS capability, but you already have that?):

QUICKSTART SIM800 (SIM800L) WITH ARDUINO

This technology is moving quickly, so you may find better options, for instance see:

Difference between SIM908 vs SIM808 modules

Hope this helps,
Regards, Geoff


Keypad as game input device? I have been trying to get a button matrix to work but im not experienced enough in programming.
I Have tried to read up but i don't know how to execute so some help would be greatly appreciated.
I want the keypad to function as a game controller of sorts. when i pres the 1 key on the keypad i want the read light to light up and only go out when i release the button. code was copied from "mstanley" on arduino forum.
Q: How do i use the Keypad.h library to get my keypad press to run one line of code when i press a button and another line when i release the button.
I Was testing with leds now, the code is identical, digitalWrite(1, HIGH); then digitalWrite(1, LOW); this can easily get exchanged for joystic.PressButton 1 and Joystick.ReleaseButton 1

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5,4,3,2}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

char holdKey;
unsigned long t_hold;

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

  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop(){
  char key = keypad.getKey();

   if (key){
     holdKey = key;
     Serial.println(key);
   }

   if (keypad.getState() == HOLD) {
      if ((millis() - t_hold) > 100 ) {
          switch (holdKey) {
              case '1':
                  digitalWrite(11, HIGH);
                  delay(200);
                  digitalWrite(11, LOW);
                  break;
              case '2':
                  digitalWrite(12, HIGH);
                  delay(200);
                  digitalWrite(12, LOW);
                  break;
              case '3':
                  digitalWrite(13, HIGH);
                  delay(200);
                  digitalWrite(13, LOW);
          }
          t_hold = millis();
      }
   }
}

How do i use the Keypad.h library to get my keypad press to run one
line of code when i press a button and another line when i release the
button

Edit 1:
void loop() {
  char key = keypad.getKey();

  if (key != NO_KEY) {
    Serial.println(key);
  }

  if (keypad.isPressed('*'))
  {
  randomr = random(10, 2000);
  Serial.println(randomr);
  }

}

From the link: https://playground.arduino.cc/Code/Keypad/ you can find all the functions supported by the Keypad library.
One relevant function is
KeyState getState()

It returns the current state of any of the keys.
The four states supported are IDLE, PRESSED, RELEASED, and HOLD.
Hence you can use this function for the keys you are interested in.
Also, if helpful consider this function as well.
setHoldTime(unsigned int time)

Set the number of milliseconds the user will have to hold a button until the HOLD state is triggered.

You can find the keypad.h library in action here. I motivate you to also try the code with this online Arduino emulator
you already have a builtin function defined to get the status of the key pressed
void loop() {
  char key = keypad.getKey();

  if (key != NO_KEY) {
    Serial.println(key);
  }
}

I have a poorly taken screenshot for the same for your quick reference.
Original Arduino emulator link: (you can play with the logic)

https://wokwi.com/playground/keypad

Disclosure: We work at wokwi.com, to create interesting tools and libraries for the Arduino community
https://github.com/wokwi
for a more free demonstration of the libraries:
https://github.com/wokwi/arduino-libraries


Controlling a digital 12V addressable RGB led strip with Arduino? I have a 12V addressable RGB strip that I want to control with an Arduino, the chips are ws2811s, is there a way to do this as the Arduino is 5V and 3.3V?

The only signal you need to worry about is DIN (data in) which is normally 5V from an Arduino. Use that to switch a MOSFET or transistor to convert the digital pulses to 12V. In other words, the Arduino switches the transistor, the transistor outputs 0 or 12 V.

Judging by this link you still just send 5V digital switching to the strip.

  The data signal never needs to be 12 volts. The 12 volt pixels all drop the voltage down to about 5 volts to operate the chip. Usually just a resistor and a zener diode, sometimes just a resistor.

In other words, connect the "power" pin to +12V, and the ground pin to Gnd from your power supply.

Connect the Din (data in) to your Arduino pin directly. Of course, also connect the Arduino ground to the ground pin.

Also see this Youtube video. On the comments he says:

  These 12v WS2811 "pixels" still use 5v signalling. You simply connect the 12v source power directly to the strip, tie the ground to the arduino and then treat them as if they were a 5v strip.


Overflow in bit calculation I'm having a double buffer to write data from sensors to SD card. inBuf points to the buffer that are written into (from sensors). The other buffer write data to SD card.

char buffer[2][BUFLEN];
volatile int inBuf = 0;

inBuf = 1 - inBuf;

However, the update of inBuf does not work. Firstly inBuf is 0, and after that inBuf becomes 32!!! I tried different data types: boolean, uint8_t, int and the results are the same.

How could I fix this problem? Also, what datatype should I use for inBuf, as it's really just one bit?

I ended up using the following:

inBuf = inBuf? 0:1;

but seems really complicated and unnecessary.

EDITS:
Sorry for was not being clear previously. It turns out that I had an overflow in the code:

char buffer[2][BUFLEN];
volatile uint16_t bufferCounter;
volatile int inBuf = 0;
volatile bool outBufHasData = false;

Inside the interrupt handler:

if (bufferCounter < BUFLEN - SAMPLESIZEINCHAR + 1) {
  epoch = now();
  proximity = vcnl.readProximity();
  ambientLight = vcnl.readAmbient();

  // format to be fixed length as opposed to variable length
  // sacrifice overhead in written data with simpler and more robust code
  // since we know exactly how much to increment after each write
  int written = snprintf(&buffer[inBuf][bufferCounter], SAMPLESIZEINCHAR,
        "%10lu,%5d,%5d\n",
        epoch, proximity, ambientLight);

  if (written > 0) {
    bufferCounter += written;
  }
} else {
  // only switch buffer if out buffer is written to SD card
  if (!outBufHasData) {
    inBuf = inBuf? 0:1;
    bufferCounter = 0;
    outBufHasData = true;
  }
}

Then in the for loop, where the buffer is written to SD card when the buffer is full:

  if (outBufHasData) {
    myFile.print(buffer[1 - inBuf]);
    myFile.close();
    outBufHasData = false;
  }

Previously, I had bufferCounter < BUFLEN !! Thus I was writing over the memory of the buffer, and spill into bufferCounter and inBuf. That's why I got the value 32 of inBuf, which is the ASCII code of space. Mystery resolved!!

If you want a variable to be 'yes' and 'no' or perhaps '0' and '1', then you can use a boolean which is 'true' or 'false'. With a boolean you can use logic operators:

boolean dataReady = false;
dataReady = !dataReady;
if( dataReady) ...

A boolean on a 8-bit AVR chip (Arduino Uno,Leonardo,Nano,Mega) is 8 bit. You could also use a byte and make it 0 or 1.

A 8-bit variable is often used when a interrupt routine sets a flag. By making that flag only 8 bit and volatile, it can be used in the loop function as well without the need to disable the interrupts. Reading and writing a 8 bit variable can not be interrupted by an interrupt routine.

Using 8 bits when only 1 bit is needed is normal. You don't have to worry about that.

When you need hundreds of 1 bit variables, then it is possible to select each bit with macro's or a lot #define to select each bit. This is almost never used in normal code, but almost always used for the registers of a sensor.
And last but not least: a struct with bit fields packs the bits. That can be handy sometimes.


Esp32 not connect with WiFi I'm trying to connect WiFi at home in my esp32 but in the serial monitor shows a looping connecting to WiFi but never connect. look this
The link that I followed.
To my application. I want to connect a DHT11 sensor and to communicated with node-red. Unfortunately, My esp32 doesn't connect with WiFi.
    // Projeto Curto Circuito – ESP32: DHT11 Teste
#include <WiFi.h>
#include "DHT.h" // Inclui a biblioteca DHT
#define DHTPIN 14 // Define que OUT será conectado em D14
#define DHTTYPE DHT11 // Define o modelo de sensor como DHT 22  // DHT irá interpretar os valores de leitura do pino de acordo com o tipo de sensor
DHT dht(DHTPIN, DHTTYPE);
char* ssid = "Filipe";
const char* password =  "1234512345";
void setup()
{

 Serial.begin(9600); // Taxa de transmissão 9600 dBs
WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 dht.begin(); // Taxa de transmissão do sensor

}
 void loop()
{
 delay(2000); // Intervalo de 2 segundos entre as leituras // Indica a Umidade (%)
 float h = dht.readHumidity();
 float t = dht.readTemperature();
 Serial.print("Umidade: ");
 Serial.print(h);
 Serial.println(" %\t");
 Serial.println("");
 Serial.print("Temperatura: ");
 Serial.print(t);
 Serial.println(" *C ");
  Serial.println("");
}

I hope somebody can help me.
I'll be so glad with your contribution.

Solution from the original poster :

Hello everyone, I did a test in another laptop and it worked. I didn't know what happened with my laptop . Look this new image I needed to change the number Serial.begin to 9600. Now everything is working. Thanks for your help and have a nice week.


How to decrease a variable every second I am trying to count down the variable "bankValue" with a certain costfactor
The code I tried will perfectly count down the bankValue..but..

#define INTERVAL_MESSAGE1 1000

unsigned long time_1 = 0;

const float CostFactor = 1.0;
float bankValue = 10.00;
const float CostButton1 = 0.004167;

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

void loop() {
    if(millis() >= time_1 + INTERVAL_MESSAGE1){
        bankValue = bankValue - (CostButton1 * CostFactor);
        time_1 +=INTERVAL_MESSAGE1;
        print_time(time_1);
        Serial.print("€");
        Serial.println(bankValue);
    }
   }

I want this the use in an if.
IF button1 is pressed then bankValue will be decreased by a costfactor every second.

I tried this in an if

  if(Pushed == HIGH){
    if(Pushed != StatePushed){
    Serial.println("Button1 OFF");
    }

    digitalWrite(relayPin, LOW);
  }else{
    if(Pushed != StatePushed){
    Serial.println("Button1 ON");
    }
                if(millis() >= time_1 + INTERVAL_MESSAGE1){
        bankValue = bankValue - (Button1Value * CostFactor);
        time_1 +=INTERVAL_MESSAGE1;
        print_time(time_1);
        Serial.print("€");
        Serial.println(bankValue);
        }
    digitalWrite(relayPin, HIGH);
     }

If the button is pressed, bankValue will decrease.
But when the button is not active....the millis timer keeps on running.
When switching on the button again, I see the bankValue decrease rapidly and not every second.

So the main question:
How can I decrease a variable every second when a button is active.

Your basic main problem is that you don't know when the button was pressed.  Your timing algorithm always works from the "last time the value was decremented" - and that could be hours ago.  When you press the button the difference between millis() and time_1 could be massive, and it has to count up one second at a time until time_1 passes millis().

What you really need to do is separate out the button from the action. That makes it easier to manage.  You need to find the times when the button transitions from HIGH to LOW (pressed) and from LOW to HIGH (released). You're almost doing that right now, but not quite.  Then when you find the moment of being pressed you can say "From this moment forth you shall count."

For example you might change the first part of your code to be:

if (Pushed != StatePushed) {
    StatePushed = Pushed; // Remember the current state for the next time round
    if (StatePushed == HIGH) { // Released
        Serial.println("Button1 OFF");
    } else { // Pressed
        Serial.println("Button1 ON");
        time_1 = millis(); // Remember what the time is right now
    }
}

That then is a single atomic operation and you can now at any time examine StatePressed to see if the button is pressed or not, and also at the moment of pressing time_1 is set to the current millis() value, so you now know when the button was pressed.

Now you can add your second part using StatePressed as the trigger:

if (StatePressed == LOW) { // Button pressed
    if(millis() >= time_1 + INTERVAL_MESSAGE1){
        bankValue = bankValue - (Button1Value * CostFactor);
        time_1 +=INTERVAL_MESSAGE1;
        print_time(time_1);
        Serial.print("€");
        Serial.println(bankValue);
    }
}

However your method of comparing the time is not good. It doesn't handle the millis rollover problem.  Instead you should be using something more like:

if (millis() - time_1 >= INTERVAL_MESSAGE1) {
    time_1 = millis();
    ... etc ...
}


Unplanned behavior with two power sources I'm trying to control this servo, and whenever I leave the Uno connected, via USB, to the PC, most of the time the servo barely moves, and sometimes jitters.

simulate this circuit – Schematic created using CircuitLab

I connected the oscilloscope to try to understand / solve my problem, and I see that the signal I send is the same whether or not the USB is connected. I measured the voltage over the 5V/GND and it's constant at 5V and doesn't dip/spikes. I tried with a pull-down resistor on the signal pin (don't know if it's a good idea) and it doesn't change anything.

If I unplug the battery, but keep the USB connected, the servo stays immobile, but I figure that's because the Arduino can't feed a servo, hence why I wanted to use an external power for it. The second power source is a PowerBoost 1000C with a LiPo battery.

As soon as I unplug the USB port, the servo just starts moving properly, so I figured it must be interference of some kind. I saw the accepted answer to this question and it has me doubt whether I should use a battery while it's plugged in, but surely there is a way. Would I kind of need to connect the GND of my circuit to the GND wire of the USB before it actually enters the Arduino?

I didn't post the code as it's basically just the swipe demo from the website, and because it works when on battery only.

Regards

Beginner error: As stated in the diagram, I connected the external source of power to the 5V pin, while it should have been connected to the Vin pin. /ashame


Slave SPI does not work I am trying to use both an SRAM (23LC1024) and SD card reader on an SPI bus.

My connections (for SPI):

Arduino pin 11 (MOSI) -> SRAM pin 5 (SI/SIO0)
Arduino pin 12 (MISO) -> SRAM pin 2 (SO/SIO1)
Arduino pin 13 (SCK ) -> SRAM pin 6 (SCK)
Arduino pin 10        -> SRAM pin 1 (CS )

In this way, I can read data from the SRAM.

To connect the SD I connected:

SRAM pin 2 (SO/SIO1) -> SD MISO
SRAM pin 5 (SI/SIO0) -> SD MOSI
SRAM pin 6 (SCK    ) -> SD SCK
Arduino pin 9        -> SD CS

Currently the SD card works, but read-byte commands to the SRAM always gives the same (wrong) value.

If I remove the wire between SRAM pin 2 and SD MISO the SRAM gives correct values, but the SD card does not have a MISO connection and seems to always return the same data (but still functions).

I also tried to first make the connections from the Arduino to the SD and than to the SRAM (but same result, not working).

What am I doing wrong?

Update: The problem is solved, however I do not understand why. I reconnected all pins, removed the shield to access the SRAM directly which worked. Than I put the shield back on (and moving the pins back) ... maybe it was something stupid that one pin did not have good contact. I'm sorry for the inconvenience.

New question (related):

Now it works with the Data logger shield, but not with the (cheap) SD reader breakout cards.

However, my eventual solution needs more proto space than is available on the Data logger shield.... do I really need to use a complete shield (and later the Arduino Mega), and a Mega proto shield ... that will be a big box.
While for the data logger, I don't need the RTC neither.

It doesn't sound like you are doing anything wrong as such, it all sounds fine.

However SD cards, certainly some cheap ones, don't like to play nicely with other devices on a shared bus. Also some SD card adapters with level shifting don't play nicely.

By not playing nicely I mean tri-stating the MISO line in a timely fashion (or at all in some cases) which stops any data getting out of other devices, and can even cause damage in some cases.

You should check out the level shifting on the SD card adapter to see if it has tri-stating control of MISO (if it is shifting that line, not all do), try other brands of SD cards, and maybe add your own tri-state buffer to the SD card signals.


How can I pass a char array as the parameter to a function? I am creating a menu for adjusting system variables.

The menu is made up of pointers like so:

char* options4[] = {"hMin1", "hMax1", "refr1", "fSpeed1"};

I want to pass the selected string as the parameter for an 'adjust' function for use in some conditional logic and for display on a HCMAX7219 7 segment display. Here's what I've got:

int option = 0;
float variable = 82.0;

if(Serial.available() > 0) {
  key = Serial.read();
  if(key == back) {
    return;
  } else if(key == fwd) {
    float newVar = adjust(String(options4[option%4]), variable);
  } else if(key == down) {
    option++;
  } else if(key == up) {
    option--;
  }
}

float adjust(char* str, float var) {
  ...do some stuff...
  display.print7Seg(str, 8);
  EDIT: forgot this call..
  display.print7Seg(var, 1, 4);
  ...do stuff to var...
  return var;
}

The library function takes (char[] TextString, unsigned int Offset) as it's parameters.

EDIT: the library also has functions print7Seg(long number, byte decimalPlace, unsigned int Offset) and print7Seg(long number, unsigned int Offset)

Now I'm new to pointers, but I can see that I am passing a pointer to my adjust function, and expecting it to dig out a char array from memory. I can't see any problems with that, though I may be missing something. When I try to compile, the IDE just crashes with exit status 84; so no debug info.

Am I going about this the wrong way?

There are one or two things missing in your code. Where is setup() and loop()? Or is it just a snippet?

But answer to the question first. This is not right:

newVar = adjust(String(options4[option%4]), variable);

Should be:

newVar = adjust(options4[option%4], variable);

You want to index the vector of strings and pass one of the elements to the function.

Cheers!


How to connect Mg995 and arduino nano since nano can only output 40mA at max? Datasheet for Mg995 shows:

Current draw at idle 10MA
No load operating current draw 170MA
Stall current draw 1200MA

Maximum current that an arduino nano can output is 40mA.
So, what intermediary component should I use to make the connection between the two work?

The servo has 3 Pins to connect: Vcc, GND and PWM. The power, which actually drives the servo is drawn through the power lines Vcc and GND. The PWM pin, which is connected to an Arduino output pin, does not draw mich current. It is only for the PWM (-like pulsed) signal, which tells the servos driver, which angle is requested. But you should not power the servo through the Arduino. You have to connect it directly to a power supply with the correct voltage, because some parts of the Arduino can get fried, when drawing too much current through it.

So all in all: Connect the PWM pin directly to an Arduino output pin and supply the power from the source directly to the servo, not going through the Arduino.


Alternatives to Wire library for I2C I am looking for (reasonably easy to use and well tested) alternatives to the Wire library. Wire works very well, but: I only need the Arduino to act as I2C master and the Wire library seems to be a real waste of resources:

My goal is to send out data en bloc (e.g. 32 or 64 bytes). This data is already sitting in an array in SRAM. Now when you use the Wire library, you call the TwoWire::write function which copies your data into a 2nd buffer. Afterwards, Wire makes use of the TWI library where twi_writeTo copies the data again into a 3rd buffer. That's a bit clunky, isn't it?

I have seen the DSSCircuits / I2C-Master-Library but I am not sure how mature it is because there hasn't been any commit after the initial commit which is 3 years old now.

I don't see any objection to using DSS Circuits I2C Master Library.

It may not have been updated for a couple of years, but if it works it doesn't need to be. It's not as if libraries for micro-controllers have to support new printer drivers, video drivers, etc.

If it works, it works.

The chip hasn't changed, and the only real reason for updates these days is if the IDE changes (or the compiler changes) in such a way that it introduces compile errors. Such things have happened fairly recently with things like PROGMEM having tighter rules, for example.


Code for activating a led after 2 minutes and will blink after 30 seconds interval Can anyone help me to build a code which will activate a LED after 2 minutes when the power supply is cut off and blink that LED after a time interval of 30 seconds.
I want to import the code on Arduino-Uno.

I will power the Arduino with cell and assign two pins as sensor if they are connected to each other than every this is fine if they are cut the Arduino will blink the LED after 2 minutes and will keep blinking at 30 seconds interval

Use a commonly available USB power pack re-charging from mains and powering the Arduino.  Use a light source directly powered by main and optically couple that to an Arduino.  There are plenty of examples on the web where an Arduino is used to detect light.  Once triggered, write some additional code to blink the led.  Since you are not doing anything other than timing, you can use the delay Arduino library to time events.


A more elegant way to deal with timers without using delay()? I am looking for a more elegant way to write a function that performs timer-based tasks as in the case of the code below, which essentially collects 5 sample values from a microphone module over a given period of time and then computes their average. It is important that it does not use the delay() function because other tasks are supposed to run in the background which should not be affected by the delay.

  int sensorPin = A0;
  int ledPin = 13; //  pin for the LED
  int sensorValue = 0; // variable to store the value coming from the sensor
  unsigned long timer;
  int interv = 50;
  unsigned long sampleArray[] = {0, 0, 0, 0 , 0};
  unsigned long millisaver;

  void setup ()
  {
    pinMode (ledPin, OUTPUT);
    Serial.begin (9600);

  }

  void loop ()
  {

    if (millis() > 2000) {
      if (millis() < 2050) {
        millisaver = millis();
        timer = (int) millisaver;
        Serial.println(timer);
      }
      if ( millis() > timer && millis() < timer + interv ) {
        sampleArray[0] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv && millis() < timer + interv*2 ) {
        sampleArray[1] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv*2 && millis() < timer + interv*3 ) {
        sampleArray[2] = sensorValue = analogRead (sensorPin);

      }
      else if ( millis() > timer+interv*3 && millis() < timer + interv*4 ) {
        sampleArray[3] = sensorValue = analogRead (sensorPin);

      }
      else if ( millis() > timer+interv*4 && millis() < timer + interv*5 ) {
        sampleArray[4] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv*5) {
        unsigned long averageVal = (sampleArray[0] + sampleArray[1] + sampleArray[2] +sampleArray[3] + sampleArray[4])/5 ;
        Serial.println(averageVal);
        millisaver = millis();
        timer = (int) millisaver;
      }
    }
  }

For excact timing there is feature called ADC Auto Trigger mode. For example millis() are usually counted by timer 0 overflow (on AVR based Arduinos) every 1024us (I suppose it's because of PWM - otherwise it could be set exactly to 1ms). So if you don't mind that little offset, you can configure
ADC with Timer 0 Overflow and use every 20 measure only.
But don't forget that analogRead on another pin changes ADC channel and you will get something else if you don't check it.

As an auto trigger source can be used one of these:

Free Running Mode
Analog Comparator
External Interrupt 0
Timer/Counter 0 Compare Match A
Timer/Counter 0 Overflow
Timer/Counter 1 Compare Match B
Timer/Counter 1 Overflow
Timer/Counter 1 Capture Event

For ATMega328 it can be something like this:

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

    // ADC setup is done by arduino framework, but it's possible to change it slightly (for ATMega328) :
    ADCSRB  = _BV(ADTS2); // ADTS2..0 = 100, Timer 0 overflow as trigger source
    ADCSRA |= _BV(ADATE); // enable auto trigger mode
    ADCSRA |= _BV(ADIF); // reset conversion interrupt flag (by writing log 1)

    analogRead(A0); // dummy read to set correct channel and to start auto trigger mode
}

int8_t sample_count = 0;
int8_t sample_index = 0;
uint16_t  samples[] = {0, 0, 0, 0, 0};
uint16_t sample_sum = 0;

void loop() {
    if (ADCSRA & _BV(ADIF)) {
        ADCSRA |= _BV(ADIF); // reset ADIF flag by writing logic 1 into it (mentioned in datasheet)
        if (++sample_count == 20) {
            sample_count = 0; // reset sample_count, as we wan't every 20th

            sample_sum -= samples[sample_index];
            samples[sample_index] = ADC; // read value
            sample_sum += samples[sample_index];

            if (++sample_index == 5) { // reset index and count and send average
                sample_index = 0;
                Serial.println(sample_sum);
            }
        }
    }
}


How to slow ADC clock speed to 1MHz on Arduino Due? I know that the ADC on the Arduino Due has a clock speed from 1 MHz to 20 MHz. I have two questions: 1. What is the default clock speed when I run a sketch, and 2. How can I change it? (I am using Arduino 1.6.4.)

The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)

You can change the prescaler (ADCSR register). Lowest scaler is 2, so it can never run at 20mHz. Also Atmel recommends a max ADC clock of 1MHz.

Arduino sets the ADC clock to 125 KHz (prescaler of 128)

So to match Arduino, you should select a prescaler of 8 ( set bits ADPS1 and ADPS0)


Arduino Due: multiple TCS sensors I am trying to run 2 TCS3200’s from one Arduino Due. Next, I must increase to 4 sensors. I need to read the data from the 2 digital pins but how do I read both within the same loop rather than in series to save time. The code reading one sensor tasoOutPin1 (pin 10) works but why can’t I place the second read command int detectColor(int taosOutPin2) before the { symbol?

int detectColor(int taosOutPin1) {

float white1 = colorRead(taosOutPin1,0,1);
float red1 = colorRead(taosOutPin1,1,1);
float blue1 = colorRead(taosOutPin1,2,1);
float green1 = colorRead(taosOutPin1,3,1);
}

Thanks,

Scott

Seems you have to run these serially, but not sure why it's an issue, a due is quick.

seems more programming related... 'detectColor' is a function, and this is run inside the loop i assume.

int taosOutPin1 = 10; //color detector 1
int taosOutPin2 = 2; //Pins are examples, change to actual pin...
int taosOutPin3 = 3;
int taosOutPin4 = 4; //color detector 4

typedef struct {
   float white;
   float red;
   float blue;
   float green;

} color;

void setup() {
  // put your setup code here, to run once:

}

void loop() {

color detectedColorForSensor1 = detectColor(taosOutPin1);
color detectedColorForSensor2 = detectColor(taosOutPin2);
color detectedColorForSensor3 = detectColor(taosOutPin3);
color detectedColorForSensor4 = detectColor(taosOutPin4);

Serial.print(detectedColorForSensor1.red);
Serial.print(detectedColorForSensor1.green);
Serial.print(detectedColorForSensor1.blue);
Serial.print(detectedColorForSensor1.white);

//etc for sensor 2,3,4............

}

color detectColor(int taosOutPin1) {

color detectedColor;

detectedColor.white = colorRead(taosOutPin1,0,1);
detectedColor.red = colorRead(taosOutPin1,1,1);
detectedColor.blue = colorRead(taosOutPin1,2,1);
detectedColor.green = colorRead(taosOutPin1,3,1);

return detectedColor;

}


Compile error in Ubuntu 18.04 I'm trying to compile a code to arudino pro micro, I have the right option for compiling like the port and the type of the board,but I get an error,I can't copy

This is likely a permission problem.  The user likely does not have permission to read from and write to the port created when plugging in the Arduino.  This can be temporally fixed using the following command:

sudo chmod 666 /dev/ttyACM0

However, this procedure is only temporary as the port is recreated every time the Arduino is reconnected to the computer.  And upon recreation the permissions are reset to their defaults for security reasons.

A better solution is to determine the group which the port belongs to and to add the users expected to access these connected devices to that group.

Plugin and list the port to determine its group:

ls -l /dev/ttyACM*

or

ls -l /dev/ttyUSB*

The group the ports belong to will likely be "dialout".  Add the user to that group:

usermod -a -G dialout user_name

...where user_name is replaced by the name of the user who needs access to the port.  If you don't know the name of the current user you can use this command:

whoami


Why does serial port stop sending data? I'm using an Arduino Leonardo to interface with two pressure sensors and Python on my laptop, a MackBook Pro.

I'm using arduino IDE V. 1.5.4, Python V. 2.7.6, and OSX 10.8.5.

One pressure sensor is digital, using the Wire lib, and the other is analog.

My sketch compiles, runs, and works until I try to get the data in Python using pyserial.

If I try to grab a bunch of data using the readlines method in the scrip it will only return blank data or hang, depending on the serial object timeout settings. My python code sometimes works from the repl when I initialize the serial object and wait before reading from it.  If I don't wait the serial object will only partially fill a list and then any future reads will return an empty string.  This continues even after closing the serial object and reopening it in Python, or closing the serial object in Python and then opening the Serial Monitor in the Arduino IDE.  Once the serial port stops sending, I have to reset the Leonardo in order to read new data.

I could be running into some kind of buffering problem, but if that were the case I would expect future calls to return data.  Another option is that the Wire protocol is getting stuck and halting the program.

Here's my sketch

#include <Wire.h>

int ADDRESS = 0x28;//I2C address of sensor
int REQUEST = 4;//# of bytes to request from sensor
int BAUD = 19200;//serial rate
int PRESSURE_PIN = 1;

void setup()
{
  pinMode(A1, INPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(BAUD);  // start serial for output
}

void loop()
{
  Wire.requestFrom(ADDRESS, REQUEST);    // request 6 bytes from slave device #2

  Serial.print(analogRead(PRESSURE_PIN));
  Serial.print(',');

  while(Wire.available())    // slave may send less than requested
  {
     Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
     Serial.print(',');
     Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
  }

  delay(10);
}

and here is how I read it from python

import serial

serial_port = '/dev/tty.usbmodem1a1221'
ser = serial.Serial(serial_port, 19200, timeout=0)

vals = [val.split(',')[0:2] for val in ser.readlines(1001*14)]

The Arduino forums talk the Arduino resetting when the serial port is opened. A solution as stated in the forums is to add a short delay. See if that works.
Source: http://forum.arduino.cc/index.php/topic,18371.0.html


ESP8266 does not respond after changing baud rate to 9600 I have ESP8266 WiFi module and Arduino Mega Board connected. I use external 5 to 3.3 V regulator to power up the module. Common (-ve) line on the external power source and Arduino Mega GND is connected. Then I used 1K and 2K voltage divider for WiFi module RX and TX use as same. I am sure my circuit is well works.

Then I connect RX0-RX and TX0-TX. Then i put CH-PD to 3.3v

Then I opened the Arduino IDE and upload the Blink sketch. Done.. Then I opened Serial Monitor and set baud rate to 115200. Then power up the module. It gave me a lots of garbage values and ready. Fine.

Then I downloaded the FLASH_DOWNLOAD_TOOLS_v0.9.5. configure the 0x0000, 0x1000 and 0x7c000

SPI speed = 40MHZ
SPI mode = QIO
FLASH size = 4Mbit
0x1000 = ai-thinker-0.9.5.2-9600.bin

Then O power off the module and connect GPIO0 to ground and again power on.

Then push start button. Then it downloaded to the chip. It worked. Done. Success fully uploaded. Then I again disconnected the GPIO0 and power on. Then I put AT and it results OK.

AT+GMR gives version 0.9.5 updated.done.

The problem was the module was responded for 115200 baud rate, not 9600. Then I:

AT+IPR=9600

it gives me nothing.

Now I can't communicate with it at either 115200 or 9600 baud. No respond whatever baud rate I put. Sometimes I am having same garbage values.

This is a common issue. Using the AT+IPR command seems to brick the module. Try to re-flash your module, like you did the first time. If it works, use this command: AT+UART_DEF=9600,8,1,0,0 instead to change the baud rate.


Multiple GSM shields on one Arduino I am looking for a way to listen for received text messages on multiple numbers. When I came across the Arduino and its shields, I thought to myself this might be the perfect way to do just that.

One of the modules / shields I found on the internet by watching a youtube video is the TC 35 GSM.

I have been reading multiple questions here regarding the "stacking" of shields, and the usual reply is "check what pins / if they are using the same pins". Though these questions were not GSM module specific, and did not include stacking the same shields.

So I am very curious if this is possible. Let's say I want to listen to 10 SIM cards at once for received messages, will this be possible by stacking the modules on one Arduino?

Thanks!

The data sheet for the Siemens TC35 says "The  data  interface  is  implemented  as  a  serial  asynchronous  transmitter  and  receiver conforming  to  ITU-T  RS-232  Interchange  Circuits  DCE.  It  operates  at  CMOS  level  (2.65V).
All RS-232 signals on the ZIF connector are low active."

this is actually a low-voltage  equivalent of "RS232" serial. Real RS232 uses -12V and +12V signalling for binary 0 and 1 but most modern devices work with logic levels, often inverted (e.g. 0V and ~3.3V).

Most Arduinos support in hardware only a single logic-level serial interface. A few Arduinos, like the Arduino Mega, will support up to four logic-level RS232 interfaces.

Using a software library, you can emulate a serial port over the digital IO pins but the Arduino will quickly run out of processing power if you try to emulate several RS232 interfaces.

  will this be possible by stacking the modules on one arduino?

Almost certainly not. I doubt the daughterboard ("shield") designers made provision for that. At the least you'd have to re-route the serial interface to nonstandard pins and check that the power requirements don't exceed what the Arduino can supply.

If you can find a module that communicates over I2C or SPI there might be a better chance of getting it to work.


How can I break the loop if it hasn't finished in 10 seconds? Currently I am using OneButton.h library to code  my push button project.
When I press button1, it will loop for 10sec and print TRIG, and after that it will break the loop.
However, now I want to program it where when I pressed button1, it will jump to void(singleclick) function, but right now, during the 4th seconds (anytime before 10th sec) , I pressed other button, thus Arduino will break the 10sec loop and run other function.
Thus, I need help how to make sure Arduino actively read other button and when pressed, it will break the current loop/function to other related functions.
#include <OneButton.h>

OneButton button1(2, true);
OneButton button2(3, true);
OneButton button3(4, true);
OneButton button4(5, true);

int led1=12;
int led2=11;
int led3=10;
int led4=9;

int flag;

unsigned long mode;

void setup()
{

  Serial.begin(9600);
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(led3,OUTPUT);
  pinMode(led4,OUTPUT);

  button1.attachClick(singleclick1);
  button1.attachLongPressStop(longclick);

  button2.attachClick(singleclick2);
  button3.attachClick(singleclick3);
  button4.attachClick(singleclick4);

   digitalWrite(led1,HIGH);
   digitalWrite(led2,HIGH);
   digitalWrite(led3,HIGH);
   digitalWrite(led4,HIGH);

}

void loop()
{
  button1.tick();
  delay(20);

  button2.tick();
  delay(20);

  button3.tick();
  delay(20);

  button4.tick();
  delay(20);

  Serial.println("No button");

}

void singleclick1()
{
   mode=millis();

   flag=1;

   while(flag==1)
   {
     Serial.println("button1");
     digitalWrite(led1,HIGH);
     digitalWrite(led2,LOW);
     digitalWrite(led3,LOW);
     digitalWrite(led4,LOW);

     if(millis()-mode>5000)
     {
      Serial.println("TRIG");
      flag=0;

      button2.tick();
      delay(20);

      button3.tick();
      delay(20);

      button4.tick();
      delay(20);

      return;
     }
   }
}

void singleclick2()
{
   Serial.println("button2");
   digitalWrite(led1,LOW);
   digitalWrite(led2,HIGH);
   digitalWrite(led3,LOW);
   digitalWrite(led4,LOW);
}

This is just a rough, incomplete and untested code.
void singleclick1() { startTimer = true; }      // this only sets a flag

void singleclick2() { runTimer   = false;}      // this only clears a flag

void loop() {

   button1.tick();
   button2.tick();

   if startTimer {                 // this occurs once every click 1

      mode        = millis();
      runTimer    = true;
      startTimer  = false;         // run this block only once every click 1

      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW );
      digitalWrite(led3, LOW );
      digitalWrite(led4, LOW );
   }

   unsigned long currentMillis = millis();

   if (currentMillis - mode > 10000) {
      runTimer = false;                      // 10 second timer expired
   }

   if (runTimer) {

      Serial.println("TRIG");

   }
   else {
      // optional stuff to do
   }
}


Is code in a class repeated for each instance? I haven't needed classes before in programming for Arduino, but I now have a good use case. I'm not sure I grasp how this will affect code space, though.

Currently I have a struct that holds the properties of an object, and common code that iterates over an array of 12 of that struct. It's fairly compact.

It would be cleaner to wrap the operations on the struct in a class and act on an array of 12 of that class. Essentially the current struct would become private data of the class.

Will all the code in the class be repeated in each instance, or is the compiler clever enough to avoid such repetition?

Any clarifications welcome. C++ is not my main language.

No, it is not repeated. Unless you are using templates, each method of
each class is stored only once in the compiled program. Or even not
stored at all if the optimizer notices it is not used.

Just to demystify the classes a bit, you can consider them as a kind of
“syntactic sugar” over an “object oriented” programming pattern. The
following C++ code:

class MyClass {
public:
    int aMember;
    long anotherMember;
    int aMethod(short);
};

int MyClass::aMethod(short theParameter)
{
    return aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    objects[1].aMethod(42);
}

is interpreted by the compiler as being roughly equivalent to this C
code:

typedef struct {
    int aMember;
    long anotherMember;
} MyClass;

int MyClass_aMethod(MyClass *this, short theParameter)
{
    return this->aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    MyClass_aMethod(&objects[1], 42);
}

Can you spot the differences and the similarities?


Build a timer that starts and stops timing when 2 wires are broken I need to build a timer that uses the breaking of copper strips to trigger its starting and stopping. The intention is to measure the speed of a rocket with this - it will break the first wire, starting the timer, and then break the second, stopping it.

I am using an Arduino Uno, and a couple of lengths of wire for now.

I can plug one wire into the 1st 5V power supply on the board, and the other end into one of the analog pins (AO), (and then the second wire into the 2nd 5v supply and A1) so that when it is pulled out of the pin socket, it is 'broken'. Is this the correct method to go about this, and if so, how do I tell the Arduino to look for those signals as its 'start' and 'stop' and then record the time difference accordingly?

So far, I have managed to read a signal from the wire using the Analog Read Signal tutorial on Arduino.cc (https://www.arduino.cc/en/Tutorial/AnalogReadSerial). I noted whilst watching the printed data that once the wire is removed from the pin, the voltage value slowly decreased, and held at around 290 (starting at 1023, as per the tutorial). Is this simply a side effect of not using a grounded potentiometer, but a wire?

void setup() {
  // set up comms:
  Serial.begin(9600);
}

void loop() {
  // check and read value of input:
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

I am new to Arduino, so please explain in detail, or point me to a thread that will! Thanks in advance for help!

UPDATE
Having played around with analogWrite some more, I have managed to get a situation where I can output the relative value from both A0 and A1. However, I am still struggling to make it operate as a timer.

// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

void setup() {
  Serial.begin(9600);   // set up comms
}

void loop() {
  // check and read value of input:
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);

  if (sensorValue1 < 1023) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 < 1023) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }

  Serial.println("Time: ");   // prints "Time: "
  Serial.println(totalTime);  // prints time value
    delay(1000);
}

I have also tried to convert this to use digitalRead rather than analogRead but have not had much success - I am still failing to get a time. I know my method is wrong, but have struggled to find guidance on how to correct it.

    // declare variables
boolean timingFinished = false;
unsigned long startTime, stopTime;

String strTime = "Time:";

void setup() {
  Serial.begin(9600);   // set up comms
  pinMode(7, INPUT);   // set up pin 7
  pinMode(6, INPUT);   // set up pin 6
}

void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}

You have a number of problems in your code. For one thing, you are doing a lot of printing:

void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}

At 9600 baud each byte output takes 1/960 seconds (about 1 ms). A println adds a carriage-return/linefeed to what you are printing so I estimate:

3 + 3 + 7 + 7 = 20 bytes (20 ms)

That is every time around the loop! You will soon find the output buffer filling up, and thus are limiting the rate at which you can test times to be the nearest 20 ms which makes using micros() a bit redundant. You won't get that accuracy.

Plus, the String class does dynamic memory allocation which will slow things down. Why use String at all? For example, you can print "Time" like this:

Serial.println ("Time:");

Next, this assigns not compares:

  if (sensorValue1 = HIGH) {

That statement makes sensorValue1 HIGH (always) and then tests if it is true, which it always will be. You want:

  if (sensorValue1 == HIGH) {

Finally, as mentioned by Majenko, make the inputs INPUT_PULLUP and wire the other end to ground, like this:

  pinMode(7, INPUT_PULLUP);   // set up pin 7
  pinMode(6, INPUT_PULLUP);   // set up pin 6

Edit - after amended question.

// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

You don't declare totalTime like that. It appears you want totalTime to eventually subtract startTime from stopTime.

Just declare totalTime without any calculations, and do the calculation when it is needed. eg.

// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime;

...

  if (sensorValue2 == HIGH) {
    stopTime = micros();
    totalTime = stopTime - startTime;
    Serial.print ("Time: ");
    Serial.println (totalTime);
    }  // end of second sensor tripped

Note the "==" there, without it the code thinks both sensors tripped immediately.


Why doesn't the LED turn on in this circuit? I'm experimenting with buttons and LEDs and I would like my code to change a LED's brightness once a button is pressed. I connect the LED to the PWD digital pin.

My circuit looks like this one:

This is the code I'm using:

int switchPin = 8;
int ledPin = 11;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;

void setup() {
    pinMode(switchPin, INPUT);
    pinMode(ledPin, OUTPUT);
}

boolean debounce(boolean last) {
    boolean current = digitalRead(switchPin);
    if (last != current) {
        delay(5);
        current = digitalRead(switchPin);
    }
return current;
}

void loop() {
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH) {
        ledLevel = ledLevel + 51;
    }
    lastButton = currentButton;

    if (ledLevel > 255) ledLevel = 0;
    analogWrite(ledPin, ledLevel);
}

Though, the LED never turns on, but the light on the Arduino is on. I made sure the leads of the LED were in the right spot. Why doesn't the LED turn on?

Because you don't actually have a circuit?  One side of the LED doesn't connect to anything.


Reset HC-05 from within Arduino sketch I have an HC-05 Bluetooth module attached to an Arduino Mega; the module is paired with a Raspberry Pi and fed data via a python program; there's roughly one send and one receive per second of about 35 bytes.

When I first power up the Arduino / HC-05, it flashes quickly, and then after pairing, it flashes twice every second indicating a successful pair & communication. All is good; data is flowing. Periodically (5 minutes? 3 hrs?) & unpredictably, the communication ends; I'm still trying to troubleshoot this; the python code on the RPi reports a not-helpful OSError: [Errno 5] Input/output error on the available() method of the pySerialTransfer library; though I welcome thoughts on that, I realize that question isn't for this forum.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/pi/.local/lib/python3.7/site-packages/pySerialTransfer/pySerialTransfer.py", line 416, in available
    if self.connection.in_waiting:
  File "/home/pi/.local/lib/python3.7/site-packages/serial/serialposix.py", line 467, in in_waiting
    s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
OSError: [Errno 5] Input/output error

The HC-05 module continues to flash as if it's connected, even though it is not, and even if I restart the python program, I'm unable to repair with the HC-05.  The only way I can figure out to reconnect to the HC-05 is to power the Arduino / HC-05; then I can reconnect.

So here is the question: is there to reset the HC-05 from within the Arduino sketch? I realize I could attach the VCC to a digital pin to do a full power cycle on the HC-05, but I believe the HC-05 draws on the outer limit of safe current for an Arduino (40ma); I could go thru a relay to do the disconnect, but I wonder if there's a cleaner way with fewer moving parts, or if that is indeed the best way?

Thanks for any guidance!

You could use a logic level MOSFET with low RDSon (e.g. IRLZ44) to switch the supply of the HC-05 and use a digital pin to control it.


Arduino project feasibility Question completely rewritten

Trying to assess an Arduino project feasibility. New to Arduino... but did a lot of controller programming (assembly), Roboteq (C) and Phidgets (C++) , using various kinds of motors and sensors ; and reading the Arduino documentation makes me feel confident interfacing and programming shouldn't be an issue.

However, before investing time (and some money) in the project, I thought it'd be better to ask here if Arduino is the right choice, considering

a non-latching Hall sensor is to be connected to Analog 0, analogRead() to return a [0,1023] value, used as a proximity sensor. This should be straight forward.

Question →

while the Arduino runs my program, and is still connected to the PC (USB), is it possible to synchronously or asynchronously send commands from the PC to the Arduino. I.e. can the Arduino poll if there is something coming from USB (synchronous), or is there a way for the PC via USB to have Arduino do something (asynchronously)?

Thank you.

It's perfectly doable. As Chris Stratton puts it, it's all about
implementing non-blocking serial communication:

whenever you receive a character, you store it in a buffer
whenever you have a complete command in the buffer, you process it and
reset the buffer

For a line-oriented protocol, it may look something like:

/* Process incoming characters if any. */
while (Serial.available()) {
    static char buffer[BUF_LENGTH];  // incoming command
    static int length = 0;           // command length

    int data = Serial.read();
    if (data == '\r') {              // complete command
        buffer[length] = '\0';       // terminate the string
        if (length)
            exec_command(buffer);    // process
        length = 0;                  // reset buffer
    }
    else if (length < BUF_LENGTH - 1)
        buffer[length++] = data;     // buffer incoming character
}

For a more complete example, you may want to take a look at this simple
Arduino command line interpreter. You connect a terminal
emulator to the Arduino at 9600/8N1, type the "help" command and it
displays:

mode <pin> <mode>: pinMode()
read <pin>: digitalRead()
aread <pin>: analogRead()
write <pin> <value>: digitalWrite()
awrite <pin> <value>: analogWrite()
echo <value>: set echo off (0) or on (1)

You can use it as a template, replace existing commands or add new ones
(the interpreter is just a long if ... else if ...) and – since
it's all non-blocking – add whatever you want to loop().


Arduino doesn't boot unless I short USB pin 1-2 (VCC/Data -) I've made my own AVR programmer with an Arduino Nano V3 clone. It has been working fine, but yesterday I was trying to program a faulty board that pulled too much current. Was powering via USB and my OSX laptop told me it had disabled it due to pulling too much power.

After that I couldn't power it anymore, not even from a simple phone charger. I thought I had burnt something, but when testing with a DVM I accidentally shorted pin 1 and 2 of the USB connection:

1 - (red) VDC / plus / +5V

2 - (white) Data -

Then it boots up and is powered as long as I have them connected. Without it wont start with any usb connection, laptop or phone charger. Just to show what I mean:

https://photos.app.goo.gl/rtFj6bp3j4SbuYKr1

Why is this and is there something I can do to save this Nano - it seems to be working fine when usb is shorted like this…

Would hate to have to build up another one while waiting for a new programmer from China :)

When you plug the board in, the computer enumerates it. The normal device descriptor (IIRC) requests 50mA. If you are (as you most likely are) drawing more than that then the computer is quite within its rights to turn it off.

By shorting those pins you are preventing it from enumerating, so the computer doesn't know the requested amount, so it assumes (probably) 500mA.

You can achieve the same effect by using a cable with no data wires in it.


Arduino Nano - How to add multiple sensors? Lithium battery requirements? LED requirements? I am new to arduino and need help with a couple projects I am working on. One involves the use of 2 sensors - one pulse sensor, and one vibration sensor. Both need to be plugged into the "5v" pin but there seems to be only one. Is there a way I could split the pins to add multiple sensors? Will data be taken in simultaneously, and be cross compared with each other for code execution? I dont want to use breadboaard and want to wire directly to chip.
Also, I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more? Ive seen battery regulators, and other parts people recommend, but I want to make sure it will work with just those 2 parts.
I also need to wire a multicolor LED to the board, but do I need any resistors? I see them often for others people projects, but I do not have any and am wondering if I need them.
Thanks if you can answer any of these questions. Totally new to EE

Warning: unexperienced experiments even with low voltage may result in dangerous situations. E.g. a typical 10 Ohm resistor on 5 V may get so hot that it starts burning. Make yourself familiar with basic electronics, ideally with the help of someone else who can explain it to you. That person should especially explain the safety instructions first.

Both need to be plugged into the "5v" pin but there seems to be only one.

5 Volts means that this is a voltage source. In an ideal voltage source, you can basically plug in as many components as you like.
A real world voltage source will have a power limit. So you need to find datasheets of all components: the Arduino and the sensors. You can then read how much power the Arduino can provide and you can read how much power the sensors need.
As long as the Arduino can provide more power than the sensors need, that's ok. If it can't stuff will become more complicated, since you'll need another 5 V source and find a way to connect them safely.

Is there a way I could split the pins to add multiple sensors?

One does not split pins, one connects additional wires to a pin.

Will data be taken in simultaneously, and be cross compared with each other for code execution?

The 5V pin is only a voltage source. It will not provide or receive data. You'll need another pin or even multiple other pins to send and receive data.
Sometimes you can only have one device per pin (like a digital out pin), sometimes you can have multiple devices on a few pins (like I²C, SPI, 1Wire).
Typically, you would define what you need and then buy the components so you can build it. This requires a bit of knowledge, so watch some tutorials or introduction videos first.

I dont want to use breadboaard and want to wire directly to chip.

Sorry to be that direct, but at your level of understanding, that's probably not a good idea. Build it on a breadboard first and once it works as intended, make it a soldered circuit.

I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more?

As you said your components need 5 V, a 3.7 V battery will not help you at all.
You also need to be careful with the terms: a Mah is something totally different than a mAh. Don't confuse other people by mixing Mega (millions) with milli (1/1000).
Other than that, again, read the data sheets, find out how much current each component needs and sum it up. Then divide the 1000 mAh by the value you found, e.g. 100 mA and you'll get 10 h. That's how long it will last. Maybe it's good for your purpose, maybe not. How should we know that?

I want to make sure it will work with just those 2 parts.

That's great. Just consider all the aspects written in the data sheets of the components and it'll be fine.

I also need to wire a multicolor LED to the board, but do I need any resistors?

Yes. Read the data sheet of the multicolor LED and build a voltage dividor according to the values you find.

Totally new to EE

That's probably true. Maybe you want to start at the beginning and not jump into such a complex project. Get some resistors, measure voltages, measure currents. Make an LED light up. Learn about Ohms law, you'll need it very often. Once you got familiar with the basic stuff, come back to this project.
Honestly, I think you'll destroy components if you start with "a couple of projects".


Play audio on an ESP32 or an Arduino I am in the process of making a talking robot and I have linked my ESP32 to a Google text-to-speech service. The service returns me a base64 8-bit audio response.
I need to play this audio and I can't figure out how to do it. I know that an audio playing library exist for PCM but the data that it requires is not base64.

Base64 has nothing to do with audio. It is merely a way of encapsulating binary data into ASCII text so that it can safely be included in text-based structures like JSON, or transmitted over a text-based communication channel.
There is no library to "play" base64 simply because base64 is not something you play.
First you decode the base64 text into raw 8-bit binary. It's then that data that you play through whatever library is most suitable for your hardware.
For example on the ESP32 you have the function base64_decode() available. You can read up on how to use it in this tutorial.


Cannot find COM port for Arduino after replacing Atmega328p I had mistakenly burnt my ATmega328p that was there on the Arduino UNO R3 board. So I bought a new ATmega328p-pu with Arduino UNO bootloader installed and a sample blinking LED program pre-flashed.

However when I replaced it and plugged in to the PC using the provided Arduino programmer cable, I could not find the COM port in the device manager in Windows and neither in the Arduino IDE.

I should also mention that when I put the new Atmega328p-pu into the Arduino UNO board, the LED at 13 or L did start blinking. So I am inclined to think that both the bootloader and the sample program are there. But I cannot find the required COM port.

How do I fix this?

Generally the IDE will detect one it can use, so you shouldn't need to use the Device Manager.

When you select the board type, so far, so good.

Then when you ask it to pick the port, it will present a list of ports that it has discovered that are registered in the Device Manager.

One thing you will notice is that if you have a Genuine Uno, for instance, it will list that next to the port name.

But if you are using a board (of any type) that have the CH340-type port it will show just the COM9 or whatever it finds.

If it doesn't find any ports (My laptop always detects the COM1 port on the back that I never use so in my case if that is all it finds then it is not finding any USB ports)  then jump ahead to the arrow below.

So by trying each one you will find a port that works with your board.  Or not.

I am sure you have already seen the errors it throws when you use a port that won't work for you.

----->  If you have tried all the ports listed and none works, then you are left with only a couple of possibilities:  Either the cable is bad, or the board is not responding.

Ultimately, it doesn't matter what it says in Device Manager if the IDE won't use it.

So if you can find another board and see if the cable works that would eliminate the cable as being a problem.

But if it simply will not respond then look above in the comments at what @Majenko said.

Good luck.


Can i use PL2303 USB to TTL Serial Converter Module send keystrokes using Arduino nano? If I can, which library to use (an example code will be great).
Here is the module:

No. That is serial. Just like every other USB to TTL Serial converter. The clue is in the name.
You need an Arduino with a dedicated native USB interface, like those based on the ATMega32U4 chip.
Or dedicated software on the PC that will read serial data and emulate keypresses (which is outside the scope of this website).


Explanation of code found online i found following code online, to read the value of a touch sensor... i am having difficulties understanding how the 2 second timeout on the marked line works..
 if ((touch_sensor_value (TOUCH_timeSeconds * 1000))) {
touch_sensor_value is the value read from the touch input.. and the rest?? i dont see any comparison with anything in the parenthesis, i cant figure out how this if condition is working...
#define TOUCH_timeSeconds 2
uint64_t now = millis();
unsigned long lastTrigger_TOUCH = 0;
bool startTimer_TOUCH = false;
bool buttonIsPressed = false;

int touch_sensor_value = 0;
//Mux control pins
int s0 = 26;
int s1 = 27;
int s2 = 14;
int s3 = 12;
//State array
int currentState ;
//Mux in “SIG” pin
int SIG_pin = 33; //is touch sensor
void setup()
{
pinMode(s0, OUTPUT);
pinMode(s1, OUTPUT);
pinMode(s2, OUTPUT);
pinMode(s3, OUTPUT);

digitalWrite(s0, LOW);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);

Serial.begin(115200);
Serial.println(“Multiplexing 1 Touch sensor ESP32 using CD7HC4067 MUX”);

}

void loop() {

for (int i = 0; i < 16; i ++) {
currentState = readMux(i);
touch_sensor_value = touchRead(T9);

if ((touch_sensor_value (TOUCH_timeSeconds * 1000))) {    <-----!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Serial.println(“2 Second LOCK OUT: No rapidly repeating readings”);
buttonIsPressed = false;
startTimer_TOUCH = false;
return;
}

//

}

// delay(1000);
}

int readMux(int channel) {
int controlPin[] = {s0, s1, s2, s3};

int muxChannel[16][4] = {
{0, 0, 0, 0}, //channel 0
{1, 0, 0, 0}, //channel 1
{0, 1, 0, 0}, //channel 2
{1, 1, 0, 0}, //channel 3
{0, 0, 1, 0}, //channel 4
{1, 0, 1, 0}, //channel 5
{0, 1, 1, 0}, //channel 6
{1, 1, 1, 0}, //channel 7
{0, 0, 0, 1}, //channel 8
{1, 0, 0, 1}, //channel 9
{0, 1, 0, 1}, //channel 10
{1, 1, 0, 1}, //channel 11
{0, 0, 1, 1}, //channel 12
{1, 0, 1, 1}, //channel 13
{0, 1, 1, 1}, //channel 14
{1, 1, 1, 1} //channel 15
};

//loop through the 4 sig
for (int i = 0; i < 4; i ++) {
digitalWrite(controlPin[i], muxChannel[channel][i]);
}

//read the value at the SIG pin
int val = analogRead(SIG_pin);

//return the value
return val;
}

The comment form of a blog is not an appropriate place to publish source
code, as the content-management system (Wordpress here) quite often does
some destructive transformations. For example, here:
Serial.println(“2 Second LOCK OUT: No rapidly repeating readings”);

Wordpress tried to be “helpful” and replaced the ASCII quotes (") with
typographic quotes (“ and ”), which makes the line non-compilable.
As for the line you are asking about:
if ((touch_sensor_value  (TOUCH_timeSeconds * 1000)))

it is likely missing a less-than sign (<), as those are often stripped
from user-generated content for security reasons. I don't know why some
of those signs went through the filter, maybe it has something to do
with the white space surrounding them, but this is pure guess.
Given that the code has been destructively mangled, your options are
either to guess from the context, or post a comment asking for
clarification.


UART Software Serial - Syncing two different sensors with start and stop bytes I'm using 2 SRF02 sensors on the same Arduino board to attempt to have the transmitter only pulse the 40 KHz wave, while the receiver will be only taking a fake range, i.e. picking up a reading based on another transmission.

I've been using SoftwareSerial and need to know how to synchronize the time for the receiver to know when the transmitter sent the data. What I found is that I'm going to have to do this using start and stop bytes to set them in the same cycle.

How can I do this?

This is my current code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd) {
  mySerial.write(address);
  //set the address of SRF02(factory default is 0)
  delayMicroseconds(100);
  //serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
  mySerial.write(cmd);
  //send the command to SRF02
  delayMicroseconds(100);
  //serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
}
void setup(void) {
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}

void loop(void) {
  unsigned int reading;
  SendCmd(0x00,0x5C);
  //Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
  delay(70);
  //time for SRF02 to measure the range
  SendCmd(0x02,0x57);
  //Get Fake Range at Address 0x02 - receiver
  delay(10);
  //wait for some time,let the Arduino receive 2 bytes data from the TX pin of SRF02
  if(mySerial.available()>=2) {
    //if two bytes were received
    reading = mySerial.read()<<8;
    //receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    reading |= mySerial.read();
    // receive low byte as lower 8 bits
    Serial.print(reading);
    // print the reading
    Serial.println("cm");
    //Serial.println("Time Sent: ");
    //Serial.print(T_sent);
  }
  delay(250);
  // wait a bit since people have to read the output :)
}

Your code bit

SendCmd(0x00,0x5C);//Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
delay(70);//time for SRF02 to measure the range
SendCmd(0x02,0x57); //Get Fake Range at Address 0x02 - receiver

will send a sound burst, delay 70 ms, then start listening for the burst, which by then will have traveled around 24 meters and probably be no longer audible.

You should instead start the fake range listener immediately after sending the burst.  The general idea for one approach is as follows:

Record time (eg, t1=micros();)
Send burst (eg, SendCmd(0,0x5C);)
Record time (eg, t2=micros();)
Listen for burst (eg, SendCmd(2,0x58); // Get microseconds)
Wait 70 ms, then read microseconds result t3
Compute corrected total microseconds, tm=t3+t2-t1
Convert microseconds to cm

Note use of command 0x58 instead of 0x57 to get microseconds instead of cm.  If you used 0x57, instead of adding t2-t1 to t3, you would add t2-t1 microseconds-converted-to-cm to a cm reading.

The reason for the computation tm=t3+t2-t1 is that the second command is issued about t2-t1 microseconds later than the first command, as explained in the next paragraph.

There is an unknown delay d1 between when t1 is recorded and when the first SRF02 acts; and there is an unknown delay d2 between when t2 is recorded and when the second SRF02 begins listening.  The correct amount to add to t3 is t2+d2-(t1+d1), which is t2-t1 if d1 equals d2, a more-or-less plausible assumption.  If your experiments reveal a constant error, add a small constant offset to compensate.

I doubt you should have the delayMicroseconds(100); statements in SendCmd(), and would recommend getting the code to work ok, then see if it still works ok when you take them out.  The delay(10); is unnecessary if you rewrite your 2-character-wait correctly (ie as a while rather than an if), and the delay(70); is unnecessary if you start conversion with command 0x5A,  “Fake Ranging Mode - Result in centimeters, automatically Tx range back to controller as soon as ranging is complete” and then properly wait for two characters to arrive, instead of a blind wait followed by a test if they've arrrived.


Interrupts for analog inputs I have an Arduino Uno. I've been reading about pin change interrupts, and one vector covers the analog pins. However, is it possible to trigger interrupts using analog pins as analog inputs (not digital)?

I actually want to analogRead() a potentiometer inside the ISR.

This is my code so far, http://pastebin.com/ykpp78GB

And my circuit is just two potentiometers connected to pin A0 and A1.

It is not possible to trigger an interrupt when an analog input has reached a threshold on any tinyAVR or megaAVR. It is possible to trigger an interrupt when an analog input of an AVR XMEGA with the event system.

It is possible to use the built-in analog comparator on the ATmegaXX8 and ATmegaXXU4 in the Uno, Leonardo, and comparable boards to trigger an interrupt when an internal or external threshold has been met. It is only possible to compare to an internal threshold on the Mega, Mega 2560, or comparable boards since the pin for the external threshold is not broken out, although actual breakout boards for the ATmegaXXX0/1 will have the pin broken out.

In all cases, examine the appropriate datasheet (in particular the "Analog Comparator" section) as well as the pin mappings on the Arduino website for full details.


Arduino to Thingspeak using WiFly-RN171 (Firmware 4.0) I am attempting to use an Arduino Uno+WiFly setup to send data to Thingspeak.
I have tried a few libraries by now. But nearly all of them don't have a working WebClient example (WebServer works fine).
I am using Arduino 1.6.3 IDE for Arduino UNO R3 + Wifly-RN171 with Firmware 4.0

The libraries I have tried (found through Google and forums):

https://github.com/sparkfun/WiFly-Shield/tree/master/Libraries/Arduino

A ThingSpeak example is given but the execution stops when WiFly.begin() is called. I tried WebClient and WebClient(Faster) examples from the same library and they are both stuck at the same line: WiFly.begin().
I believe this could be compatibility issue (WiFly firmware version/Arduino) but am unsure how to fix it.

Note: There seems to be a few versions for the SparkFun WiFly library from my search results. I tried whatever I found but only listed the latest one since if it is indeed a compatibility issue a newer version should be more likely to work.
https://github.com/Seeed-Studio/WiFi_Shield

This one has a http example which I am attempting to use to send data to Thingspeak through http get/post. I am getting 'Bad Request' from their nginx server. Any help in the right direction will be much appreciated.
I hosted the sketch I tried here: codebender.cc/sketch:276925

p.s. I am not allowed to post >2 links due to reputation so the last one is plain text.
p.s.s Can someone with higher reputation help me add the new tags {thingspeak, wifly, rn171}

I solved my problem by sending a GET request to a hosted PHP script which in turn updates Carriots by means of a Curl request.

My PHP Script

<?php
$humidity=$_GET['humidity'];
$data = array("protocol"=>"v2", //Compose JSON stream
              "at"=> "now",
              "device"=>"DEVICE_NAME",
              "data" => array ("humidity" => trim($humidity)),
              "checksum" => "");
$data_string = json_encode($data);

$ch = curl_init('https://api.carriots.com/status'); //Compose the HTTP request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'carriots.apikey: YOUR_API_KEY',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch); //Send the stream

Note:

I switched to Carriots from ThingSpeak due to personal preference.
This is by no means a standard way to send stream to Carriots.This
involves additional effort which slows down transmission of data but
I decided that this setup will be enough for a hobby project.
A good understanding of how POST requests are built should allow me
to skip the extra PHP script completely.


Why Can't I Program my Atmega168 Pro Mini? I'm trying to program a Atmega168 Pro Mini 3.3V/8mhz I bought online. I followed a tutorial that walks through the steps of how to program a Pro Mini with an Arduino Uno. However, in their example they are uploading code to a Atmega328 Pro Mini though I don't think it matters.
Anyway, I followed the same steps as they did (namely hooking up Uno's ground -> ground, 3v -> Vcc, Reset -> DTR, tx->tx, rx->rx). When I attempted to upload via Arduino IDE I got the message that the programmer was not responding. I also noticed that the transfer led on the Uno was not lighting up. Did I screw up something? Also, are my hookups correct? I would think tx pin should connect to rx pin, but I just followed the instructions. Would appreciate any thoughts

Your hookup seems to be correct. However check if there is a capacitor on the pro-mini board between DTR and reset pin, some arduino clones don't come with one.
If there isn't any you can simply connect a capacitor like this:
Reset pin (Arduino Uno) -> Capacitor (0.01uF for example) -> DTR (pro mini). The reason for this hookup is exmplined well here


How to get more than the 16 Analog INs on a Arduino Mega for using like 24 piezo sensors i bought an Arduino Mega2560 and flashed it with usbmidi. So now it comes up as a midi device.

I need more than those 16 analog ins to be able to put all my 24 piezo sensors into it to receive midi signals from it. I still have no idea how i have to put the piezo pieces into the arduino but also no clue as how to get more than those 16 analog slots. Any way to use the digital inputs as well or do i need some extension shield or so? I'm a total beginner with arduino...

You can customize a controllino on their page
https://www.controllino.biz/controllino-myplc/
I just looked at it and it seems you can get 24 analog outputs.

Don't know what the cost is though.


Installing Jan Breuers SCPI Parser I am trying to install/include Jan Breuer's SCPI parser. I was not able to find any documentation to accomplish this. I copied the contents on of the GIT zip file to my Libraries directory, but when I try to include the library I get a message that the header file could not be found. What do I need to do to install/utilize this library?

Here is the error message I am getting:

Specified folder/zip file does not contain a valid library

-Tim

You can't. It's not an Arduino library. You will have to find a different implementation.


How to run multiple functions one after another? I want to fade a red LED up and down, then a green LED up and down, and repeat the whole cycle indefinitely.

I've been trying to run multiple functions one after another. However my current code seems to have them both fading in parallel.

I tried using a switch case, do while and the while loop but the code runs the two functions at once. So what is wrong with the code below?

This is my code:

void setup() {
    Serial.begin(9600);
    DDRD |= (1<<DDD6)|(1<<DDD5);
    TCCR0A = 0xF1;
}

uint8_t fade_seq;

void loop() {
    loop1:
    fade_seq++;
    while (fade_seq==1)
    {
        fade_red(1);
    }
    Serial.println(fade_seq);
    while (fade_seq==2)
    {
        fade_green(1);
    }
    if (fade_seq==3)
    {
        fade_seq=0;
        goto loop1;
    }
}

void fade_red(uint8_t cnt)
{
    uint8_t i,k;
    for (k=0;k<cnt;k++)
    {
        OCR0A+=1;
        _delay_ms(10);
        if (OCR0A == 255)
        {
            for (i=0;i<255;i++)
            {
                OCR0A--;
                _delay_ms(10);
            }
        }
    }
}

void fade_green(uint8_t cnt)
{
    uint8_t i,k,c;
    for (c=0;c<cnt;c++)
    {
        for (k=0;k<255;k++)
        {
            OCR0B+=1;
            _delay_ms(10);
            if (OCR0B == 255)
            {
                for (i=0;i<255;i++)
                {
                    OCR0B--;
                    _delay_ms(10);
                }
            }
        }
    }
}

I did not quite understand what you are actually trying to accomplish.
Neither you question nor your code is very clear in this respect. And
your code is probably buggy anyway, since it does not do what you
expect.

Then, I am just guessing: you may just want to fade a red LED up and
down, then a green LED up and down, and repeat the whole cycle
indefinitely. I am guessing right?

First of all, I would recommend you stick with the functions provided by
the Arduino core library, as they will make your life easier. The kind
of low level AVR programming you are attempting here is for advanced
users. You should learn the basics first before moving to that realm.

Here is how I would write that using the plain analogRead() function:

const uint8_t RED   = 6;  // pin connected to the red LED
const uint8_t GREEN = 5;  // pin connected to the green LED

void setup()
{
    Serial.begin(9600);
    pinMode(RED, OUTPUT);
    pinMode(GREEN, OUTPUT);
}

// Fade an analog pin up and down.
void fade(uint8_t pin)
{
    for (int i = 1; i <= 255; i++) {
        analogWrite(pin, i);
        delay(10);
    }
    for (int i = 254; i >= 0; i--) {
        analogWrite(pin, i);
        delay(10);
    }
}

void loop()
{
    Serial.println(F("Fading RED."));
    fade(RED);
    Serial.println(F("Fading GREEN."));
    fade(GREEN);
}

Each LED fading up and down takes roughly 5 seconds:
2 ramps × 255 steps/ramp × 10 ms/step.


Can I power my shift register with a 12V external power supply and connect only the data, strobe and clear pins to the Arduino digital pins? I'm using a CD4094 shift register to power my LEDs along with a ULN2003A darlington transistor array. I want to hook up the LEDs to an external power supply of 12V (common anode).

The cathodes of little groups of LEDs will be connected to the ULN2003A which is connected to the shift register which will get its data from the arduino (the digital pins which i assume work at 5V).

My question is, if I connect the Vdd pin of the shift register to the 12V external power supply, will it still function as intended through the Arduino?

No. CD4k devices reference their high and low voltages to a (mostly) fixed ratio of Vdd, so there will be no way for the Arduino to operate the device.

Consider using a TPIC6C595 instead, which combines the shift register and the high-voltage driver into a single device.


Options for communicating between Arduinos I'm looking to communicate between ~5-10 Arduinos to send commands and data between them. By "Arduino" I mean the ATmega328 programmed using the Arduino programming framework.

Each of the devices would be on the same PCB.

I know I2C and SPI can communicate to some degree, but that they're really meant for peripherals devices connected to a micro controller rather than connecting multiple micro controllers to each other, and that they usually only send a few bytes of data at a time. On the other hand I know LCD displays can be driven using them, and I'd imagine there's a lot of data being transferred in those cases.

Is there a something like I2C (multi-master, multi-slave, single-ended, serial computer bus) for communicating between micro controllers? Allowing each device to send data to each other device unsolicited. For example, if a switch was pressed on device A, it would tell device B, without having device B ask A all the time if a switch was pressed. and vice versa.

Edit: I found some libraries that may do what I want with RS-485. Is this the only viable option for ~1k bps transmission between 5-10 devices? I would imagine TCP/IP over Ethernet would work as well, but that seems like too much. Are there any I2C libraries that allow sending that amount of data between only master devices?

https://github.com/MichaelJonker/HardwareSerialRS485
https://github.com/MajenkoLibraries/ICSC

There are a number of concepts that can help you realize your dream. I can't, in the space of this answer, tell you exactly how to implement what you want, but I can show you the concepts that will help you to implement it.

First off there's the concept of the bus master.  This isn't necessarily the device that instantiates communication - instead this is the device that owns and controls the bus.

When a device that isn't the bus master wants to communicate on the bus it first asks permission from the bus master.  The old Z80 (well, I say "old", but they are still in use in many forms today) used this concept to allow other chips to use the data and address buses. It consists of two signals - BUSRQ and BUSACK.  A device first looks to see if either of BUSRQ or BUSACK are active, and if neither are it then activates BUSRQ. If the bus master is willing to give up the bus to the other device (it's not using it at that moment) it activates BUSACK and the other device then knows that it can use the bus.  Nothing else can use it until BUSRQ and BUSACK have both been released.  Nice and simple and elegant.

But not perfect. If two devices both decide to ask for the bus at the very same instant you get a collision.  This is a common problem amongst shared bus systems like this, and causes untold problems unless you know how to handle it properly.

Enter the concept of listen-while-you-talk.  This involves the device that is sending on the bus also listening to what is being sent on the bus through a separate receiver.  It then can know if what it sent on the bus is what actually ended up on the bus.  For instance if two devices talk at the same time and one sends 10011001 and the other sends 11001100 the result that appears on the bus might actually end up as something else, such as 11011101 or maybe 10001000 depending on how the bus signals are created.  So if you know what you sent got corrupted you can now do something about it.

Next concept: backing off.  This is where both the senders wait for a short period and try and send again. As long as they both delay for a different amount of time the first one to try will get the bus and be able to communicate. But how do you guarantee that they will both delay for different times?  You may think the answer is simple: use a random number, like rand() or random().  But that is also problematic:

Another concept: The pseudo random number generator

The Arduino doesn't generate random numbers.  It just uses a complex mathematical formula to create a sequence of numbers that, to us, look random.  They aren't though.  Write a small program to print 10 random numbers through serial and run it multiple times (press the reset button).  You will find the same "random" numbers in the same order every time.  Try it on another Arduino and you get the same numbers again. Always the same.

So what to do?  The answer is called seeding the random number generator.  The next number generated by rand() et al depend on the number that had been generated last.  So change the first number and all the rest of the numbers will change.  However, you have a catch-22 situation. You need a random number to seed the random number generator to make it random to be able to generate a random number to seed the random number generator... ad infinitum.  You see where that's going? You can't seed from rand() since rand() isn't random until you have seeded from a random source. So you need to find a random source.

And that's not an easy task.  The best source of entropy as it's known is white noise. This can be generated in a number of ways with a number of different circuits - from the breakdown of a diode junction to very high gain amplification of the thermal fluctuations in a resistor.

All are quite complex for what you want really, but there is a simpler, if slightly less random, method - read an analog input that isn't connected to anything.  It won't have as much of a range as a proper entropy generator, but it should provide enough randomness to give a reasonable chance of each device getting a different seed.

Another useful concept is the interrupt.

This is good in a situation where you don't want the complexity of a multi-master bus with all the collisions etc. You have a single master that does all the work on the bus, and when a slave device has something important to say it nudges the master with an interrupt. The master then goes "Yes? What do you want?" to which the slave replies "Someone pressed my button".

That way the master isn't constantly polling the slave to see if the button has been pressed.  It is often used in bus arrangements like SPI and there are many chips, such as IO expander chips, that can assert an interrupt when one of their input pins changes state.

But if you have 20 devices does that mean you have 20 interrupt pins?  Not necessarily. New concept: wired OR.

It's perfectly possible to have multiple different slaves all using the same interrupt pin.  The pin is normally held HIGH with a resistor (it could be an internal pullup resistor) and each slave has an open drain output connected to that pin.  An open drain output, when "off", is not connected to anything - it's like the pin is in input mode (in fact it can be emulated on chips that don't have open drain by switching between input and output mode).  When the output is "on" it connects the pin to ground, pulling down the IO pin, just like a button would.

It's then up to the master to make its way round the slaves that it knows are attached to that interrupt to see who needs attention.  You can of course implement a number of different interrupt pins with different groups of slaves on each one - maybe a high priority one with just one device, and lower priority ones with multiple devices on each, for example.

The same concept of wired OR and open drain can be used for allowing multiple devices to all share the same physical wires.  That is exactly how I2C works - the two bus lines are pulled up by resistors and the devices on it use open drain outputs to pull the line low to release it back to high to create the different logic levels. If two devices both pull it low together it will just be low.  Without the open drain method if you had one device outputting a 1 and another outputting a 0 you would basically get a short circuit between the two and you would end up damaging chips.

And then of course you have the concept of synchronous versus asynchronous communication, but that is an entirely different kettle of fish. Simply said though, protocols with a clock, like SPI and I2C, which have a master generating that clock, are synchronous. Protocols like the UART and RS-232, RS-485, etc are asynchronous - they rely on both ends agreeing on how fast data is being sent (baud rate) so they know how to interpret the signals as they arrive.


Can I use custom ethernet shield with standard libraries? I would like to make a custom ethernet card that uses the enc28j60 like this:
DIY Ethernet card

but first I would like to know if I can use the standard libraries which can be used with the ethernet card which is in the market like this:
ENC28J60 ethernet module

The libraries don't care whether or not you're using a shield, only that you're using a device they support and that you've wired it up how they expect (or that you've modified the library to use the actual wiring you're using). So find a library that supports the ENC28J60 and knock yourself out.


Arduino screws up trivial program involving enum Behold this insanity:

enum WhatArduinoIs {
  Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
};

void TellMe(WhatArduinoIs pls) { }

void setup() { }
void loop() { }

I'm pretty good at C++, so I'm fairly sure that should compile. However I get this error:

sketch_jan21b.ino:3:13: error: variable or field 'TellMe' declared void
sketch_jan21b.ino:3:13: error: 'WhatArduinoIs' was not declared in this scope
Error compiling.

I've encountered the Arduino "IDE"'s propensity for insane and totally unrobust modification of programs before. Specifically when you #include libraries Arduino only magically adds the relevant C++ files if the #include is in your main sketch. #include <LiquidCrystal.h> in another C++ file? Link errors.

I suspect in this case it is Arduino magically trying to add function declarations to the start of the file so their order doesn't matter. I.e. it turns the file into this:

void TellMe(WhatArduinoIs pls);

enum WhatArduinoIs {
  Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
};

void TellMe(WhatArduinoIs pls) { }

void setup() { }
void loop() { }

That obviously doesn't work. How can I tell Arduino to leave my damn program alone?

You can workaround the issue by putting your enum and function into a namespace. You can even take advantage of C++ unnamed namespaces if you like:

namespace
{
  enum WhatArduinoIs {
    Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
  };

  void TellMe(WhatArduinoIs pls) { }
}

void setup() { }
void loop() { }

It's annoying (as are many things in the Arduino IDE), but it seems to work.

If you're more experienced with programming then you might want to consider using a 3rd party IDE with an Arduino plugin, such as Eclipse. The Arduino IDE is really only designed for beginners.


about how to write data in the whole EEprom? I have interfaced AT24c1024 EEprom with ATmega32.AT24c1024, which has 512 pages each of 256 bytes. There are two mode of writing (byte write and page write).

In page write mode, it is capable of writing 256 bytes for page; if we want to write 258 bytes, then the first two bytes in the beginning of that page will be overwritten.

My question is: what should I do to write in the whole EEprom (i.e) if I want to write 300 bytes, I want to writes 256 bytes in a page then continues to the next page and so on?

In that case you write two pages, the first page containing the first 256 bytes and the second page containing the following 34 bytes.

You can do a speed check to see if writing the second page's 34 bytes by using the byte write is faster, but I doubt that.

In case you want to keep from the second page the remainder of the 34 bytes (the 256-34 bytes following), you first read the second page, than you change the first 34 bytes, than write it back.

Also note that there is a limit on the number of writes on a page. This is called page wearing. So if you write these 2 pages very often, you might want to come up with an algorithm to rotate through all the available pages in your EEPROM, and not writing every time to the same 2 pages.

EXAMPLE

Assume you want to write totalBytesToWrite:

// Calculate the number of pages to write, round up.
int pagesToWrite = int((totalBytesToWrite + 255) / 256;

for (int page = 0; page < pagesToWrite; page++) // Current page to be written
{
    // Calculate number of bytes to be written in this page, for the last page, write remaining bytes, otherwise 256
    int pageBytesToWrite = (page == pagesToWrite - 1 ? totalBytesToWrite % 256 : 256;

    // Write page (btw, I do not know what the second argument char deviceAddress means)
    page_write(n / 256, ??, &memory[n], pageBytesToWrite);
}