ESP8266 NodeMCU 3v3 current for fingerprint sensor From what i see that 3.3Vpin provide 3.3V and 400mA. The fingerprint module i use is AS608. Connecting the fingerprint module power pin to 3.3V of the nodemcu. From the datasheet it only can handle 3.3VDC, operating current<60mA and peak current at <70mA. Do i need to add a resistor to take the current away. Since last time i use another fingerprint module which is R307 connecting to Vin of the nodemcu and now it not working anymore?

Be careful using Vin on the NodeMCU for 3.3V devices! If you are powering it by 5V USB power, this Vin pin will probably have something like 4.76V on that pin. The circuit diagram shows that Vusb is connected to Vin with just a schottky diode, which drops the current about .34 volts and provides some noise isolation from the Vusb supply. If you connected a 3.3V device to this pin at 4.76V, you may have damaged your component.
You'd have to check the datasheet or documentation for the fingerprint module, but it sounds like the fingerprint module will only draw 60-70mA when it's given 3.3 volts. Datasheets often provide application examples and may specify that you do need additional resistors, capacitors, etc. The refrain in cases like this is always read the datasheet.
If your NodeMCU datasheet says it can provide 400mA then it should certainly be able to provide the 60-70mA that the fingerprint sensor needs. I've powered an ESP8266 by connecting its Vin pin to the Vin of another NodeMCU and they seem fairly happy together, although there tends to be quite a bit of noise on the Vin pin.


4 channel relay module reversed? Or is it my code? So I am designing a simple project where my Arduino reads analog values from a potentiometer, or rotation sensor, as it is called on EBay, and uses that value to determine how many relays to close. I am connecting 4 digital pins to the relay module, and powering it with a constant digital signal from pin 2.

Here is my code:

//set up the pins for activating each relay on the module
#define in1 13
#define in2 11
#define in3 10
#define in4 9
#define power 2      //set up the power pin for the module

void setup(){
 Serial.begin(9600);
 pinMode(in1, OUTPUT);
 pinMode(in2, OUTPUT);
 pinMode(in3, OUTPUT);
 pinMode(in4, OUTPUT);
 pinMode(power, OUTPUT);
 digitalWrite(power, HIGH);        //for power to the relay module
}

void loop(){
 float rotationValue = analogRead(A0);          //read raw value from potentiometer
 float percentValue = rotationValue / 10.23;       //convert the value to 0%-100%
 Serial.println(percentValue);                  //print it out on screen
 if(percentValue >= 0.00 && percentValue <= 1.00){         //all relays off
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 1.00 && percentValue <= 25.00){        //relay #1 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 25.00 && percentValue <= 50.00){           //relay #1, #2 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 50.00 && percentValue <= 75.00){     //relay #1, #2, #3 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 75.00){             //all relays on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, HIGH);
 }
}

Ok, here's the problematic part. After I upload the program onto the board, when I set the potentiometer to the 0 position, all relays are on. And when I twist it to the 100 position, which is maximum, all relays are off. Although it is usable, what's weird is that when I start from 100 and twist it back toward 0, the relays will activate, but in the opposite order. So relay #4 will activate, then #3, then #2, and then #1, and all four are on when I reach 0. Is it something wrong with my code? I've checked and rechecked, and even checked with a different project where I connect the pins to LED's. And they work normally. But when I connect up the relay module, it's reversed. Any ideas?

Here is the relay module: http://www.miniinthebox.com/4-channel-relay-module-with-optocoupler-5v_p903429.html?currency=USD&litb_from=paid_adwords_shopping&gclid=Cj0KEQiAts-kBRCbgrXc1rnXw7MBEiQAnFqTdph_qI5n7rrpW7gZaxafVVkeWitQlN8FUSUJzdsV2JwaAlBA8P8HAQ

And here is the potentiometer: http://www.ebay.com/itm/Potentiometer-Sensor-module-Rotation-Angle-Sensor-Arduino-competible-/251656942542

I mean, right now I'm even thinking that the relay module may be labeled incorrectly, that the numbers are printed the wrong way. But it could be my fault, most likely.

Thanks for any help.

All the relay boards I've come across are 'active low' i.e. as you've discovered bringing the control pin down to earth activates the relay. As an aside just be careful that the arduino has enough juice to power the relays, a separate supply is normally required if these are coil rather than ssr type relays


Simple LCD countdown timer I tried to modify the basic "hello-world" sketch for the LCD that is a part of the examples section in the IDE. I intended to make a countdown timer using the LCD.
The original code simply prints "Hello World" in the first line, and then makes use of the millis() function to print the time elapsed in the next line.
So I tried a simple modification to make it count down from 20. Instead of printing millis()/1000 , I printed 20-millis()/1000, and also added a while() to only print till millis()<=20,000. (so that it does not go beyond 00)
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {

  lcd.begin(16, 2);

  lcd.print("time left");
}

void loop() {

  while(millis()<=20000){

    lcd.setCursor(0, 1);

    lcd.print(20- millis() / 1000);
  }

}

It seemed to work till 10. but instead of 9, it printed 90, and likewise 80,70.. for 8,7...etc till 00.
How can I get rid of these extra zeros?

instead of 9, it printed 90

No, it didn't: it printed “9”. However, it did not erase the previous
value before printing “9”. Before printing the 9, the LCD had:
┌────────────────┐
│time left       │
│10              │
└────────────────┘
 ^cursor position

When you printed “9”, that character replaced the “1”, and you end up
seeing “90”.
The fix, as pointed out by Juraj, is to add a space after printing the
numbers.
An alternative is to prepend a space (or a zero), but only when the
number to be displayed is less that 10:
int count = 20 - millis() / 1000;
if (count < 10)
    lcd.print(' ');  // alternatively: '0'
lcd.print(count);


Creating a Web Interface for ESP32 I am working on a project that involves moving various servos and lights and I need a good UI to work with the device. I've previously used Blynk, which worked very well but I didn't like some of the limits it has. My current code works with Blynk and I'd like to change it to a web server so it can work on any device without an app or internet connection.

Right now my esp configures itself as an access point and I can navigate to its IP address to get to my "hello world file" but after that I'm stuck. What really stumps me is getting the input from the interface that I make in HTML, I could fairly easily make an arrangement of buttons, sliders, and fields, that fits my need but how do I get the value of these as a variable in my arduino code?

I've seen some examples of code that are very simple essentially a couple buttons redirect to different web pages on the server and it takes these commands to assign a variable, but that seems kind of poor form, is there a better way, or how do I make that work with a complex interface with many buttons and switches.

I've heard of Jquery and Ajax but not familiar on how to make this work with Arduino code.

I would highly recommend splitting it into two parts: back end (C++) and front end (JS). You'll probably want to connect to a router, so your clients, like a phone and laptop need not be on that AP hotspot w/o internet.

You first build an API with arduino using GET params to control, example pin values int level = server.arg("level").toInt(); analogWrite(2, level);, or whatever you need to do. Put that in a function called handlePin, and subscribe it in setup(): server.on("/pin", handlePin);. Then just add CORS to the server response: server.sendHeader("Access-Control-Allow-Origin","*"); and you can now hit it from any computer on the network. To test, just enter it's URL and some params into a browser URL bar; http://192.168.2.123/pin?level=512 to dim halfway.

Once you have the URLs working, the interface part is built completely separately using whatever tools you want. All you need to do is have your UI hit the API using simple ajax calls. As a quick and dirty example: Level:<input type=range id=val max=1024> <br> <button onclick="fetch('http://192.168.2.123/pin?level='+val.value)">update</button>

That's hows the pros do it, you just swap C++ for PHP or C# or whatever, and use any UI framework you want. Once you have the source of your client app ready, you can upload it to the SPIFFS of the ESP, but I find it easier to host and update system-wide on a "real" server.

If you don't want to write the UI code yourself, you can use node-red to make a quick and dirty "control panel", just like HTML but with drag and drop functionality (more or less). You still use the same API on the ESP, and you can use more than one system at a time; all the ESPs care about is hitting the right URL.


Contoller for a stepper motor I am currently implementing the following setup:

Arduino Mega 2650 -- DRV8834 -- Stepper motor

Everything works fine, however since it can provide a higher torque I want to run the stepper in half step mode. Each step is triggered by a single pulse coming from the Arduino to the driver. If one uses the Digital Pins for this purpose as done by AccelStepper, the maximum frequency is around 1000 pps (points per second). This is a third of what I want to achieve. The second option would be to use the PWM of the Arduino which naturally runs at 16 MHz (way to high). There is a way to downgrade this frequency, however the steps are only discrete and not accurate enough for a nice speed control.

Therefore I want to do the following

Arduino Mega 2650 -- Controller -- DRV8834 -- Stepper motor

whereby the Controller is creating a PWM with a frequency (100 to 3000 Hz) depending on some signal coming from the Arduino (I2C, voltage level or something else). I was now searching two days for a component and have no clue what I could use.

How can I create a PWM from 100 to 3000Hz with an arduino?

Edit 1: I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM

void loop(){
digitalWrite(pinSTEP, HIGH);
delayMicroseconds(T/2);
digitalWrite(pinSTEP, LOW);
delayMicroseconds(T/2);
}

where T = 1 / f is not feasible since I have to read out a sensor in the loop which destroys the motor timing.

Edit 2: There is a method to change the register of the timers. One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM. However with only seven discrete steps this leads to the following freuquencies:

prescalar = 1 ---> PWM frequency is 31000 Hz
prescalar = 2 ---> PWM frequency is 4000 Hz
prescalar = 3 ---> PWM frequency is 490 Hz (default value)
prescalar = 4 ---> PWM frequency is 120 Hz
prescalar = 5 ---> PWM frequency is 30 Hz
prescalar = 6 ---> PWM frequency is <20 Hz

which is not sufficient for my application.

For more about this method:

http://usethearduino.blogspot.ch/2008/11/changing-pwm-frequency-on-arduino.html
http://forum.arduino.cc/index.php?topic=72092.0

Sometimes a solution is so easy that it hurts ;) Based on the input of this wonderful community I found my solution. Code:

#include <TimerThree.h>
// TimerThree PWM Pins 2, 3, 5

#define pinPWM       2
#define pinM0        22
#define pinM1        24
#define pinSleepnot  28
#define pinDir       30

void setup(void){

  // Define output pins
  pinMode(pinM0, OUTPUT);
  digitalWrite(pinM0, HIGH);
  pinMode(pinM1, OUTPUT);
  digitalWrite(pinM1, LOW);
  pinMode(pinSleepnot, OUTPUT);
  digitalWrite(pinSleepnot, HIGH);
  pinMode(pinDir, OUTPUT);

  // Initialize serial communication
  Serial.begin(9600);

}

void loop(void){

  for (float frequency = 500; frequency < 3000; frequency = frequency + 1) {
    float T = 1 / frequency * 1000000;
    Serial.print("Frequency: ");
    Serial.println(frequency);
    Timer3.initialize(T);
    Timer3.pwm(pinPWM, 100);
    delay(5);
  }
}

the maximum frequency is around 1000 pps

Arduino pin operations takes about 100 ticks. Or 400 ticks for four pins. No more than another 100 ticks for processing and logic ops. So I would expect 500 ticks or 30k on a 16mhz Arduino.

Much faster if you use direct pin ops.

So maybe the code you used isn't well written or your Arduino is doing lots of other things?

edit:

  I found my solution. Code:

there is no reason for you to repeatedly initialize the module. this thing is simple, and others have laid out the thought process for you. write a set of routines that spin the motor - spin it left, spin it right. and then call those routines in a timer isr. nothing fancy here.


how to get esp32 ip address ,which is being connected to local network I need to know the IP address of ESP32 on the local network(without printing ip on serial monitor ). The idea is to do mDNS or UDP broadcast to send the IP to the android application. The app will then use that IP to do the communication. Is there someone who has already done it?

You don't. You configure mDNS (as you already suggested in your question...!) and the client device then queries mDNS to find the device by the name you allocated it.

Look at the ESPmDNS library examples for how to use mDNS.

Edit: if you really want the IP, you can do WiFi.localIP() (station mode) or WiFi.softAPIP() (access point mode).


Arduino pins LCD and motor controller I am using an L298N motor control. I want to use my 2*16 LCD. Can I use the code like this?

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

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(12, 9, 4, 5, 6, 7);

// Motor Control
#define enableA  3
#define enableB  11
#define in1 4
#define in2 5
#define in3 6
#define in4 7

Using that pin configuration you'll have several problems despite you'll use enable pin.

I would use a I2C module for 16x2 lcd like this https://www.amazon.com/SainSmart-Serial-Module-Display-Arduino/dp/B00813HBEQ

Control 16x2 lcd with I2C.


Master doesn't receive the correct values in a master/slave SPI link I've been struggling for 3 weeks looking for a solution to my problem concerning SPI communication.

So, I need to establish a SPI communication between two Arduino devices: for instance, the master sends a letter 'a' to the slave; the slave receives it and does some processing. In my case, it should set one of his  8 pins to high then read all pins and send the report back to the master.

The part where the master sends 'a' and the slave processing it works fine but the master doesn't seem to receive the correct values. Instead it always receives 0.

Here's the code:

Slave:

#include <SPI.h>;

volatile byte command = 0;
byte ett =8; //nbr of test points
byte motif= 0b000000000 ; //intiatition of my varible which will contain my pin's states
byte end[8] = { 2,3,4,5,6,7,8,9}; //array containing the pins

void setup (void) {
  Serial.begin (9600);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  // turn on interrupts
  SPCR |= _BV(SPIE);
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect) {
  byte c = SPDR;
  switch (command) {
    //////////////Slave traitement/////////////
    // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  case 'z': ////case 'z", set all pins to INPUT
    for (int i=0; i<8; i++){
      pinMode (end[i], INPUT);
    }
    break;

  case 'a': // //if 'a' : Set one pin to high then read all pin's satete to verify if there is any open circuit or short circuit
    for (int j = 0; j < ett; j++) {
      pinMode(end[j], INPUT);   // set all pins as INPUT
    }
    motif = 0;
    pinMode(end[0], OUTPUT);  // Set one pin as OUTPUT
    digitalWrite(end[0], HIGH); // Set the output pin to HIGH
    Serial.println();
    Serial.print(" ");
    for (int k = 0; k < ett ; k++) { // scan
      if (digitalRead(end[k]) == HIGH) {
        // if pin == HIGH add '1' to my vector
        Serial.print("| ");
        motif = motif + 1; // +1
      } else { // if pin == LOW
        Serial.print(". ");
      }
      motif = motif << 1; // shift left
    }
    Serial.print(" -MOTIF LU= ");
    Serial.print(motif, BIN);
    SPDR = byte (motif); //SPDR is the SPI Data Register: it contains the data that will be sent to the Master
    Serial.print(" ");
    break;
  }
}

void loop (void) {
  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
}

Master:

#include <SPI.h>

byte CS0=10;
byte CS1=9;

void setup (void) {
  Serial.begin (9600);
  Serial.println ();
  digitalWrite(SS, HIGH);  // ensure SS stays high for now
  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();
  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);
}  // end of setup

byte transferAndWait (const byte what) {
  byte a = SPI.transfer (what);
  delayMicroseconds (1000);
  return a;
} // end of transferAndWait
///traitement au niveau du maitre

void loop (void)  {
  byte esclave0_testpin0;
  /////////////Set the first slave's pin to High then read all pins
  digitalWrite (CS0,LOW); //activate the slave
  transferAndWait ('a'); // set first slave's pin to high
  esclave0_testpin0 = transferAndWait ('z'); //read all slave's pins and report it in the variable esclave0_testpin0
  digitalWrite (CS0,HIGH); //disactivate the slave
  Serial.println ("test_0");
  Serial.println (esclave0_testpin0, BIN);
  delay (1000);  // 1 second delay
}  // end of loop

In slave, command is always 0. You problably meant:

void loop(void) {
    command = (digitalRead(SS) == HIGH ? 0 : 1);
}

and at ISR:

ISR (SPI_STC_vect) {

    byte input = SPDR;
    byte output = 0;

    if (command) {

        switch (input) {

            case 'a':
                //...
                break;

            case 'z':
                //...
                break;
        }
    }

     // send data back
     SPDR = output;
}

As a best practice, avoid to implement the logic within the ISR and use global volatile variables to pass state changes to the code in the main loop. Probably you will have to implement a circular buffer to receive from and send to the SPI bus...


How to detect cancelled download? I have a server with files that may be downloaded.

How do I go about detecting when a download is cancelled by a client?

The function that handles reading files for download:

void readFile()
{

EthernetClient client = server.available();

// Open file for Reading.
SdFile webFile;
webFile.open(&root, &MyBuffer[1], O_READ);
if (!webFile.isOpen()) error("readFile");

do   // @ adafruit_support_rick's do-while loop
{
    int count = 0;
    char buffers[BUFSIZE];
    bool done = false;

    while ((!done) && (count < BUFSIZE) && (webFile.available()))
    {
        char c = webFile.read();
        if (0 > c)
        done = true;
        else
        buffers[count++] = c;
        delayMicroseconds(1000);
    }

    if (count)
    client.write( buffers, count);

} while (webFile.available());

webFile.close();

fileDownload = 0;  //File download has finished; allow logging since download has completed

delay(500);

MyBuffer[0] = '\0';

}

Well, assuming cancelling a download == incomplete download == client disconnected before server was done, you could create a flag like this at the top of the function:

bool dload_cancel = false;

Change the IF block, below the innermost WHILE loop, to this:

if (count){
  if (client.connected())
    client.write( buffers, count);
  else {
    dloadCancel = true;
    break;
  }
}

The flag will be set once your server checks and discovers that the client has been disconnected. You can check the state of the flag outside the DO-WHILE block to know if the download was completed or not.

if (dloadCancel){
  // client was disconnected; download did not complete
}

dloadCancel is also a better indicator of a completed download than your fileDownload flag.

You should also know that this:

if (0 > c)
    done = true;

is redundant. Its already taken care of by webFile.available().


Voltage divider producing unexpected voltage I'm trying to run a neopixel strip and an arduino from the same power supply using a voltage divider to get 5V to the strip.

Here are the values for my voltage divider:

R1 = 1500 Ω

R2 = 1000 Ω

Vin = 12 V

resulting in:

Vout = Vin*(R2/(R1+R2)) = 12*(1000/(1500+1000)) = 12*(1000/2500) = 12*0.4 = 4.8

When the divider is connected at its inputs but not at its outputs, I measure the expected 4.8V across R2. But as soon as I connect the neopixels, I only get about 1.6V.

Could anybody explain this || Suggest a possible solution?

Since you are connecting your pixel strip in parallel with R2, the
correct formula is

Vout = Vin × (R2∥Rp) / (R1 + (R2∥Rp))

Where Rp is the resistance of the pixel strip and

R2∥Rp = R2 × Rp / (R2 + Rp)

is the combination of R2 and Rp in parallel. From this you can see that
an output voltage of 1.6 V is consistent with a strip resistance of
300 Ω.

This is, however, somewhat oversimplified, as the I(V) characteristic of
the LED strip is probably non-linear, thus not really equivalent to a
resistor.


What is happening when digitalWrite(pinname, LOW) is invoked after pinMode(pinname, INPUT_PULLUP)? I read the Arduino official docs on digitalWrite and am confused about what is happening from an electrical perspective when digitalWrite is invoked on INPUT_PULLUP pins.
Say my code says this:
pinMode(4, INPUT_PULLUP);
digitalWrite(4, LOW);

The docs say:

If the pin is configured as an INPUT, digitalWrite() will enable
(HIGH) or disable (LOW) the internal pullup on the input pin. It is
recommended to set the pinMode() to INPUT_PULLUP to enable the
internal pull-up resistor. See the Digital Pins tutorial for more
information.

Does this mean pin 4 is floating or is it at ground?  Are those two lines of code equivalent to pinMode(4, OUTPUT); digitalWrite(LOW);  ?

It's pretty explicitly stated there in your quote: if you write a LOW when in INPUT mode it disables the pullup resistor. That's all it does.
pinMode(4, INPUT);
digitalWrite(4, HIGH);

is exactly the same as:
pinMode(4, INPUT_PULLUP);

And
pinMode(4, INPUT_PULLUP);
digitalWrite(4, LOW);

is exactly the same as
pinMode(4, INPUT);

Of course this exploits a peculiarity of the AVR's IO block, but any decent core will emulate that functionality for compatibility with older code.


How do I control multiple LEDs strips with Arduino I want to decorate my house with LEDs strips on each step of my stairs.
I will buy LEDs strips with a 12V power supply.

I want that if I put my foot on the first step, the first LEDs strip turn on, and after every second, the next step turn on too until the last step.
After 10 seconds on, the step must turn off.

To detect my foot, I'm thinking of using that kind of component : PIR (motion) sensor (product 189 on adafruit website). It act like a push button.

My first thought was to create two circuit loops.
One to supply the LEDs strips with a transistor between each strip.
And the second to control the transistor, so the turn on/off signal.

Thanks to your advices, I decided to use an Arduino to do the control loop.

I found this (http://www.zem.fr/decouverte-du-composant-74hc595-8-bit-shift-register/):

It's two 8-bit shift register, I have 16 steps on my stairs.
With a simple bit of code, I successed in writing a Arduino code that push ten HIGH(1) bits from the right then sixteen LOW(0) bits. So I have what I want with the LEDs.

The question is : how to connect the 16 LEDs strips with my circuit (instead of the single led) ?

English is not my native language, I tried to do my best.

Assuming your LED strips are essentially "always on" when they have power, you could replace the single LEDs in your diagram with transistors that sit between the power supply and the strip. Then, when your Arduino pin goes high, the transistor turns on the LED strip.


Multiple Wireless Sensors to an Arduino I am looking for ideas on how to connect 12 sensors to an Arduino wirelessly.  The sensors will be about 10ft from the Arduino.  They need to send one byte of data every 100ms-250ms to the Arduino in an organized manner.

I have investigated MQTT and pubsubclient, but have not found a way to make an Arduino a Broker, and have been told it is very inefficient for my application.
I have looked at NRF24L01, but it appears to be limited to just 6 pipes to receive data in an organized fashion.
I researched Xbee, but have been told that it cannot keep up with the data rate.

Other suggestions are appreciated...  Thank you.

I would recommend the nRF24L01.

You don't need one pipe per node - just one pipe.

Each pipe is effectively an address that a node responds to - having multiple pipes means you can have multiple addresses on one node (like aliases) - but of course you only need one address per node, and hence one pipe per node.

The range is more than adequate (with the antenna version I have managed to get hundreds of meters no problem) and the price is so low as to be negligible.


ISR not working as it is supposed to For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle).

I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small test program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs.  My code looks like following:

    #include <PinChangeInt.h>
    #define pw 3
    int pwm;

    void setup() {
      // put your setup code here, to run once:
      pinMode(pw, OUTPUT) ;
      pwm_setup();             // Set PWM to a frequency of 62.5kHz

      PCintPort::attachInterrupt(pw,rise,RISING);    // call void rise() when PWM is HIGH
      PCintPort::attachInterrupt(pw,fall,FALLING);   // call void fall() when PWM is LOW

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      pwm = 127;                                                // 50% duty cycle
      pwm_on(pwm);

    }
    void pwm_setup()
    {

      TCCR2A = 0x23 ;
      TCCR2B = 0x09 ; // mode 7, clock prescale by 1
      OCR2A = 256-1 ;  // 256 clock periods = 16us per cycle
      OCR2B =0 ;
      TCNT2 =0 ;

    }
    void pwm_on(double)
     {
        OCR2B = pwm ;
     }

    void rise()
    {
      Serial.println("RISE");
    }

void fall()
{
  Serial.println("fall");
}

But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.

Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can anyone point it out please ?

Your helpful comments and suggestions would be appreciated.
Thankyou!

Here are a few items to consider.

From #define pw 3 you are working with PD3, INT1.  As one of the Atmega328 Uno's two external interrupts, INT1 supports RISING and FALLING events separately.  Pin change interrupts (PCIs) on pins other than 2 or 3 of the Uno won't separate them and in the interrupt routine (one interrupt routine in that case, not two) you will need to test which occurs by reading the pin.
Serial communication depends on interrupts and won't work in an interrupt handler.  Instead, set a flag (via a volatile byte variable) to test in your loop().
For testing, put pwm_on(pwm) in setup() instead of loop().
In loop(), compute seconds = milli()/1000 and if seconds != prevsec, set prevsec=seconds, enable your PCI or external interrupt, then enter a loop that waits for a flag and takes a reading.  Or, in the interrupt handler, both set a flag and take a reading into a volatile variable.
If you only need to measure the quantities a few times per second, or a few times per minute, you could just busy-wait for the condition, then trigger a sample-and-hold, then convert analog to digital via analogRead().

Regarding sample-and-hold: Unless you change the ADC sampling rate, analogRead() will take up to 100 microseconds per reading.  If your input waveform is 62.5 KHz, it will toggle about about six times while being measured, which if measured directly is likely to give a random result.  However, if you use a sample-and-hold circuit, you can hold the ADC input constant until your measurement completes.

An alternative to using a sample-and-hold is changing the ADC sampling speed. See post #5 in thread Faster Analog Read? on forum.arduino.cc.  If you get the sample time down to 8 to 12 microseconds you can do ok with a busy-wait method.  Ie, when your code wants a reading, it has a loop that measures the PWM line over and over, and starts an ADC conversion shortly after the PWM gets to the state desired for the measurement.


How can i read serial data into a string until a certain character is recieved? This is not a duplicate of my other question. This question deals with reading specific data within a serial stream. The other question deals with reading and adding data into a manageable data string.

What I'm trying to do is send a command to serial, get the response, and put it into a string, and then break that string up into usable parts of data.

The problem I'm having, is there is a delay between the time the serial command is sent, and the response. meaning the serial data isn't being captured before the function moves onto the next line. Using delay() doesn't appear to work, as i believe it halts everything for that delay period.

What I'm hoping to do, is read the data from serial and if the character '<' is received, place it, and everything after it into the buffer until the character ">" is received.  After the last character is received, and placed into the buffer, continue on with the script.

Unless of coarse someone has a better idea on how to approach this.
i would also like to note that this is just a part of a larger project. If you need to see the entire project, please let me know and i will provide a link where you can download it.

The string i'm expecting as a response would be similar to this:

<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

Here is the code i have so far:

float mx;
float my;
float mz;
float wx;
float wy;
float wz;
String dAlarm;
char buffer;
void gPos() {
  Serial1.print("?\n");
  buffer = Serial1.read();
  char string[80];
  string[buffer];
  char *alarm = strtok(string, ",");
  char *mposX = strtok(NULL, ",");
  char *mposY = strtok(NULL, ",");
  char *mposZ = strtok(NULL, ",");
  char *wposX = strtok(NULL, ",");
  char *wposY = strtok(NULL, ",");
  char *wposZ = strtok(NULL, ">");
  alarm += 1;
  mposX += 5;
  wposX += 5;
  mx = strtod(mposX, NULL);
  my = strtod(mposY, NULL);
  mz = strtod(mposZ, NULL);
  wx = strtod(wposX, NULL);
  wy = strtod(wposY, NULL);
  wz = strtod(wposZ, NULL);

  if (strcmp(alarm, "Idle") == 0) {
    dAlarm = "Idle";
  } else if (strcmp(alarm, "Run") == 0) {
    // Something to do when Busy
    dAlarm = "Run";
  } else if (strcmp(alarm, "Hold") == 0) {
    // Something to do when Busy
    dAlarm = "Hold";
  } else if (strcmp(alarm, "Door") == 0) {
    // Something to do when Busy
    dAlarm = "Door";
  } else if (strcmp(alarm, "Home") == 0) {
    // Something to do when Busy
    dAlarm = "Home";
  } else if (strcmp(alarm, "Alarm") == 0) {
    // Something to do when Busy
    dAlarm = "ALARM!";
  } else if (strcmp(alarm, "Check") == 0) {
    // Something to do when Busy
    dAlarm = "Check";
  }
  dispPos();
}

void dispPos() {
  int state = 0;
  int x = analogRead (0);
  if (x < 800) {
    state = 1;
  }
  if (state == 1) {
    dPos = false;
  }

  if (dPos == true) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("X");
    lcd.print(mx);
    lcd.setCursor(8, 0);
    lcd.print("Y");
    lcd.print(my);
    lcd.setCursor(0, 1);
    lcd.print("Z");
    lcd.print(mz);
    lcd.setCursor(8, 1);
    //lcd.print(" ");
    lcd.print(dAlarm);
    delay(3000);
  } else {
    mainMenu();
  }
}

What you need to do here is implement a small finite state machine.

Basically you need to look at each character as it comes in and make a decision what to do with it depending on what state you're in at the moment.

Basically the operational decisions you need to make are:

Is the character a < and am I currently not reading a string?

Yes, start reading the string.

Is the character a > and am I currently reading a string?

Yes, finish reading the string and process it

Is it any other character and I am currently reading the string?

Yes, add it to the buffer.

So you can see there some common questions:

What is the character?
What am I doing at the moment?

So you need to have a simple state variable that remembers if you're reading the string or not, and something to say where in the buffer you are so you know where in the buffer to add any incoming characters.

boolean readingString = false;

A simple true/false will suffice to depict if we're reading the string or not.  Start off not reading the string.

char buffer[80] = "";

A buffer to store the text - maximum of 80 characters (including the NULL terminating character)

int charPointer = 0;

Something to know where in the buffer are currently.

Now to read the characters:

First get the next character from the serial port:

loop() {
    if (Serial.available()) {
        int incoming = Serial.read();

Now decide what to do with it.  We have a number of possible situations, some of which can be combined into single options.  For instance, if we get a "<" while reading a string it's an error condition - but do we really care?  It could be that we lost the end of the last string and have just started a fresh one - so we can just treat it as the start of a string regardless of what state we're in.  Let's use a switch for this since it's nice and tidy:

        switch (incoming) {
            case '<':
                readingString = true; // Start reading string
                charPointer = 0; // Set the buffer pointer to the start
                buffer[0] = 0; // Make the string empty
                break;

            case '>':
                if (readingString) {
                    processBufferData(); // Do something with the buffer
                }
                readingString = false; // Finish reading
                break;

            default: // Anything that's not > or <
                // If we are reading the string and the buffer isn't full
                if (readingString && charPointer < 78) {
                    // Add the character to the buffer and increment the pointer
                    buffer[charPointer++] = incoming;
                    buffer[charPointer] = 0; // Don't forget to terminate the string
                }
        }
    }
}

So the reception of a < starts the string reading, the reception of a > stops it and triggers the processing of the string, and anything else (while we are reading the string) gets added to the buffer.


Disassembling a RC car for a Arduino Robot I am looking at making an Arduino robot car. I have a RC car( photos below). I was wondering if I could take the chassis of the car and modify it to make it Arduino controlled, if so how could I do that?(I have an Arduino UNO R3). I would like to make it into a wall avoiding robot. I have never soldered a thing in my life, and I don't own a soldering iron.

Sometimes modifying something can be harder than starting from scratch. This is probably one of those cases, but it is over all not too difficult if you have the courage.

Start with a good example, like this robot.  It will give you an idea of what hardware you must add to your RC car and how to program the Arduino.


How do I listen for a sound that matches a pre-recorded sound? I'm working on a project that uses an Arduino Uno to listen for a bell ring and then uploads to a web server the exact time the bell was rung using a WiFi Shield.

I want to know how I can listen for the bell ring (a three second long high pitch tone) and be able to detect that that's what the Arduino heard. I think the best way may be to pre-record the sound and then the Arduino will constantly try to match the incoming sounds to the prerecorded sound. I'm wondering how I could go about doing this (or are there better methods).

The bell sounds kind of like this: bell sound

About the simplest starting point is to use an FFT (fast Fourier transform) library (like ArduinoFFT at openmusiclabs.com) to characterize the spectrum of an audio stream.

[Edit: An alternative method (digital bandpass filter) is mentioned below.]

Audio typically is made up of many frequencies of many amplitudes and phases, mixed together.  FFT sorts some of that out; it estimates the amplitudes of the various frequencies that make up a bit of audio.

The general idea is to use an Arduino ADC to take readings of an audio voltage for a fraction of a second, then use FFT to convert the large set of readings to a small set of numbers, in eg a set of 32 or 64 frequency-bins, to represent amplitudes in given frequency ranges.  For example, if the sound during a sample is a mix of five sine waves at five frequencies, the bins those five frequencies are in should have large numbers assigned, while other bins should have small numbers.

The approach would amount to sampling at 10KHz for 0.1 second or so, computing an FFT with 32, 64, etc. bins in the next 0.1 second, and comparing bin counts to a training pattern.  Whenever bin count patterns match reasonably well, start a three-second timer; if several seconds of matching samples occur, declare a match.

If the bell is electronically generated and mostly a mix of pure sine waves, then its sound will have an easily recognized spectrum.  But if the sound source is buzzy and there is background noise, it may be difficult to compare spectra.  See eg
• Comparing an audio signal with a previous 'taught/profiled' signal
• How do I compare chords played on a guitar with a known sample?
• How do I compare 2 audio files, returning a percentage of difference
• What does the phase of a FFT bin of an audio signal represent?
• Sound pattern matching using Fast Fourier Transform in Windows Phone
• How do I go about detecting whistles, pops and other sounds in live audio input?
• The Frequency Domain
Section 3.4: The DFT, FFT, and IFFT

An alternative: digital bandpass filter

Digital bandpass filters are based on processing a signal in a way that detects the amplitude of the signal's frequency component within designated limits.

For theoretical background see wikipedia's Digital filter article.  Also see Vaseghi, Chapter 5, Digital Filters, (eg section 4.6.6, Design of Band-Pass FIR Filters) pdf file and
ECE438 digital filter design lecture notes
pdf file.

You can use MatLab or Octave to do most of the work of designing a filter.  For example, if you have the Signal package installed and loaded into Octave, commands like

v=cl2bp(30, 0.48*pi, 0.52*pi, [0.02, 1.02, 0.02], [-0.02, 0.98, -0.02], 2^11);
freqz(v);
v

will compute coefficients for a Constrained L2 bandpass FIR filter, plot the freqency response (as below), and display the 60 coefficients.  To use the filter, copy the 30 non-zero coefficients into a program, set up a rolling array of readings, and at each sample compute a new filtered value.  If at some point high filtered values occur, and if they recur for about three seconds at the bell's frequency or twice its frequency, then the bell is ringing.  Note, there are other kinds of bandpass filters; the Constrained L2 bandpass FIR filter is shown for convenience, but other kinds may be better.

If you are unfamiliar with signal processing, you might need to try the following approach:
1, On your development system, obtain a few seconds of audio to use for tests. (Eg, allocate two buffers of several dozen bytes each; fill one buffer while using the other buffer to send data from the Uno to your development system.  Use (eg) Serial.write(buf, len) and a high data rate, eg 115200 bps, to send binary data, with three ADC readings packed per four bytes.)
2, Use Octave or similar software to try out several different FFT or filter approaches.  You would use FFT to determine the bell's fundamental frequency and then could try out digital bandpass filters while developing a recognizer.  You can also use mkfilter to design filters to try out in C programs on your system, and should be able to iterate more quickly while developing your approach than if you were developing it using the Uno.  When you get satisfactory results on your development system, you then can code a sketch to test the technique on your Uno.

Note, for a given filter order, filters implemented using fixed-point integer arithmetic on an Uno can handle more samples per second than those implemented using floating arithmetic.  An Uno might support 50000 to 100000 floating multiplies and adds per second (1,2,3,4), vs. two to four times as many fixed-point operations per second.  If your filter uses a dozen floating point ops per sample, your sample rate probably would have to be under 5000 samples per second.  If it uses half as many floating ops or uses fixed point instead of floating point, your sample rate could be twice as much.


GSM dongle instead of GSM shield? I googled for this problem many times and ended up with no results, so I decided to post it here.

Can we use a GSM Dongle (usb dongle) instead of a GSM shield (like SIM900 module) to send and receive SMS in Arduino? If so how it is possible?

Not directly. The standard Arduino Uno doesn't have the hardware/software necessary to act as a USB host, which means it can't talk directly to other USB devices.

You might be able to get it work via a USB Host Shield. I don't know how compatible that is with GSM dongles though because I assume you can't install drivers on it. Additionally, if you're using a shield anyway, you might as well use a GSM shield.

If you're able to get an alternative board then another possibility might be the Arduino Yún. It has a USB host built-in which is operated by the Linux part of the board. I don't know for certain that it would handle a GSM dongle, but it may be worth looking into.


Power small hobby motor using Vin pin on Arduino and 9V battery, safe? I want to power a small motor with a 9V battery and control it with PWM using an Arduino Leonardo. I know I can power the motor separately, but this introduces the problem of needing a battery to power the motor (9V battery) and another power source to power the Arduino (another 9V battery?)

Would it be safe to simply power the Arduino with a 9V battery and use the Vin pin on the board (which is unregulated and outputs directly the power source powering the Arduino) to drive the motor? That way, I power everything from the 9V battery, and use a transistor to drive the motor.

Thanks a lot!

Steve.

If you use a transistor circuit as shown below, back EMF would not cause any trouble.


serial communication dead slow after a while I'm workin on a node for blender to control an arduino. I notice it goes really slow after a while so I isolated the problem.
It is good in maintaining 60 frames a second, then after around 40 seconds (pretty exact), it drops to a pretty exact 1 fps for some reason.

What could be going on?

import serial
import time

ser = serial.Serial('COM3', 115200)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100n"
    ser.write(numIn.encode('ascii'))
    time.sleep(1./60)

arduino code:

// special thx to  Nick Gammon

const unsigned int MAX_INPUT = 50;

unsigned long delay_time = 300;
unsigned long last_toggle_time = 0;
int current_state = LOW;

void setup () {
  Serial.begin (115200);
  pinMode(12, OUTPUT);

}

void process_data (const char * data) {
  Serial.println (data);
  delay_time = atoi(data);
}

void processIncomingByte (const byte inByte) {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte) {

    case 'n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      process_data (input_line);
      input_pos = 0;
      break;

    case 'r':
      break;

    default:
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }
}

void loop() {

  while (Serial.available () > 0) {
    processIncomingByte (Serial.read ());
  }

  unsigned long m  = millis();

  if (m > last_toggle_time + delay_time) {
      current_state = current_state == HIGH ? LOW : HIGH;
      digitalWrite(12, current_state);
      last_toggle_time = m;
  }

}

If you print from arduino to serial and you don't read it then the buffer gets full. Causing it to go in a second delay. So make sure you read as well when you send data over.

A short sleep is required between the sleep and the read for some reason. Else it hangs.

import serial
from time import sleep

ser = serial.Serial('COM3', 115200)
sleep(1)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100"
    ser.write((numIn + '\r\n').encode())
    sleep(1./120)

    inp = ser.readline()
    print(inp.decode("utf-8"))
    sleep(1./120)


How to measure free RAM on an Arduino Due in Runtime? I use this Library to measure my free RAM on a Mega in runtime. But this Library does not work on the Due.

As mentioned by Mikael Patel in a comment, the library from Arduino-MemoryFree
 should do it. A minimal sketch that seems to work on the Due:

extern "C" char* sbrk(int incr);

int freeMemory() {
  char top;
  return &top - reinterpret_cast<char*>(sbrk(0));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.print ("Free memory is: ");
  Serial.println (freeMemory ());
}  // end of setup

void loop () { }

I'm not totally convinced that this gives the correct figure. The figure returned by the library above for my Uno was too high (2297 bytes).


Send commands to Arduino from the WEB I need to send Arduino some instructions from the web. Basically I would have a web app with a few buttons, and when I press them they send an instruction to Arduino to move for example a motor or turn a lamp. This has to function remotely, so not locally.

I'm using an Arduino Yùn.

How should I do this? Websocket? How? Thanks!

It becomes lots easier if you see the yun as a linux computer with a arduino connected over serial.
Then the question becomes: what is the best way to send commands over the internet to a (linux) computer.
Answer: there are so many ways because there is no best way.
What are the main key drivers:
Your linux computer needs to be reachable from the internet. That means opening your local network(firewall). The firewall is there for a reason. Do you have the skills to open your firewall and still be safe? If so you can run a service (lots of options) and reach your yun from anywhere on the internet. Just as you do locally.

If not you will need to go to a polling system. You use a server which is on the internet and send you request to that server. Your yun polls that server to get the messages you send.

There is a third option: If you can open your firewall from the internet, and you are the only user of the service and you very rarely need the service you can temporarily open the firewall when you need it
.


Arduino for push notifications to phone I'm interested in using an Arduino for a project for taking information and sending it through a phone application. I was wondering what the cheapest option there is for an arduino with internet capabilities. From what I see, a lot of articles list they use UNOs with shields for wifi/ethernet. After looking these up, I noticed that they can get a little pricey. Is there any alternative options I may be overlooking? Thanks.

You could look into buying an ESP8266 WiFi module (cca. 7$) and add it to your existing Arduino. If you're not constrained with money that much I would then recommend look up Arduino Industrial 101, which comes with WiFi out of the box. You could then use MQTT protocol to send messages to a broker and your phone. There are alot of nice tutorials online on MQTT.


Is the Arduino bootloader really the Atmel bootloader? Can I use Flip to upload? I've been asked to do a small project using an Ada BlueFruit board. It has a ATMega32U4. The 32U4 comes from the factory with a bootloader pre-installed. I've never used an Arduino before, but I have used AVR a bit in the past. Is the Arduino bootloader actually the one that came pre flashed from the factory? Does it even matter if it's the same bootloader as far as Flip is concerned?

Can I use the Flip batchisp utility to load my application code? We don't have a programmer handy and I don't want to muck up the bootloader on the board.

It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". I'd much rather continue writing straight AVR code in Atmel Studio. Is there anything I need to take into account when writing my application code? For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

Arduino uses a different (second) bootloader, next to the DFU one that build into the 32u4.


Control a motor with a button Code:

int motorPin = 9;  // the pin the motor is connected to

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

void loop()
{
 motorOnThenOff(); //motorAcceleration
}

void motorOnThenOff(){
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  digitalWrite(motorPin, HIGH); // turns the motor On
  delay(onTime);                // waits for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turns the motor Off
  delay(offTime);               // waits for offTime milliseconds
}

void motorOnThenOffWithSpeed(){

  int onSpeed = 200;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 50;  // a number between 0 (stopped) and 255 (full speed)
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
  delay(offTime);                   // waits for offTime milliseconds
}

void motorAcceleration(){
  int delayTime = 50; //milliseconds between each speed step

  //Accelerates the motor
  for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }

  //Decelerates the motor
  for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }
}

This code spins the motor. In the circuit, I have a button which I want to toggle the spinning of the motor.

This is the circuit:

https://circuits.io/circuits/4267039-spin-motor-spin/edit

How would I make it so that the button toggles the spinning of the motor? like a fan and its switch?

add this variable at the top of your program:

const int buttonPin = XX;   // the pin for the button
bool bState = false;

in the setup() function:

pinMode(buttonPin, INPUT_PULLUP);
// in case INPUT_PULLUP is not defined, comment the above line and uncomment below
//pinMode(buttonPin, INPUT);
//digitalWrite (buttonPin, HIGH);  // enable internal pull-up

in the loop() function, change your code with this:

update_bState();

if (bState) { digitalWrite(motorPin, HIGH); }
else        { digitalWrite(motorPin, LOW); }

then, at the end of your program, add the getButton function:

void update_bState(void)
{
    static bool buttonDone = false;
    static uint16_t timeButton;

    if (!digitalRead(buttonPin))
    {
        if ((!buttonDone) && ((uint16_t) (millis() - timeButton) > 100))
        { // Do once when button is pressed for at least 100ms (debounce)
            bState ^= true;     // Toggle button state
            buttonDone = true;
        }
    }
    else
    {
        buttonDone = false;
        timeButton = millis();
    }
}

Now that all the work is done, you should add acceleration when launching and deceleration when launching and stopping :D

By the way, I did not tested any code, so there may be some typo errors...


Renaming pins in sketch I'm trying to rename pins so that they post as some kind of alpha-numeric combination in a database.  For example, if I define the following....

#define APLHA 0
#define BRAVO 2
#define CHARLIE 5
#define DELTA 6

...I would like to rename the output of the pins, as recorded in the db, as something other than 0, 2, 5, and 6 (or whatever pin is used). Let's say A, B,C, and D for the purposes of this exercise.

Is this just as simple as creating if() function that is called upon prior to posting to the db (ex. if 0 then A, if 2, then B, etc)?  I feel like there must be a better, dare I say more elegant(?), way of doing this?

Current output:
PIN | VALUE
0  |   1
 2  |   1
 5  |   0
 6  |   0

Desired:
PIN | VALUE
 A  |   1
 B  |   1
 C  |   0
 D  |   0

If I understood your question correctly, you're looking for something like this:

static const byte PIN_NUMBER[4] = { 0, 2, 5, 6 };
static const char *PIN_NAME[4] = { "A", "B", "C", "D" };

// and use them like this:

void Log(byte index)
{
  byte val = digitalRead(PIN_NUMBER[index]);
  Serial.print(PIN_NAME[index]);
  Serial.print('|');
  Serial.println(val);
}

void setup()
{
  for (byte i = 0; i < 4; ++i) pinMode(PIN_NUMBER[i], INPUT);
}

void loop()
{
  Serial.println("PIN|VALUE");
  for (byte i = 0; i < 4; ++i) Log(i);
  delay(1000);
}

Also, in the special case of "A", "B", "C", "D" as pin names, you don't really need the PIN_NAME array, instead of

Serial.print(PIN_NAME[index]);

you can use:

Serial.print('A' + index);


Trying to verify that Arduino Pro Micro ISP is working I'm trying to program an Arduino Pro Micro with another Arduino Pro Micro. The purpose is to verify that I can use this Pro Micro board reliably as an ISP to program another Arduino device that does not have a USB interface.

These are actually Pro Micro clones but they seem to work quite well using the Arduino Leonardo profile. I'm following this pinout.

Here is the photo of the setup:

The "red" Pro Micro is set up as ISP using the stock ArduinoISP sketch (didn't think anything needed changing). The "white" Pro Micro is the one I'm trying to program.

The pins are connected, 5V - 5V, GND - GND, MISO - MISO, MOSI - MOSI, SCLK - SCLK, Pin 10 - Pin 10 (reset? this might be wrong).

I've confirmed the ISP sketch is running by the green heartbeat LED. The three LEDs on the red board are connected to pins 7 (top), 8, 9 (bottom), with 9 being the heartbeat.

I loaded the Blink sketch and changed the LED pin to pin 9 since the default pin 14 on the white board is being used as the MISO pin for programming.

In the IDE, I set the board to Arduino Leonardo, port to the red board's port, programmer to "Arduino as ISP" and ran "Upload Using Programmer".

The only output I get is:

avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

Since I'm really just beginning all of this, I'm a bit confused what might be wrong and what could be a next troubleshooting step. Any help appreciated.

As Mikael Patel notes, pin 10 on the programmer Pro Micro should run to RST on the target.

That might or might not fix the problem.  In some previous instances of the “Yikes! Invalid device signature” [1,2] bad breadboard connections turned out to be the problem.  I suggest you run a second (or even a third) set of jumpers in parallel with the first set.  Of course use matching colors to avoid confusion.


Adafruit ImageReader Library 2.3.5 added several library dependencies Why has Adafruit ImageReader Library v2.3.5 recently added six dependencies on other libraries for hardware I'm not using?

I used the v2.3.2 of the Adafruit ImageReader Library successfully two months ago. An example sketch worked fine with my ILI9341 3.2" display and its SD card.

Now there is an updated v2.3.5 available but the library manager wants to add six more "dependency" libraries:
- Adafruit ST7735 and ST7789 Library
- Adafruit seeswaw Library
- Adafruit HX8357 Library
- Adafruit SSD1351 library
- Adafruit SSD1331 OLED Driver Library for Arduino
- Adafruit EPD

As far as I know, the ILI9341 uses none of the hardware that corresponds to the six libraries it's trying to drag in. I don't want unneeded dependencies and don't want the code bloat.

If I don't accept the additional libraries, my sketch fails to compile. The error message is "C:\Users\barry\Documents\Arduino\libraries\Adafruit_ImageReader_Library\Adafruit_ImageReader_EPD.h:18:10: fatal error: Adafruit_EPD.h: No such file or directory"

However, EPD code is for "e-paper displays" which does not apply to my ILI9341 which is a TFT display. I don't think EPD code should be a real dependency.

Kindly redirect me if there's a better place to ask.

If you don't use the functions of the ImageReader library, which use the additional libraries, your compiled code will not contain code from the additional libraries.

The Adafruit ImageReader library may have functions which use other libraries and the libraries are required for compilation. But at linking the compiled units which are not used by your code and even parts of the compiled units which are not used by your code are not put in the resulting hex or bin file.


avrdude: stk500_recv(): programmer is not responding Arduino IDE is throwing this error when uploading sketches - avrdude: stk500_recv(): programmer is not responding

The problem arose just after I uploaded a blink sketch to my Arduino Mini, which worked absolutely fine. After the successful upload I tried to upload a different sketch and got the error.

I thought I had destroyed the boot loader somehow and was about to get out the Bus Pirate for ICSP but I decided to try another Arduino Mini I had lying around (albeit from another manufacturer) and got the same error.

So I'm convinced it's a driver issue as I successfully uploaded a sketch (it still runs as we speak!) then just magically without changing ANYTHING I can no longer upload.

In a futile attempt to get back to work I've done the following:
Switched the RX-TX lines (clearly not the issue as the first upload worked)
Used a different FTDI cable
used a  different programmer
(FTDI 5V/3.3V USB to TTL Basic FT232 FIO Programmer)
(USB to TTL Serial UART RS232 Adaptor (PL2303HX)
I'm fairly certain these use different drivers - FTDI and Prolific

Please help me I'm about to murder something :'(

Screencaps of error and device manager - Imgur

Is it this?

"To upload a new sketch to the Arduino Mini, you need to press the reset button on the board immediately before pressing the upload button in the Arduino environment."

https://www.arduino.cc/en/Guide/ArduinoMini


Barebones 328p, 2xAA vs 3xAA, which will last longer? So im just running a 328p at 8mhz with the internal oscillator. Datasheet says 1.8 to 5.5v is voltage range.

Will 3xAA in series (~4.5v) last longer than 2xAA in series (~3v), assuming all batteries have the same capacity, theoretically each option should have the same mAh but does the difference in voltage affect things ?

Yes, running at a higher voltage will consume more current.  In the datasheet you have this nice graph:

I have highlighted the two voltages at 8MHz for you. At 4.5V you would typically be using about 4.7mA.  At 3V you would be using around 2.8mA.  That's not taking into account anything else in your circuit of course - just the ATMega itself.


Disconnect Ethernet Shield I'm trying to use the Ethernet Shield and the EasyVR (voice recognition) together.
The Ethernet shield uses the same pins that the EasyVR, but the easyVR works fine if I don't call Ethernet.begin(). Is there a way to disconnect the ethernet shield in order to be able to use the EasyVR again?

I haven't seen any method like "release" or "disconnect" in the Ethernet's class.

Thanks!

You have correctly determined the root of the problem, both shields are trying to use the same pins. To work around this we need to know which pins are being used, and for what.

The Ethernet Shield documentation reveals the following:

  The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

https://www.arduino.cc/en/Reference/Ethernet

The documentation for Sparkfun's EasyVR library isn't as explicit, but one of the examples gives us another clue:

#if defined(__SAMD21G18A__)
  // Shield Jumper on HW (for Zero, use Programming Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_MONITOR
#elif defined(SERIAL_PORT_USBVIRTUAL)
  // Shield Jumper on HW (for Leonardo and Due, use Native Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_USBVIRTUAL
#else
  // Shield Jumper on SW (using pins 12/13 or 8/9 as RX/TX)
  #include "SoftwareSerial.h"
  SoftwareSerial port(12, 13);
  #define pcSerial SERIAL_PORT_MONITOR
#endif

#include "EasyVR.h"

EasyVR easyvr(port);

EasyVR-Arduino/examples/TestEasyVR/TestEasyVR.ino

This block of code is determining how to set up the serial communication. The first two if statements are for different boards, but the third one sets up the software serial connection... and it says there are two options, pins 12/13 OR 8/9! If there are two options, there must be a way to switch it on the board itself.

And sure enough! Check out that white box labeled "SW Serial Pins". Jackpot!

Here's what the manual has to say:

  On the bottom side of the board there are two SMD resistors that you can move to select the two pins of
  Arduino that the EasyVR will be connected to when in Software Serial mode (Mode Jumper on SW).

  RX – Software Serial Receiver pin

  D12 – Use digital pin 12 as serial receiver (default)
  D8 – Use digital pin 8 as serial receiver

  TX – Software Serial Transmitter pin

  D13 – Use digital pin 13 as serial transmitter (default)
  D9 – Use digital pin 9 as serial transmitter

  The choice of pins 12-13 is maintained for backward compatibility with the previous hardware revisions of
  the EasyVR Shield. However those pins may also be used for the SPI interface, so another choice of pins 8-
  9 is provided. If you want to use different pins make sure the receiver pin supports change interrupts.


Convert JSON into string for MQTT I am trying to publish json object into string with following snippet

JSONVar data;
data["chipid"] = chipId;
data["co2_equivalent"] = co2_equivalent.c_str();
data["tvoc"] = tvoc.c_str();
data["h2_signal"] = h2_signal;
data["ethanol_signal"] = ethanol_signal;
data["humidity"] = humidity;
data["temperature"] = temperature;
data["absolute_hum"] = v.absolute_hum;
data["co2_equivalent_baseline"] = co2_equivalent_baseline;
data["tvoc_baseline"] = tvoc_baseline;

String data_json = JSON.stringify(data);
Serial.print(data_json);
Serial.println();
client.publish("/devices/data", data_json);

This give me following error during compilation.

  /Users/ubuntu/Desktop/Arduino/data_collection/esp32-svm30-mqtt.ino/esp32-svm30-mqtt.ino.ino: In function 'void loop()':
  esp32-svm30-mqtt.ino:271:46: error: no matching function for call to 'PubSubClient::publish(const char [14], String&)'
       client.publish("/devices/data", data_json);
                                                ^
  In file included from /Users/ubuntu/Desktop/Arduino/data_collection/esp32-svm30-mqtt.ino/esp32-svm30-mqtt.ino.ino:2:0:
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:141:12: note: candidate: boolean PubSubClient::publish(const char*, const char*)
      boolean publish(const char* topic, const char* payload);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:141:12: note:   no known conversion for argument 2 from 'String' to 'const char*'
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:142:12: note: candidate: boolean PubSubClient::publish(const char*, const char*, boolean)
      boolean publish(const char* topic, const char* payload, boolean retained);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:142:12: note:   candidate expects 3 arguments, 2 provided
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:143:12: note: candidate: boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int)
      boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:143:12: note:   candidate expects 3 arguments, 2 provided
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:144:12: note: candidate: boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int, boolean)
      boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
              ^
  /Users/ubuntu/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:144:12: note:   candidate expects 4 arguments, 2 provided
  Multiple libraries were found for "PubSubClient.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/PubSubClient
  Multiple libraries were found for "Arduino_JSON.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/Arduino_JSON
  Multiple libraries were found for "svm30.h"
   Used: /Users/ubuntu/Documents/Arduino/libraries/svm30
  Multiple libraries were found for "Wire.h"
   Used: /Users/ubuntu/Library/Arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/Wire
  Multiple libraries were found for "WiFi.h"
   Used: /Users/ubuntu/Library/Arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/WiFi
   Not used: /Applications/Arduino.app/Contents/Java/libraries/WiFi
  exit status 1
  no matching function for call to 'PubSubClient::publish(const char [14], String&)'

Line Serial.print(data_json) does print it in serial monitor.

Update :

If I doclient.publish("/devices/data", data_json.c_str());, it gets compiled, but data doesn't appear in mqtt.

Serial.print(data_json.length()); prints 236

Is my json to string conversion correct ?

Please note: the question originally had no mention of trying to use c_str() - so I'm not a retard

Point 1 JSON actually is a string
Point 2 your data_json varibale is a String
Point 3 client.publish doesn't work take String as the payload argument, it takes either const char * or const uint8_t *

So, what you can simply do is use Strings c_str method to pas a const char * as the payload

i.e.

client.publish("/devices/data", data_json.c_str());

Point 4 - if you read the pubsubclient documentation, you'll see that

  The maximum message size, including header, is 128 bytes by default. This is configurable via MQTT_MAX_PACKET_SIZE in PubSubClient.h. Longer messages can also be sent with the publish_P() method.

so what you may be experiencing now is a message size too big for pubsubclient to handle - set a larger packet size before including the PubSubClientHeader.h

#define MQTT_MAX_PACKET_SIZE 1024
#include <pubsubclient.h>

If that also doesn't work, try

client.publish_P("/devices/data", data_json.c_str());


Convert uint8_t array to ascii character for serial transmission I am trying to send packets of via bluetooth data that include 6 bytes read from a sensor and stored in a uint8_t array. Instead of sending over the data as numerical digital, I would like to send the ASCII character of each of the bytes. I am doing this to reduce the size of my data packets and make it easier to interpret the incoming data.

uint8_t* temp = readBufferData(FIFO);

for (int i = 0; i < 6; i++)
{
    Serial.write(temp[i]);

}

Read buffer data returns a pointer to a uint8_t array read from a FIFO buffer.
When I use Serial.print, I get the following output, which makes sense.
22163226094255
One question is, when I use Serial.print on a single character, is it transmitted a single byte, or is it actually sending the decimal digital of the number, anywhere from 1-3 bytes?

When I use the Serial.write, however, I get something like the following
DÿÂ?ÁÏ?ÌÆ?Ûµ?Ë½?ÔÀ?Ð¿?ÃÕÓÑËÐTÿÀ?Ï3ÿÉ?¹4ÿÐ?Ê<ÿ½?µfÿ¼?ìNÿÐ?×Â?ÊÚ?×¿?Å
Also, these data display much more slowly on the screen, than normal.

How can I send each uint8_t value by sending over the corresponding ASCII character for serial transmission?

Thanks!

You don't "convert" anything. A character is just a human representation of an 8-bit value.

Instead you just need to change what the compiler thinks the data represents (from a human perspective).  The simplest way of doing that is to either cast the uint8_t values to be char values, or to write each one individually as a raw value.

The latter way:

myBluetoothSerial.write(myData[0]);
myBluetoothSerial.write(myData[1]);
myBluetoothSerial.write(myData[2]);
myBluetoothSerial.write(myData[3]);
myBluetoothSerial.write(myData[4]);
myBluetoothSerial.write(myData[5]);

Or, with a loop:

for (int i = 0; i < 6; i++) {
    myBluetoothSerial.write(myData[i]);
}

or using a built-in variant of write that does the loop for you:

myBluetoothSerial.write(myData, 6);


attiny85 and arduino - analogRead + pwmOut I am using the Arduino IDE to program the attiny85. I want to take an incoming analog reading, then based on that reading, output a specific PWM value. Here's my circuit:

and here's my code:

// to run on attiny85

const byte pwmPin = 0;
const byte analogInPin = A2;

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

void loop() {
  int analogIn = analogRead(analogInPin);
  analogWrite(pwmPin, analogIn);
}

should be very simple- I have no problems uploading code to the attiny85, and no problems with simple tests like outputting a specific PWM value (not based on the analog read). but when I try to combine the two- read, then write that value, I can't seem to get things to work. In this circuit for example- I get a reading of 1023 (5v) on the arduino micro- instead of a reading of ~ 790 (3.85v) which is what I should expect. I've used a multimeter to verify the voltages in this circuit- so I think I must either be doing something wrong with my expectations of how to wire up or program the attiny85.

Analog read is 10-bits (2^10 = 0-1023 range), analog write is 8-bits (2^8 = 0-255 range). Ditch the lower two bits of the result either by doing:

analogIn = analogIn >> 2;

which can be shortened to:

analogIn >>= 2;

Or you can use the rather complex map function:

analogIn = map( analogIn(0, 1023, 0, 255) )


How much voltage and amps for 2 SG90 servos? Question is pretty straight forward: How much amps and voltage do I need for 2 SG90 servos? I want to use 4 but you might already know that Arduino Uno only has 2 5V ports.

The SG90 servo datasheet is here:
SG90 Servo Datasheet
As you can see, the voltage specification is 4.8 - 6.0 Volts.  But you do NOT want to power this or any other servo via the Arduino.  Servos are quite "noisy" electrically and this can cause instabilities with your Uno.
You want to supply power to the servo directly from a +5V power supply.
I don't see the current draw for this servo specified so you will need to do your own measurements based on the loading of the output shaft.  Be aware that these draw more current with increased load on the shaft.
As far as the control signal, the Arduino Uno can certainly drive it via its PWM outputs.


Passing class member function as argument I need to pass a class member function to server.on, unfortunately i get an error.

  error: no matching function for call to 'ESP8266WebServer::on

I have done some searching but could not understand anything I found. No simple explanation.

This works:

void handleRoot(){}
server.on("/", handleRoot);

This doesn't:

void myClass::handleRoot(){}
void myClass::setup(){
    server.on("/", handleRoot);
}

The second argument to server.on is

typedef std::function<void(void)> THandlerFunction;

Unfortunately I have no idea what it means.

It's quite common question related to C++ programming.

The extensive explanation can be found here.

The short answer is: it's very different from taking the address of a regular function.

Workarounds (that might or might not work for you, depending on what else you need that function to do) are:

make it static
declare it as friend function, rather than member function

Either way, the point is that it should not be something associated to an instance of the class, but rather to the class as a whole.


Point-to-point Communication of Arduinos with RFM LoRa Shield In this tutorial, it sends a string from a node to the other node. But if I want to send an integer instead of a string, how should I change the code?

Serial.println("Sending to rf95_server");
// Send a message to rf95_server

String radiopacket = "Hello World #";
radiopacket += String(packetnum++);
radiopacket += " from ";
radiopacket += node_id;

Serial.print("Sending "); Serial.println(radiopacket); delay(10);
rf95.send((uint8_t*)radiopacket.c_str(), radiopacket.length()+1);

Serial.println("Waiting for packet to complete..."); delay(10);
rf95.waitPacketSent();

The simplest way is to just cast the integer into an array of 2 bytes and send that.  Assuming int temperature:

rf95.send((uint8_t *)&temperature, 2);

To make it more portable you can use the size of an integer instead of 2:

rf95.send((uint8_t *)&temperature, sizeof(int));

Reading back, you just cast the buffer you have received as an integer, or combine the data manually (which may be safer since the buffer may be misaligned on a more powerful system than an 8 bit Arduino):

int temperature = buf[0] | (buf[1] << 8);

(Assuming it was sent from a little-endian 8-bit system).

If you want to send the number as plain text, so it can be easily read by a human, you want to print it to a string:

char temp[6];
sprintf(temp, "%d", temperature);
rf95.send((uint8_t *)temp, strlen(temp));


Drive 12V Piezo Buzzer (Arduino) I want to drive this 12V piezo buzzer:
http://www.conrad.com/ce/en/product/130256/Kemo-L001-High-Freqeuncy-Piezo-Speaker-Component-12-24-V

This is the circuit I am using.

The Arduino is powered by a 12V DC adapter trough the DC IN jack.

I have tested the following code:

void setup() {
}

void loop() {
  int pinOut = 9;
  int freq = 10;
  int duration = 100;
  while(1)
  {
    for(int i=0; i<1000 ; i++)
    {
      tone(pinOut, freq*i, duration);
      delay(duration * 1);
      noTone(pinOut);
    }
  }
}

When run I can hear the tones changing but is really really low. I have measured the voltage between buzzer pins and it is 12V (as expected) so the MOSFET seems to be properly working.

This piezo buzzer should be louder (I have tested it with this 12V tone generator http://www.kemo-electronic.de/en/Car/Modules/M048N-Ultrasonic-Generator.php )

I am making any mistake?
Thanks in advance!

The piezo element acts like a capacitor, not like a more-or-less resistive element as in a conventional speaker. You need to discharge the capacitor during the 'off' time or you just get a click and little sound after that. That's why your resistor helps. Push-pull would be much better, and an H-bridge would give you much more output (maybe too much for the speaker).

Also the IRZ44 is not specified to be driven from 5V (it's specified at 10V Vgs) so you may not get much current. Further, if you're trying to get 10's of kHz, you won't be able to drive the MOSFET gate that fast with a 1K resistor, in fact the Arduino may not be able to source enough current and you may have to use a gate driver.

If you can measure the capacitance and provide the frequency of interest, more specific recommendations would be possible. At 2kHz about 3K would be okay with a 10nF element, but that resistance would decrease with increasing resistance and with increasing capacitance, and at some point the power dissipation in the resistor will become excessive.

Edit: You can do something like the below with a 10nF/20kHz requirement:

simulate this circuit – Schematic created using CircuitLab

You could even duplicate the above circuit and add an inverter in series with one of the halves and get 24Vpp across the piezo, but you might want to use somewhat beefier transistors (Zetex perhaps).


What would the total current requirements be for these items? I'm using 5 of those 8mm NeoPixels + a 5V Trinket.

I'm trying to get a rough estimate of the current requirements that would have, assuming all 5 NeoPixels were running at full brightness "white" (255 RGB).

I'm voltage-regulated to about 150 mA from the Trinket and my current hunch is that those NeoPixels need more than that, but trying to confirm it.

According to the data sheet each LED takes a maximum of 3*20mA, so you are pulling 300mA.  You  are going to need a bigger power supply :(


Powering Arduino with Solar Panels Clearly, an Arduino can be powered with solar panels.

What is the most optimal configuration?
Can you recharge and discharge at the same time?
Is LiPO the best battery cache technology, or is there something more durable out there, for fielded deployment?
What are the most economic, and reliable ways to do this?

First of all you want to buy some solar panels or cells. Although they can be found on eBay for very cheap, but they not be as efficient as they say. I would say try to buy from a reputable dealer to see reviews on the product or trust that they work efficiently. Sparkfun datasheets are generally accurate and can be trusted.

Most optimal configuration: Do not use a regulator and some sort of step-up booster. Try the TPS61200 or TPS61202 chips. They will not regulate the voltage, they boost the voltage dynamically. This is much more efficient and therefore generates less heat. They work like a reverse voltage regulator, taking .3V to 5.5V and turning it into anywhere from 1.8V to 5V (xxx0) or 5V exactly (xxx2). Hack a USB B end and just connect the power lines to the Arduino.
Discharge/charge simultaneously: Yes, however I'm not sure how to. I believe that if you hook up a charger IC and a load, the voltage won't go through the battery, it will go through the path of least resistance. However, your battery wouldn't get charged then. This is outside the scope of the question, so I would recommend EE on how exactly to do this.
Is LiPO the best: Try a Lithium-Ion Battery. (A.K.A. Li-ion) According to this site:

  Although the lithium-polymer battery is sleeker and thinner, lithium-ion batteries have a higher energy density and cost less to manufacture.

Therefore, it seems like Li-ion is the best choice for you. Note: Since you are dealing with very dense batteries that if overvolted can go up into flames [Note: please mute your speakers!], make sure to go with Sparkfun/Adafruit/etc...
Economic way: If you don't mind a big "homemade" solar panel, go this way. Buy through eBay or a similar site solar cells. They are small plates that are connected to create a solar panel. Try looking for "grade B" or similar solar cells that work fine, they just may have minor imperfections. It won't be as pretty, but you'll save some cash.

See this EE.SE post for more information. One cool thing that I saw was:

  This is really cool. You can connect the Li-Ion voltage through an op-amp to generate a pulse wave, which can be picked up by your MPU to tell your bot to go charge –  Raaj Oct 18 '13 at 18:44

I'm not exactly sure how to do this, but it might be useful. I couldn't find anything online about it.


Which board/shield to generate (non-PWM) analog outputs? I am currently building a project involving a laser scanner (two galvanometers with mirrors that deflect a laser beam) that I want to control. The galvos need +-10V differential signals (and I'd like to have a least 12Bit) that I want create with some small board.

Most Arduinos I know use PWM to create an analog output which is not usable for this project. I found the Teensy3.1 which has at least one 12Bit DAC so that also doesn't work. An alternative would be a DAC breakout board like "MCP4725" but it would be nicer to just have a single board with no additional parts.

The best thing would be a small board with already two 12Bit DACs. (even If I had to upscale the voltage +-10v)

Is there a board I haven't found so far? Or have I missed a completely different approach?

For 12-bit dual DAC you want the MCP4822 which has two channels of 0-4.095V in 1mV steps.

The output of that you would then need to pass through a suitable amplifier arrangement with an op-amp giving a gain of 5 and adding an offset of -10V.  The gain would change the 0-4.095V to 0-20.475V, and the -10V offset would change that to -10V to +10.475V.  If you want to get more precise you could use an offset of -10.2375V (it's not easy to make an offset voltage that precise) then you would get -10.2375V to 10.2375V in 12-bit resolution.

It's doubtful you'll find a board already made up with that specific arrangement (it's fairly specialised) but it's not something that's hard to make - all the components are available as DIP or other through hole components, and the circuit for the amplification stage is pretty simple (check for non-inverting op-amp circuits online, there's millions), so building it up on strip board or matrix board would be easy enough.


calling a timer when a button is pushed I'm trying to call a function to keep an LED on for a certain amount of time. The function is called when the button is pushed but the LED stays on. I used the same code in the void loop before moving it into a function and it worked.

const int ledPin2 = 2;
const int buttonPin7 = 7;
const unsigned long onTime = 1000;
unsigned long previousMillis = 0;

//
void timer(){
    unsigned long currentMillis = millis();
    digitalWrite(ledPin2, HIGH);

    if (currentMillis - previousMillis >= onTime){
        digitalWrite(ledPin2, LOW);
        previousMillis = millis();
    }
}

void setup(){
    Serial.begin(9600);
    pinMode(ledPin2, OUTPUT);
    pinMode(buttonPin7, INPUT);
}

void loop(){
    int buttonState = digitalRead(buttonPin7);
    if (buttonState == HIGH) timer();
}

When your code:

if (currentMillis - previousMillis >= onTime){
    digitalWrite(ledPin2, LOW);
    previousMillis = millis();
}

was in the loop, it was executed multiple times, so when if (currentMillis - previousMillis >= onTime) eventually became true, it would set ledPin2 LOW again.
Now that you moved it to the timer funtion, it only gets executed once (and if (currentMillis - previousMillis >= onTime) never gets a chance to become true).

You need to introduce a loop in the timer function. It also looks like you have your currentMillis / previousMillis messed up. I think you are looking for something like this:

void timer(){

    unsigned long previousMillis = millis();
    unsigned long currentMillis = millis();
    digitalWrite(ledPin2, HIGH);

    while((currentMillis - previousMillis) < onTime) {
        // wait for a bit
        sleep(10);
        // update currentMillis
        currentMillis = millis();
    }

    digitalWrite(ledPin2, LOW);
}


STM32 "Blue Pill" Serial.print freezes Serial Monitor I am having difficulties when printing any type of variable using the Serial.print(ln) command.

The Serial Monitor becomes inactive after printing for approximately 7 - 15 times.

I currently have the STM32 Blue Pill Board, running Mac OS Mojave and Arduino IDE v 1.8.9

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

}

void loop() {
  float raw = analogRead(PA0);
  float voltage = (raw * 3.3) / 4096;
  Serial.println(voltage);
  delay(500);
}

Have you made sure to modify the board before using it?
This page mentions at least one resistor that you have to replace for the USB to "work".

The USB standard requires a 1.5 kΩ pullup resistor on D+, but this board is known to have a wrong value (R10 on the board). It ships with either a 10 kΩ resistor or a 4.7 kΩ resistor, but it should be replaced with a 1.5 kΩ resistor, or put an appropriate resistor value (e.g 1.8 kΩ) in between PA12 and 3.3V.
It is also true that some PCs are tolerant of incorrect value so, before you change the resistance, you can try if it works in your case.

I have had issues with bluepill boards myself in the past, but never had an issue like yours after fixing the resistor. (before that, I couldn't even flash the bootloader)
Try printing other things with the board, and see if there's any pattern to it cutting out. e.g. a string over and over again, or the same float over and over again.
Try different baudrates, or even SoftwareSerial to another board.


can I give the 9v input power for arduino mega 2560 using vin pin? I am using Arduino mega 2560. I have some doubts about powering my microcontroller.
Can I use the 9v battery to power my arduino through the VIN terminal?
I have uploaded an image. Check whether it is a correct method or not?

Yes!

  The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

  The power pins are as follows:
  - Vin. The input voltage to the board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

https://www.arduino.cc/en/Main/ArduinoBoardMega2560

Vin is the same as the external positive power input.


Mapping values from analog input giving unexpected values? Mega 2560

I am reading in values from 3 pots then mapping them to values between 0 - 255

#define REDPIN   7
#define GREENPIN 8
#define BLUEPIN  9

int red_pot   = A0;  // analog pin used to connect the potentiometer
int green_pot = A1;
int blue_pot  = A3;

void setup() {

  pinMode(REDPIN,   OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN,  OUTPUT);

  Serial.begin(38400); //Debug port
  Serial.setTimeout(50);
}

void loop() {

  int red, green, blue;

  red   = analogRead(red_pot);
  green = analogRead(green_pot);
  blue  = analogRead(blue_pot);

  Serial.print(" r = ");
  Serial.print(red);

  Serial.print(" b = ");
  Serial.print(blue);

  Serial.print(" g = ");
  Serial.print(green);
  Serial.print("\n\n\n");

  // map values
  red   = map(red,   20, 650, 0, 255);
  green = map(green, 20, 570, 0, 255);
  blue  = map(blue,  20, 570, 0, 255);

  Serial.print("red map : ");
  Serial.print(red);

  Serial.print(" green map : ");
  Serial.print(green);

  Serial.print(" blue map : ");
  Serial.print(blue);
  Serial.print('\n\n\n');

  analogWrite(REDPIN,   red);
  analogWrite(GREENPIN, green);
  analogWrite(BLUEPIN,  blue);
}

red & green behave as expected but blue is not, from the serial monitor...

When blue is at its lowest value,

When blue is at its highest value,

I have changed blue's analog pin assignment but the same issue.

Any clues what's happening?

EDIT #1

I thought it might be some int sign error so I changed the map operation to,

blue  = map(abs(blue), 20, 670, 0, 255);

It made no difference.

Note that the Arduino function "map" is really this:

long map(long x, long in_min, long in_max, long out_min, long out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

...so, if you pass a "minimum from" value which is less than the actual value you are mapping from you will get a negative number given your "minimum out" is zero.

In several of your examples you have set the minimum to 20 but pass a value of 19.  If your program is intolerant of negative numbers (for instance, how would a negative number effect the PWM hardware), consider testing for lower than minimum and higher than maximum values before using the map function.


Arduino Uno wiring and code with Parallax PMB-688 I'm new to Arduino GPS and am wondering if I could be pointed in the right direction regarding code and wiring when hooking up my Parallax PMB-688 to an Arduino Uno

The following link was suggested in the comments by user PhillyNJ. Adding it here as a community wiki answer:

http://playground.arduino.cc/Tutorials/GPS


How many times can I upload a program or sketch to my Arduino Uno Clone Board? I'm about to work on my very first project using arduino (I'm just about to buy one next week), and one of our professor says that we can only upload a program or sketch in an Arduino Uno Board for approximately 8 times. He also added that if we're using a clone version, it'll can only last for 2 sketch uploads. Is this true or is he bluffing? Thank you in advance.

He's talking complete and utter gibberish.  To quote from the ATMega328P datasheet:

  High Endurance Non-volatile Memory Segments

  32KBytes of In-System Self-Programmable Flash program
  Memory
  1KBytes EEPROM
  2KBytes Internal SRAM
  Write/Erase Cycles: 10,000 Flash/100,000 EEPROM
  Data Retention: 20 years at 85°C/100 years at 25°C(1)
  Optional Boot Code Section with Independent Lock Bits

  In-System Programming by On-chip Boot Program
  True Read-While-Write Operation

  Programming Lock for Software Security

So you have at least 10,000 uses out of it before it starts to go flakey.


Setting float to two decimal places I'm trying to set my temperature measurements to two decimal places. Currently what I get are six decimal places.
Here is my code:
#include "math.h"

...

(in loop)
temp1 = sensors.getTempCByIndex(0);
     temp1 = roundf(temp1*100)/100;

Once I push temp1 to Firebase realtime database there are sic decimals, such as 26.059999. I'm using dsb20 sensor for temperature measurements.
What could be wrong?
Thanks for your help in advance!

In addition to Majenkos answer:
A float cannot take any decimal number. It has a limited change and a limited resolution in that range you could say. So if often happens, that the flat (rounded) value is not a valid float. This is the case for 26.05. There is no valid float value, that is exactly 26.05. So the nearest valid float value is chosen. The following code would always print 26.059999:
float i = 26.05;
Serial.println(i);

since the variable i contains the float number 26.059999 (nearest valid float value to 26.06). That is the reason, why mostly the rounding of floats is only done directly with the outputting/printing. In that stage the number is not longer bound to the limitations of the float type (since it is internally not again saved in that type).


Arduino AD-converter tolerance I created a quite simple Arduino sketch:

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

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);

  float voltage = sensorValue * (5 / 1023.0);
  Serial.println(voltage);

  delay(1000);
}

I use the following circuit:

My multimeter measures 3.31 V, between the pin 3V3 and GND.

I get a sensorValue of 730 and a calculated voltage of 3.57 V. This is 8% higher that 3.3V. What is the tolerance by the AD-converter?

The absolute accuracy of the ADC in the ATmega328P when its clock is within its optimal range is given in the datasheet as 2LSB. This means that the actual value could be anywhere between 728 and 732.

Of course this depends on the accuracy of VCC, since it is being used as the ADC reference. This is why supply voltage measurements should be performed using the internal bandgap voltage instead.


Arduino Infinity Loop I'm new to this Arduino programming. So I want to ask about my current project. My lecturer told me to make a temperature sensor using an LM35, where a green LED will light up when below some certain temperature that I set. The same goes for yellow and red LEDs for medium, and high temperatures. The tricky part here is that I need to make sure my buzzer (piezo) is on forever if it reaches the high temperature, until I press a button to reset it.

This is my coding so far:

const int greenLed = 3;
const int redLed = 4;
const int yellowLed = 5;
float tempC;
int reading;
int tempPin = 0;
int speakerOut = 11;
const int buttonPin = 2;
int buttonState = 0;
long duration = 10000;
int tempo = 0;

void setup() {
// initialize digital pin 13 as an output.
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(2, INPUT);
pinMode(11, OUTPUT);
analogReference(INTERNAL);
Serial.begin(9600);
}

// the loop function runs over and over again forever
void loop() {
buttonState = digitalRead(buttonPin);
reading = analogRead(tempPin);
tempC = reading / 9.31;
Serial.println(tempC);
delay(500);

if (tempC < 30.00) {
//Serial.println("Temp LOW");
digitalWrite(3, HIGH);
delay(10);
}else {
digitalWrite(3,LOW);
delay(10);

}

if (31.00 < tempC < 33){
//Serial.println("Temp MED");
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(50);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(50);

}else {
digitalWrite(4,LOW);
digitalWrite(5,LOW);

}

if(tempC >= 34){
**WHAT SHOULD I FILL UP HERE TO MAKE SURE MY PIEZO BUZZER ON FOREVER**
}
if(buttonState = 1);{
digitalWrite(11, LOW);
}

}

Any help would be great. Or if you have a better idea on how to do this, I'm gonna love it.

You can use the toneAC library, which allows even better handling of piezo speakers then the standard "tone"-functions.

  Features: Nearly twice the volume (because it uses two out of phase pins in push/pull fashion)
      Higher quality (less clicking)
      Capability of producing higher frequencies (even if running at a lower clock speed)
      Nearly 1.5k smaller compiled code
      Bug fixes (standard tone library can generate some odd and unpredictable results)
      Can set not only the frequency but also the sound volume
      Less stress on the speaker so it will last longer and sound better

With the library you can do something like:

int freq = 1000
int vol = 10
int length = 0
boolean background = true

toneAC(freq, vol, length, background);

The tone now will play forever in the background, until you stop it with:

toneAC(0);