Minimal Arduino using ATmega32U4 I am a newbie and I would like to build my own minimalistic ATmega32U4 based arduino compatible board. Can anyone please tell me which parts resistors/capacitors (and maybe one status led) I need to connect it over usb to my computer? Thanks in advance.

Several Arduinos and Arduino-compatible boards use the ATmega32U4.
Many of them have published open-source plans that show exactly what components are used and how they are connected. They may not be the absolute minimal number of components, but it seems clear that you don't need more components than a known-working board:

1 ATmega32u4
1 16 MHz crystal
2 22pF ceramic caps (for crystal)
1 uF decoupling cap
1 pushbutton
1 10 KOhm pull-up resistor (for pushbutton)
1 LED
1 220 Ohm resistor (for LED)
1 USB socket
2 22 Ohm resistors (between USB socket and ATmega32u4)

Alas, there are two unnecessarily difficult hurdles between newbies and getting a new ATmega32u4 device connected over USB to a computer:

The ATmega32u4 and nearly every other device that communicates over USB is only available in SMT packages with pins at 0.8 mm pitch or even closer together.
Most people find packages with pins at 2.54 mm pitch easier to handle and plug into a breadboard.
Installing a bootloader into any new processor chip is often tricky.

As Russel already pointed out, you can save a lot of time by starting out with an Arduino or Arduino-compatible board that already has the chip soldered on and the bootloader programmed in, bypassing the above unnecessarily difficult hurdles.

A few Arduinos and Arduino-compatibles (with links to schematics, etc.) that use the ATmega32u4:

Bootloading an ATmega32u4 with Arduino
Teensy 2.0 (ATmega32u4 USB dev board)
Arduino Leonardo; Arduino Leonardo
Arduino MICRO
SparkFun Pro Micro (Arduino-compatible)
FLORA - Wearable electronic platform: Arduino-compatible
Adafruit Feather 32u4 Basic Proto
Installing Arduino Bootloader on an ATmega32u4; Installing Arduino Bootloader on an ATmega32u4


Paralellizing sensor data input I have a total of 15 sensors (analog and digital) connected to an arduino mega.  For my real-time control application, it's really really important that all data be collected simultaneously at regular intervals in time.  Is there any way to ensure that all data is collected at the same time?  How can I minimize the total lag time between the first and last sensors?

I would suggest looking into threading.

To minimize the time from the first read to the final read, an interrupt and an interrupt timer would probably be good. Have the interrupt timer fire after some interval and place all of your sensor reads in the Interrupt Service Routine (ISR).

I would also suggest staying away from functions that the Arduino platform provides, like delay(), digitalRead(), digitalWrite(), analogRead(). Those functions will add extra instructions to your sensor reads and waste clock cycles. The Arduino platform sacrifices speed for usability in some cases.

You might also want to look into using a real-time OS if this is a real-time application

UPDATE

The arduino will not support 15 true threads. if you look into The TimedAction class you might see something that you can use. Basically, timed actions occur after an interval and a specified function is called. However, if you have 15 timed actions all with the same duration, they won't all read at the same time, they will still have to read in some order, one at a time.

If you look into the source code for many of the functions you can see how they work. The Arduino source code comes with the IDE. A good place to start would be Arduino.h. If speed is a concern, you want to reduce as many clock cycles as possible, which means removing as many lines of code as possible. If you can do something without calling digitalRead() for example, you will save yourself some time.

A real-time operating system is an OS that is used in real-time systems. I find it helpful to think of a RTOS as a timing library that will help you, opposed to installing Linux on your arduino. There is plenty of material around the web on what a real-time system is and what a real-time OS does if you want to learn more.

The important part of an RTOS is that is guarantees that an action be performed before a deadline. So in your case, sensors are read before a given time. There are a couple RTOS's for the Arduino that google will find for you.


Power saving of atmega 2560 Is arduino code Consume More power other than "Avr Studio" Code?

Please tell some key points for power saving.
Processor on $ off Methodology.

There is nothing about the Arduino code that would inherently consume more power than using a different compiler, so no, it doesn't. What the code does you can change in either development environment.

Read Power saving techniques for microprocessors for a considerable number of tips about saving power.

Also see related threads about this question such as What are (or how do I use) the power saving options of the Arduino to extend battery life?


Keypad number input and store i'm stuck with a little problem. I need to create a program that can store a number via keypad (this number will be chosen by the user) and then do something with it. To be more specific i will create a temperature control in which the user will be able to input a value of temperature they need and then with this value control a heater, but that's another story, the main point here is that the program needs to be able to store a value via keypad.

i use the keypad library and some of its commands like getKey() and waitForKey() and so on.

thanks for your answers!

http://playground.arduino.cc/Code/Keypad#Example here is the setup for you, you should see, what you are pressing.

then try something like this:

int temp=0;
bool in_press=false;
void loop() {
  char key = keypad.getKey();
  if (in_press &&  key == NO_KEY){ in_press=false; return;} // key released
  if ( ! in_press ){
    if (key != NO_KEY){ // if key is just pressed - proceed it
      in_press=true;
      if (key == '*') {temp=0; return;} //cancel input
      if (key == "#') { do_something_with(temp); temp=0;return;} //accept input
      // key is '0'..'9' - add it to result
      temp= temp*10 + (key-'0'); // maybe check it temp is not too high ...
      return;
    }
  }
  // this pass of loop no new key was pressed, do anything else to do
  // if we want, we can test in_press to see, if key is holded or not
  // or ignore it at all
  do_other_stuff_like_blinking_leds_or_what();
} // end of loop()


Compiling error:passing as 'this' argument I am trying to make a small keyboard class to handle two buttons(in the future >2)  that are connected to my arduino UNO. The buttons being pressed are detected using interrupts. Here is the code:

Timer

class Timer{
  private:
    uint32_t start_time;
  public:
    Timer(){
      start_time=millis();
    }
    void mark(){
      start_time=millis();
    }
    uint32_t lapsed(){
      return millis()-start_time;
    }
};

Keyboard

class KeyboardBtn{
  private:
    const static byte clicksDelay=255;      //255 ms max
    struct btn{
      byte state=0;   //0->nothing;1-click;2-dblClick
      Timer clickDelay;
    };
    volatile static btn buttons[2];         //only two buttons for now

  public:
    KeyboardBtn(){
      attachInterrupt(digitalPinToInterrupt(2),this->int_handler_btn0,FALLING);       //Initially the pins are set to HIGH(pullup behaviour)
      attachInterrupt(digitalPinToInterrupt(3),this->int_handler_btn1,FALLING);
    }

    static void int_handler_btn0(){
      btns_handler(0);
    }
    static void int_handler_btn1(){
      btns_handler(1);
    }
    static void btns_handler(byte key){
        if(buttons[key].state==1 && buttons[key].clickDelay.lapsed()<=clicksDelay){
          buttons[key].state=2;
        }else{
          buttons[key].state=1;
          buttons[key].clickDelay.mark(); //Pressed one time? mark this and wait for second press
        }
    }
    byte stateChanged(byte key){
      //Function called to get key status
      byte temp_state=buttons[key].state;
      if(temp_state==1 && buttons[key].clickDelay.lapsed()<clicksDelay){
        return 0; //We still wait:don't know if it's a dblClick or single
      }else{
        buttons[key].state=0;
        return temp_state;
      }
    }
};
volatile KeyboardBtn::btn KeyboardBtn::buttons[2];

But the compiler gives me headaches(of course my code is wrong somewhere but he could just have kept quite about it):

  C:\Users....\Humidity.ino:
  In static member function 'static void
  KeyboardBtn::btns_handler(byte)':

  C:\Users...\Humidity\Humidity.ino:74:68: warning: passing 'volatile Timer' as
  'this' argument of 'uint32_t Timer::lapsed()' discards qualifiers
  [-fpermissive]

     if(buttons[key].state==1 && buttons[key].clickDelay.lapsed()<=clicksDelay){

                                                                ^

  C:\Users...\Humidity\Humidity.ino:78:40: warning: passing 'volatile Timer' as
  'this' argument of 'void Timer::mark()' discards qualifiers
  [-fpermissive]

       buttons[key].clickDelay.mark();

                                    ^

  C:\Users....\Humidity\Humidity.ino:
  In member function 'byte KeyboardBtn::stateChanged(byte)':

  C:\Users....\Humidity\Humidity.ino:83:58: warning: passing 'volatile Timer' as
  'this' argument of 'uint32_t Timer::lapsed()' discards qualifiers
  [-fpermissive]

   if(temp_state==1 && buttons[key].clickDelay.lapsed()<clicksDelay){

                                                      ^

What is the problem?
Note:It does allow me to upload the code but I am almost certain it will generate some errors while running...

If you want to use an instantiated object as volatile then the functions within it also have to be marked as volatile. That tells the compiler that the instance pointer you will be passing to the function (the auto-inserted this parameter) is volatile:

class Timer{
  private:
    uint32_t start_time;
  public:
    Timer(){
      start_time=millis();
    }
    void mark() volatile {
      start_time=millis();
    }
    uint32_t lapsed() volatile {
      return millis()-start_time;
    }
};


Arduino IDE lost board connection Board: Arduino Leonardo

IDE version: 1.6.5(also tried with 1.8.3)

Try Arduino Web Editor as well

The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.

Everything was OK, but after one deploy happened thing, that I described.

If it help: I connect OLED display and use it with OLED_I2C library. Sketch contains one cpp and one h file.

I'm already fully reinstall USB drivers with Arduino USB as well

The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.

Yes, that's normal. That's the bootloader running, and it's during that 5-7 second window that you can upload a new sketch.

Under normal circumstances the IDE will automatically reboot the board for you so the upload time window coincides with the IDE's attempt to upload a new sketch. However under some circumstances it can't, so you have to do it manually by pressing the reset button at the right time.

Also on Windows you may find that you have a different COM port for programming as you do when a sketch is running (Windows is retarded like that, you see). The IDE tries to do some magic to identify the correct COM port to use, but you have to first have the correct "sketch mode" COM port selected so it can first reboot the board into the bootloader, at which point it tries to do its magic to work out the correct COM port to use by looking to see which COM port (if any) has just appeared since rebooting.

So, in short: if the IDE can't reboot the board for you then do it manually, but note that timing is vital. Press the reset button a few moments before avrdude runs. It may take practice.


This specific code just refuses to compile? I've been working on some software to do REALLY basic composition of music.
Here's my code so far:

#include "notes_sharps.h"

int notes[] = {NOTE_B0,NOTE_C1,NOTE_D1,NOTE_E1,NOTE_F1,NOTE_G1,NOTE_A1,NOTE_B1,NOTE_C2,NOTE_D2,NOTE_E2,NOTE_F2,NOTE_G2,NOTE_A2,NOTE_B2,NOTE_C3,NOTE_D3,NOTE_E3,NOTE_F3,NOTE_G3,NOTE_A3,NOTE_B3,NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5,NOTE_D5,NOTE_E5,NOTE_F5,NOTE_G5,NOTE_A5,NOTE_B5,NOTE_C6,NOTE_D6,NOTE_E6,NOTE_F6,NOTE_G6,NOTE_A6,NOTE_B6,NOTE_C7,NOTE_D7,NOTE_E7,NOTE_F7,NOTE_G7,NOTE_A7,NOTE_B7,NOTE_C8,NOTE_D8};

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

  for(int i = 0; i < 51; i++){
    Serial.println("%i's sharp is %i",notes[i], notes[i]+(notes[i]*0.05937));
  }
}

void loop(){}

This code just refuses to compile, no error messages, it simply leaves my computer dormant.
Here's the log:

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10604 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp -o C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp.o

As Majenko stated in the comments, your use of the println function is not valid as there exists no overload that takes char*, int, int as parameters.

You could get your program to work by replacing your println as following:

for(int i = 0; i < 51; i++){
    Serial.print(notes[i]);
    Serial.print("'s sharp is ");
    Serial.println(notes[i]+(notes[i]*0.05937));
}


Digital input pin voltage treshold (voltage to register 1 or 0) I was thinking of using multiple analog light sensors (variable resistance by light), but basically I only need to know if there is "a lot of light" or "not a lot of light". And would like to use interrupts.

Since I'm using multiple analog inputs, I can't set the ADC module to interrupt on a specific voltage, for each of the (5?) sensors?
I'd like to do this withouth using a external comparator.

I've checked the ATMega328p datasheet (going to use Arduino Nano probably).

The fun thing, however, is that on 5V a high signal is >2.6V and a low signal is <2.2V

What does this mean for the grey area? Would my inputs be glitching randomly? Would they maintain high, until below 2.2V and maintain low until above 2.6V? Or can the switching point be any where between that (and is it different per chip or pin?

EDIT: I've checked, my voltage divider circuit has 0.6V for "nothing" and 3V for "interrupted", so it should work neverthless. Though, I'm still interested in how the grey threshold area behaves.

The titles of the graphs are actually saying what happens: the hysteresis.

In other words:

if the input level is high (greater than 2.6V), it will be considered high through the hysteresis area (until it goes below 2.2V)
if the input level is low (below 2.2V), it will be considered low through the hysteresis area (until it goes above 2.6V)

According to the description you gave, this should work for your case.
In case it doesn't, you have to condition it until the values you want to consider 0 and 1 are respectively below 2.2V and above 2.6V, with a safety margin, for good measure (say 30%).

The hysteresis is meant to prevent noise from causing unwanted spurious transitions: without safety margin, it should be greater than 0.4V.

You can dimension the safety margin to meet your needs.

But, for the sake of completeness, I'll say that it might be preferable to have a timer to trigger periodic sampling with the ADC.

If you know the maximum frequency at which every input can vary, you can sample it at twice that frequency and be sure that you will not miss anything. Again, this is theory, I would probably make it 4 times, to allow for unforeseen variations.

This works as long as the conversion time of the ADC is shorter than the maximum combined frequency at which you need to read the values.

The GPIOs, of course, are faster, but might require additional circuitry for the conditioning I mentioned earlier.


How can I increase the responsiveness/speed of my stepper motor? I'm trying to control the positioning of a NEMA17 bipolar stepper motor by turning the knob of a potentiometer, using an EasyDriver board.  The control part is solved.  My problem is that if I quickly turn the knob to one end of its range and then back, the stepper motor lags behind by about 1/5 of a second.

All the spec sheets for the motor says I should be able to expect a lot more responsiveness (based on max RPM, acceleration, etc...). I'd like to speed up the responsiveness of the motor to shorten the lag. My code is as follows:

//Declare pin functions on Arduino
#define stp 2
#define dir 3  //LOW => forward, HIGH => backward
#define MS1 4
#define MS2 5
#define EN  6

//Declare variables for functions
int x;
int const potPin = A0;
long potval; // current analog read of A0 voltage
int potrotsteps = 166; //num of stepper motor steps for 300-degree rotation
int cur_step_pos = 0; //current position in terms of stepper steps
long cmd_step_pos = 0; //step-position to command stepper motor to go to
int tomove; //num steps to move

void setup() {
  //stepper motor setup
  pinMode(stp, OUTPUT);
  pinMode(dir, OUTPUT);
  pinMode(MS1, OUTPUT);
  pinMode(MS2, OUTPUT);
  pinMode(EN, OUTPUT);
  resetEDPins(); //Set step, direction, microstep and enable pins to default states
  Serial.begin(9600); // initialize serial communication at 9600 bits per second
  Serial.println("\n\n\n#################    setup completed     #################");
}

void loop() {

  //map analog voltage read from pot to a step-position (0-166) of the stepper motor
  potval = analogRead(potPin);
  cmd_step_pos = potval * potrotsteps / 1023; // find where stepper motor should be in terms of step-position
  tomove = abs(cur_step_pos - cmd_step_pos);

  if (cmd_step_pos > cur_step_pos) { //if should-be position greater than current position
    digitalWrite(dir, LOW); // move forward
    CommandStepperMotor(tomove); //move forward by the diff in position
  } else { //if should-be position is lower
    digitalWrite(dir, HIGH); //move backward
    CommandStepperMotor(tomove); //move backward by diff in position
  }
  cur_step_pos = cmd_step_pos; //current position is now former should-be position

}

//GLOBAL FUNCTIONS

//Reset Easy Driver pins to default states
void resetEDPins() {
  digitalWrite(stp, LOW);
  digitalWrite(dir, LOW);  //default "forward" movement
  digitalWrite(MS1, LOW); // L-L => full steps, H-L => 1/2 step
  digitalWrite(MS2, LOW); // L-H => 1/4 steps, H-H => 1/8 step
  digitalWrite(EN, LOW); //Enable motor control
}

void CommandStepperMotor(int numsteps) {
  for (x = 0; x < numsteps; x++) {
    digitalWrite(stp, HIGH); //Trigger one step forward
    delay(1);
    digitalWrite(stp, LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
}

I understand that changing delay(1) to delayMicroseconds(100) in the CommandStepperMotor function should help, but as it turns out, anything smaller than a delay of 1 millisecond stalls the motor.  I've tried to Google other's solutions to the problem, but it seems they had no problem at all lowering the delay in sending the HIGH/LOW signals to the stepper pin to <1 ms.

Any ideas?  Thanks in advance!

Your problem is that you want to go from a standstill to full speed instantly. That just isn't going to happen. As you have seen there is a limit to how fast you can go from stationary.

If you want to go faster you will have to accelerate up to that speed.

The simplest way to do that is to use a library that is designed for it, such as the popular AccelStepper.h library.


Arduino hangs after less than a minute, but not on USB I have arduino uno + ethernet shield + 9V/200mA adapter. I am trying to send some data with HTTP connection. When it's connected to USB it works perfectly, but when I plugged out USB, hangs (after less than a minute, it stops pinging).
I have tried this:
EthernetClient.cpp

int EthernetClient::connect(IPAddress ip, uint16_t port) {
  if (_sock != MAX_SOCK_NUM)
    return 0; // i changed to -1  as suggested on previous link

  for (int i = 0; i < MAX_SOCK_NUM; i++) {
    uint8_t s = socketStatus(i);
    if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
      _sock = i;
      break;
    }
  }

and also example from library Examples-library-WebClientRepeating, but I get the same problem as in my code.
Is my adapter too weak?
This code is from Example WebClientRepeating:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED    };

// fill in your Domain Name Server address here:
IPAddress ip(193, 77, 60, 66);
IPAddress subnet(255, 255, 255, 0);
IPAddress gateway(193, 77, 60, 7);
IPAddress myDns(193, 77, 60, 213);

EthernetClient client;

char server[] = "www.arduino.cc";
//IPAddress server(64,131,82,241);

unsigned long lastConnectionTime = 0; // last time you connected to the server, in millisecond
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

void setup() {
  // start serial port:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns, gateway, subnet);

  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if ten seconds have passed since your last connection, then connect again and send data:
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.println("GET /latest.txt HTTP/1.1");
    client.println("Host: www.arduino.cc");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

EDIT 1:
Also when I plug USB in its start working with 9V power adapter.

The problem is that when you are using the external 9V power supply, you are relying on the Arduino's on-board regulator to provide the 5V power supply to both the Arduino and the Ethernet shield. This regulator has very limited current capacity — much less than the 500 mA that's available from a PC's USB port — and you're overloading it.

To avoid this problem, you should use a 5V plug pack with a USB connector to power your system.


Combining two different coding program into one sketch Im working on project that uses a relay module,arduino atmega328 and a 2 motor 12vdc. based on coding i give, the first code is the motor 1 will run based on the input switch. and the second code the motor will run based on the delay time. what im doing is, im going to combine these two coding into one sketch hoping these two coding will run together. but im confused on how to combine.

`int motorPin = 10; // pin that turns on the motor
int blinkPin = 9; // pin that turns on the LED
int watertime = 5; // how long to water in seconds
int waittime = 60; // how long to wait between watering, in minutes

void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // set pin 13 to an output so we can use it to turn on the LED
}

void loop()
{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  delay(watertime*3000);        // multiply by 1000 to translate seconds to milliseconds

  digitalWrite(motorPin, LOW);  // turn off the motor
  digitalWrite(blinkPin, LOW);  // turn off the LED
  delay(waittime*6000);        // multiply by 60000 to translate minutes to milliseconds
}`

this is the coding to run the motor by using delay time

const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == LOW) {
    // turn LED on:
    digitalWrite(ledPin, LOW);
  } else {
    // turn LED off:
    digitalWrite(ledPin, HIGH);
  }
}

this is the code which the motor will run based on the switch

for now, i dont have idea on how to combine these two coding.

the idea of my project is when switch is LOW(pin 3)  the Motor 1(pin 13) will HIGH until the switch is HIGH, the motor 1 will be LOW and stop.  At the same time,  there will be time delay for 10 second and the Motor 2 (pin 10)will active soon after switch is LOW and delaying time for 10 seconds and the Motor 2 will be active with time for 25 second  and stop and the next active for another 60 minutes

The simplest way of combining two programs is this:

Copy the content of the two programs into a single new .ino (program) file
Rename the first setup function setup_one
Rename the first loop function loop_one
Rename the other setup and loop functions setup_two and loop_two
Add the following code to the bottom of that file.

Code:

void setup()
{
  setup_one();
  setupr_two();
}
void loop ()
{
  loop_one();
  loop_two();
}

This is a very simplistic approach and it won't work for all cases.  It will work in this case, but you will find it will do program one then program two.  It will work because your constants don't clash (at the top of the program) you aren't using the same pin in the different programs, etc.

You need to learn what the code does though to really merge the programs, you will see better ways of doing it.  The best way to learn is to right down, in your native language, what each line of code does, so in the case of program one:

turn on the motor
turn on the LED
wait for 'watertime' seconds
turn off the motor
turn off the LED
wait for 'waittime' minutes

For program 2:

  read the state of the pushbutton value:
  If the button is in state low
    Turn off the LED -- Not sure  this might be on
  else
    Turn on the LED -- Not sure this might be off

Hopefully you should recognise those descriptions (they are the comments) and when you read through the descriptions you will realise why the code you put together using the above method "doesn't work".  It does, you just need to wait for 'waittime' minutes before you get a few microseconds to press the button.

If you want the motor to respond to the button then rearrange the natural language description to do what you want and then replace the English with the code and you should have a program that is close to working.  (Hopefully)


Flexibility of SoftPot Membrane Potentiometer during the use? Does anybody have some information or experiences with the flexibility of Spectra Symbol's SoftPot Membrane Potentiometer during the use? Is it possible to partly wind it up on a reel (or something similar) and use the remaining part dynamically without loosing precision and control? Are there "ghost touches" caused by the force/pressure of bending/winding the sensor strip? Or should the sensor always be used in a flattened position?

Thanks for any helpful comments.

As you can see from this data sheet it will show you examples on how it is used. https://www.sparkfun.com/datasheets/Sensors/Flex/SoftPot-Datasheet.pdf

I'd buy a curved one just to make sure, because as it bends, the 2 conductive materials will touch.


How to read data using Arduino SPI in the datasheet, it's stated that I should apply 32 serial clocks to get the 32 bits of data. How can I program this is Arduino?

You call SPI.transfer() four times, each time saving the returned value to a variable after proper bit shifting.

uint32_t val;
val = SPI.transfer(0xff);  //0xff is a dummy
val |= (uint32_t)SPI.transfer(0xff) << 8;
val |= (uint32_t)SPI.transfer(0xff) << 16;
val |= (uint32_t)SPI.transfer(0xff) << 24;

I assume the least significant byte is received first. Make sure the SPI mode is the right one, as indicated in your datasheet.

If the slave can't handle being deasserted between bytes (which is what SPI.transfer() will do at the end of the transaction), then you can either try st2000's hardware SPI approach or use bitbanged SPI with shiftIn().


Program around this while loop not working as expected int i=0;
while(i == 0){
  if(digitalRead(saveSwitch) == HIGH){
    Serial.print("New coordinates saved \n");
    lat1 = gps.location.lat();
    Serial.print("Latitude");
    Serial.println(lat1);

    lng1 = gps.location.lng();
    Serial.print("Longitude");
    Serial.println(lng1);
    i = 1;
  }
}

Why isn't leaving the while loop?

Instead of setting i=1, you could use a 'break' command to break out of the while loop.  That way you don't need 'i' at all, you can just do 'while(true)'


can teensy 3.0 or above run fingerprint scanner fps gt-511c1r? I have an fps gt-511c1r fingerprint sensor module. I want to know whether i can run it using teensy 3.0 or above?
I have tried it successfully using arduino uno.

EDIT: I have uploaded the fps blink sketch on the teensy 3.2 successfully, but the fingerprint scanner is not responding. Here is the code:-
         #include "FPS_GT511C3.h"
         #include "SoftwareSerial.h"

     // Hardware setup - FPS connected to:
     //   digital pin 0(arduino rx, fps tx)
     //   digital pin 1(arduino tx, fps rx)

     FPS_GT511C3 fps(0, 1);

     void setup()
     {
         Serial.begin(9600);
         fps.UseSerialDebug = true;
         fps.Open();
     }

     void loop()
     {
        // FPS Blink LED Test
        fps.SetLED(true);
         delay(1000);
         fps.SetLED(false);
         delay(1000);
     }

connected fps tx to teensy rx(pin 0),
          fps rx to teensy tx(pin 1),
          fps vcc to 3.3v teensy,
          fps gnd to teensy gnd.

The GT-511C1R is a 5V device. The Teensy 3.0 is a 3.3V device. You will require some level shifting as you would with any 3.3V Arduino connecting to a 5V device.

Besides that, yes, the Teensy 3.0 is more than capable of working with the fingerprint scanner. Will the software work? Most likely, but only trying it will confirm that.


Name of the Arduino Nano clone in the device manager I'm working on an app using Matlab and it recieves data from an arduino. I've changed my board into an Arduino Nano (clone) recently. My program will automatically check for the device's name in the list of serial devices connected and it will connect to it directly once the user presses connect. The user doesn't have to input any Com port number or baud rate. This worked fine with my previous boards (UNO, Pro Micro, Leonardo). I just need to change the search string in my code and it'll automatically connect. My current board however is different, I'm using VMA102 (Arduino Nano clone). It uses FTDI drivers which I downloaded following this tutorial. I can upload the codes correctly to it but I just doesn't show a name with in the ports list in Arduino IDE as shown in the picture below.

Now when I looked it up in the device manager the name was 'USB Serial Port (COM5)' so I pasted 'USB Serial Port' as my search text in Matlab, it doesn't find it. I concluded that the correct name for it is not 'USB Serial Port' but rather the 'no name' as shown in Arduino IDE. Is there a way to find what is it called or how I can change it into a unique name so that my app can search for it?

Edit: here is the code, it works fine with all the other boards:
    devices = IDSerialComs();%gets all the avilabe com ports and thier names (name, com#)
    assignin('base','devices',devices);%save it to main workspace

i=1;index=0; tesst= zeros(length(devices),1);%saves the comparison results
while i<=length(devices)
    tesst(i)= strcmp(devices{i,1},'USB Serial Port');%compare the received names with the board's name
    % 'SparkFun Pro Micro''Arduino Uno'
    if ( tesst(i)==1 )
        index=i;%save the index
    end
    i=i+1;
end

if(isempty(find(tesst,1)))
    msgbox({'Connection failed' ' plug the device, wait for 5 seconds then try again'} ,'Connection Failure','error');
else
    msgbox('Connection successful, proceed to the next tabs', 'Connection success');
end
%get the COM# associated with the index and add COM before it to from the comport number as a string
COM_Num = strcat('COM',num2str(devices{index,2}));
comport= serial(COM_Num, 'BaudRate', 115200);

and here is a screenshot of my device manager

Thanks

If you do a windows search for the device manager you will be able to see all the com devices currently connected to your computer. Unplug and replug your Arduino and it should be pretty easy to spot.

Mine is the USB-SERIAL CH340


I'm getting NaN for readings on my DHT22 sensor when using 3v3 pin, but not 5v pin I have a DHT22 temperature sensor and DS1302 RTC module connected to the 3v3 pins on an Arduino Nano. Both the sensor and the RTC module are rated to work on either 3.3V or 5V, but the recommendation is 3.3V.  For some reason though, when I connect the sensor and RTC to 3.3V power on the Nano, the sensor just returns NaN even though the RTC module works.  When I change the sensor to use 5V and leave the RTC on 3.3V, I get a proper temp and humidity value on the DHT22.  What is wrong?

Turns out the solder joint for the 3v3 pin on the nano was not properly done. I figured this out after I swapped out the nano for another nano and it worked. Resoldering the 3v3 pin fixed the problem.

Sometimes the problem is simply that you didn't properly solder the headers onto the Arduino. You should check to make sure that your solder joints are all good.


Use RFID-RC522 with other Pins I'm wondering where the pin setting is manifested in the library.
I want to use the RC522 with other digital pins than the default 50-53 pins, because I am using a shield for a display on theese ports.

Where can I change the used ports?
why are two ports user-defineable #define RFID_SS  10 #define RFID_RST 5 while the rest is not?

I am with this Playground-Guide using this library from Github on my Arduino Mega

SPI
The RFID_SS pin is the slave select pin.
So you can have another arduino pin for a LCD_SS select.
Having RfID_SS =low - talk to RFID.
Having LCD_SS =low talk to LCD via MISO.
Note: Drive other slave select High otherwise they'll both get the data.
Having only one device in communication at a time.
Cheers
Nik V


Plotting data from Arduino and using the serial monitor in parallel I'm very new to the Arduino world so bare with me.
I would like to plot live data that I receive from my arduino. I use the Serial Monitor to read user input, show text, etc.
The only way I found to plot data from the arduino is by printing the data out in the serial monitor
I would rather prefer the data not to be shown in the serial monitor at all (just from a visual standpoint) but I guess there is no way around it.
Anyways, I would like to read and plot the data only when the user makes a specific input into the Serial Monitor.
Let's say the user types in: "start"
now the arduino prints out the values that needs to be plotted.
But every plotting tutorial on plotting with the arduino that I could find always prints out the data right from the start. I want to start the plotting with the specific user input.
I hope I could explain my question well enough.
Thank you in advance for your help.
Luca

Is using the Serial Monitor a requirement, or are you just looking for a good way to get and plot the data?  If the latter, you may be interested in the open-source DaqPort sketch. https://www.daqarta.com/dw_rraa.htm  This was created to use the Arduino as a peripheral for data acquisition, as opposed to the more typical case of the Arduino being the central device.  With DaqPort you can program in any language you like on the host computer, and use it to plot data from the Arduino. The Daqarta software package that includes DaqPort has several examples that use Daqarta's macro language to implement a multi-channel chart recorder, high-speed multi-function oscilloscope, timers, signal generator, etc.  You can use these for free, forever, even after Daqarta's 30-day trial ends.  Since Daqarta already has plotting, you may find it simpler to use than rolling your own, perhaps by modifying one of the examples.


'content' is not captured I try to make a variable that can be modified from the server, using and ESP8266.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "********";
const char* password = "*********";

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
    digitalWrite(led, 1);
    server.send(200, "text/plain", "hello from esp8266!");
    digitalWrite(led, 0);
}

void handleNotFound() {
    digitalWrite(led, 1);
    String message = "File Not Found\n\n";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET)?"GET":"POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";

    for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }

    server.send(404, "text/plain", message);
        digitalWrite(led, 0);
    }
}

void setup(void) {
    pinMode(led, OUTPUT);
    digitalWrite(led, 0);
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    if (MDNS.begin("esp8266")) {
        Serial.println("MDNS responder started");
    }

    String content = "Basic";
    content += "<form action='action_page.php' method='POST'>
";
    content += "User:<input type='text' name='USERNAME' placeholder='user name'>
";
    content += "<input type='submit' name='SUBMIT' value='Submit'></form>
";

    server.on("/led", [](){
        server.send(200, "text/html", content);
        Serial.println(USERNAME);
    }

    server.on("/", handleRoot);

    server.on("/inline", [](){
        server.send(200, "text/plain", "this works as well");
    });

    server.onNotFound(handleNotFound);
    server.begin();
    Serial.println("HTTP server started");
}

void loop(void){
    server.handleClient();
}

When I compile it, it says

  'content' is not captured

I thought it may be from the input, and I tried to name it "Basic" for the start, but it still failed.

Let's look at a simpler example:

void setup ()
{
  String content = "Basic";

  attachInterrupt (digitalPinToInterrupt (2),
                   []()
  {
    Serial.println(content);
  },

  FALLING );

}  // end of setup

void loop () { }

This gives the error:

/tmp/arduino_modified_sketch_182173/sketch_jan25a.ino: In lambda function:
sketch_jan25a:8: error: 'content' is not captured
     Serial.println(content);

Why? Because you are using a local variable content in a lambda function which runs at global scope. That is, content is not available to it, because it is inside setup.

To capture it, you can put it in the capture list:

  attachInterrupt (digitalPinToInterrupt (2),
                   [content]()  // capture content

However I found that my example doesn't compile even then.

I think the reason for that can be found here: Lambda Functions in C++11 - the Definitive Guide

  How are Lambda Closures Implemented?

  So how does the magic of variable capture really work? It turns out that the way lambdas are implemented is by creating a small class; this class overloads the operator(), so that it acts just like a function. A lambda function is an instance of this class; when the class is constructed, any variables in the surrounding enviroment are passed into the constructor of the lambda function class and saved as member variables.

You can't pass an instance of a class to attachInterrupt because there is a hidden *this variable that needs to be passed to class instances, and ISRs don't do that.

Now your example isn't an ISR, but probably the same remarks apply.

I don't think there is an enormous amount of point of using lambda functions here. If you must, move content inside the lambda, since that is where you are using it.

Or failing that, make it global scope.

The closest I could get to something that compiled was:

void setup ()
{
  const int content = 42;

  attachInterrupt (digitalPinToInterrupt (2),
                   [=]()
  {
    Serial.println(content);
  },

  FALLING );

}  // end of setup

void loop () { }

Honestly though, I think using lambda functions here just makes your code obscure.


Syntax of binary Constants I was trying to compile some Arduino code on the PC for testing when I noticed some strange syntax for numerical binary constants.

Convetion seems to be to declare them like so:

    static const uint8_t smiley[] = {
        B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10100101,
        B10011001,
        B01000010,
        B00111100 };

However, when I try to compile this with g++ I get

  error: ‘B00111100’ was not declared in this scope

Now when I exchange this for B for the standard C/C++ prefix 0B it works, but I don't want to change the code that I want so simulate!

Is there some clever macro magic at play here?

There is a file (binary.h) with every possible permutation of number between 0 and 255 represented as binary in it. They're stored as C-preprocessor macros:

#define B0 0
#define B00 0
#define B000 0
#define B0000 0
#define B00000 0
#define B000000 0
#define B0000000 0
#define B00000000 0
#define B1 1
#define B01 1
#define B001 1
#define B0001 1
#define B00001 1
#define B000001 1
#define B0000001 1
#define B00000001 1
#define B10 2
#define B010 2
#define B0010 2
#define B00010 2
#define B000010 2
#define B0000010 2
#define B00000010 2
... etc ...

Quite why Arduino decided to do this is anyone's guess.  It makes, as you have seen, for non-portable code.

Personally, I never use (and would never recommend any one else should use) those macros, and instead use the GCC standard binary literal representation 0b.....


How to have an Arduino communicate with 3 other Arduinos? I was wondering how I can get 4 Arduinos in total to communicate with each-other through a wired connection. The goal is to have the master Arduino send a number 0-100 to each of the other Arduinos.

The master unit will be an Arduino Uno and the other 3 Arduinos will be Arduino Pro Minis.

You could use: U(S)ART, I²C or SPI. You should check this post for information on these protocols.

Some quick googling gave me this:

SPI: mainly for high data rates, approx 25 MHz clock but only bus has to be on same voltage level, single master (can be done through software), data arbitration not possible.
I2C: mainly for control and low data transfer (limited by bus capacity, etc...), but can be interfaced to different voltage levels and multimaster bus environment, inbuilt arbitration etc...
UART: single P2P comm, 115 kbps max.

http://www.edaboard.com/thread53139.html

I don't fully agree with it. You can send via UART to multiple devices, but then you have to handle the addressing in software. But other than that, UART is very easy to debug as Arduinos often have an USB connection.

"I²C is somewhat complicated at the physical level, but all that complication is handled by the hardware (the TWI interface of the AVR chips). At the user level, it may be the simplest to use". I don't yet have a lot of experience with this protocol, but if you want to use it, check out the other answer.

SPI would be a fair shot as it does enable master with multiple slaves in its standard.

Summary:

All protocols have different pros and cons. It's not really up to us to choose one for you. And you should look them up and learn about them by yourself.

Then try to choose which one applies most to your needs, and get started with that protocol. They are well documented and if you really can't get out of it, you can post another question ;D


Arduino UNO R3 as flight control plus brushless motor driver I am trying to build an RC plane using an arduino UNO as the flight control board.

I found a code on the arduino forum for driving a 3 phase AC motor with an arduino.
http://forum.arduino.cc/index.php?topic=8642.0

I believe it will also work for brushless motors commonly used in RC airplanes.This will eliminate the need for an ESC (Electronic Speed Controller) which are pretty expensive.

Now I plan to use a single arduino board to communicate with the nrf2l01 rf receiver , control the servos as well as drive the brushless motor(mentioned above).

In each cycle of the code the arduino will be fetching data from the receiver,sending a pwm signal to the servos and setting which two phases of the brushless motor will be high and which one will be low.
Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino  fast enough to handle all this and it won't affect the speed noticeably.

Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino fast enough to handle all this and it won't affect the speed noticeably.

This is very much an engineering question. How would one go about answering this?

One method is do a worst-case execution time measurement. Another method is to use control theory and estimate the minimum control frequency for the system (or sub-systems).

Let us assume (for this argument) that the required update frequency is 50 Hz (20 ms cycle time). That gives approx. 320.000 instructions (AVR @ 16 Hz) per control cycle.

The algorithm sketch above in your question is basically dominated by the time to receive the message. This depends on a number of factors; PLL start up, write message from AVR to NRF, transmission frequency, coding, etc, but also message loss and retransmission/acknowledgement. With 2Mbps and 5 byte address, 32 byte payload, and 2 byte checksum the transmission time is at least 300-400 us plus approx 100-200 us for the AVR/SPI to NRF communication. A total of 400-600 us which is well under the 20 ms.

What other design considerations are there? Motor interference on the communication, antenna design, range, protocol design, etc.

Cheers!


Controlling voltage and current from chip? I'm well aware that this question perfectly showcases my spectacular ignorance, but oh well. It's a simple enough question, so here we go.
I have a 595 chip (SN74HC595) wired up to an Arduino, fed by the 5V output. After switching all the outputs on, I measured an output pin at 5.04V and 74mA.
I want to use the chip's outputs to switch transistors (P2N2222A) which will have 60 mA through them (switching common cathode RGB LEDs), so I believe I need to drop it down to around .6 to 1.2V at .6mA, right (I'm not at all sure I'm reading the datasheet right)?
So how exactly do I do that? It seems like I need to put a resistor in between the pin and the base, but don't I need to know the TOTAL resistance of the circuit? Or can I just calculate from the pin itself (I believe that would need 7K)?
Thanks in advance for your help, and please feel free to OVER-explain if you're so inclined.
EDIT:
EDIT 2: Resistor values are listed wrong. R1=200, R2 & R3 = 100.

You're misunderstanding what you need to drive a transistor.

A transistor will allow up to a specific amount of current through the collector depending on the current that flows through the base. If less is needed by the load then less will flow.

Think of it like a tap. If there's not much water pressure it doesn't matter how far you turn on the tap, after a certain point the flow of water won't increase any more.

To allow 60mA through the collector you need to provide at least 0.6mA (assuming a hFE of 100) through the base. That 0.6mA will set the upper limit of the current to 60mA. If you provide more than 0.6mA then you will allow a higher upper limit.

The 0.6V on the base is the voltage (difference between base and emitter when wired as "common emitter") at which current will start flowing through the base. It's the same concept as the forward voltage of an LED. For switching the voltage you put on the base must be more than 0.6V to allow current to start flowing. Since 5V is more than 0.6V you don't need to worry about it.  If you want precision in your calculations you will want to take that 0.6V into account, though.

So if you want at least 0.6mA from 5V with a 0.6V drop on the BE junction, you need:

R=V/I = (5 - 0.6) / 0.0006 = 7.3kΩ.

That's the maximum resistance you want. Anything more than that and the current through the base will limit the current through the collector to below the 60mA you want.  So you must select some resistance that is lower than that.

What value? Well, it really doesn't matter that much. The lower the value the higher the current, but at these levels the current levels you're dealing with will be minuscule anyway.

It's common to use a 1kΩ resistor in the base for a transistor when using it as a simple switch like you are.  That would give you, for each transistor:

I=V/R = (5 - 0.6) / 1000 = 4.4mA

For all 8 outputs that's a paltry 35.2mA. Far below the total the chip can provide of 70mA.

If you care about current consumption (you're running from batteries, for instance) you may want to increase to 4.7kΩ resistors to reduce the total drive current down to 7.5mA.


PROGMEM char* mangled text I wrote a program using PROGMEM for massive string arrays. One of the arrays worked, but when I added the second one, the serial output only puts out "th".

Pastebin Code: http://pastebin.com/9U7QZQKn

Your declaration of char buffers is done like so:

char* move1 = "N/A";

This will only allocate 3 characters with an additional one for null termination i.e. not long enough to hold the name.

You need to do:

char buffer[16];

Where the length is long enough to hold your string.


TinyGPS (Plus) Library Is there a particular function in the library TinyGPS or TinyGPS Plus which outputs the raw NMEA sentences? I couldn't find anything about it on the website guide of the library.

There doesn't seem to be, but what you could do is print each character as it arrives. From their example code:

  while (nss.available())
  {
    if (gps.encode(nss.read()))    // <--- pass to TinyGPS
      return true;
  }

So, change that to be:

  while (nss.available())
  {
    char c = nss.read();  // <--- get the incoming character
    Serial.print (c);     // <--- print it
    if (gps.encode(c))    // <--- now pass it to TinyGPS
      return true;
  }


What happen to the counter value if I do not input the statement (if previous state!=current state) I refer to the code from this page: http://www.toddholoubek.com/classes/pcomp/?page_id=58 :
int ledPin = 13; // choose the pin for the LED
int switchPin =2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;

void setup() {
  pinMode(ledPin, OUTPUT); // declare LED as output
  pinMode(switchPin, INPUT); // declare pushbutton as input
  Serial.begin(9600);
}

void loop() {
  val = digitalRead(switchPin); // read input value
  if (val == HIGH) { // check if the input is HIGH (button released)
    digitalWrite(ledPin, HIGH); // turn LED on
    currentState = 1;
  }
  else {
    digitalWrite(ledPin, LOW); // turn LED off
    currentState = 0;
  }
  if(currentState != previousState) {
    if(currentState == 1) {
      counter = counter + 1;
      Serial.println(counter);
    }
  }
  previousState = currentState;
  delay(250);
}

I do not have the Arduino device so couldn't test the result currently but am Interested to know if I omitted this line:
if(currentState != previousState)

, using the command line
if(currentState == 1) {
counter = counter + 1;

only and lets say I using a FS-V21 fiber optic sensor to count the quantity of products of 1m long each and on a conveyer belt of speed 0.1m/s so the stat will be true of t=1/0.1=10second for each product.
Will the counter value increase one unit only for each product (happen on the transition edge only), or increase indefinitely in the 10 second duration?

No, it will increment as long as there is a product and at the frequency your loop runs at. So, when the light is interrupted, it will count several objects within a second.
The line you want to ommit is very essential, it makes the sketch only detect edges rather than levels.


Why use \" in arduino code? While working with JSON parsing I noticed that the char type data string is written like this:
char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

Why there are (escapes) " ---" used in the code? Why can't we use the string normally?

Why there are (escapes) " ---" used in the code? Why can't we use the string normally?

Because escapes are required.
In C " means 'The start or end of a string', but \" means 'A double-quote character'.
There has to be a way to distinguish a double-quote character from a string delimiter so the compiler knows which is which. Without escapes your string would look like:
char json[] = "{"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}";

and the compiler would find the end of the string at the second ", and then a load of junk before it finds the end-of-statement ; character. It can't work out what sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}" is supposed to be, since it isn't in the string, but after it.


Adding external power supply to any arduino connected component I have an Arduino Pro Mini 3.3v and the voltage is too small for my buzzer to ring loudly. I want to add a 9v battery to power the buzzer.

This is my current circuit:
Arduino (pin 9) => Buzzer +ve
Arduino Gnd => Buzzer -ve

I want to power the buzzer using an external 9v battery but I have no idea how to implement it in the circuit. All I know is that the ground should be common.

What next?

You can use an NPN transistor for this purpose.

All you have to do is connect it this way

Obviously use a buzzer instead of the motor and pin 9 instead of 4 :D

Arduino (pin 9)==>1k-10k Resistance==>Transistor base

Buzzer +ve ==> + 9V

Buzzer -ve ==> Transistor collector

Transistor Emitter ==> battery -ve ==> Arduino GND.

So now whenever you set the pin 9 to HIGH the transistor would allow current to pass through it from collector to emitter and your buzzer would work just as you wanted.


Outputs/inputs to Multiple Arduinos in Arduino IDE at once I apologize if this information could be easily accessed, but I'm new to Arduino and did multiple searches.  I'm currently able to write to one Arduino Trinket in Arduino IDE using digitalWrite. However, I'll have to be reading from two different Arduino Trinkets with analogRead.  An important part of this is that I must be able to access both devices at the same time.  I saw during research that other people were able to use two different Arduino IDE instances, but I don't think this will work for me.  I'll more than likely soon be purchasing 2 Arduino ItsyBitsy's or nano's for the serial USB communication.  Let me know if this would make the issue easier.  I appreciate any help!

Arduino IDE is editor and builder. Your sketch runs on microcontroller and the microcotroller doesn't need the IDE to run it. The Serial prints from microcontroller go to com port from which any Terminal app can show them, not only the Serial Monitor build-in in IDE.

Connect both arduinos of same type to computer. They will have different ports. Upload your sketch to the first one, then change the port setting in IDE and upload to second arduino.

Serial Monitor can show you the output of arduino connected to the selected port. Switch port in Tools menu and reopen Serial Monitor to see the output of the second arduino.

To display booth at once, there are some options with different difficulty level:

use two instances of a terminal program like PuTTY Terminal Emulator to show the output
connect the TX pins of arduinos together
send data from one arduino to the second and let the second process them


IR sensor readings at different voltages I am currently working on a photo-transistor like this:
http://www.ebay.com/itm/10pcs-ITR8307-S18-TR8-Optical-Switches-Reflective-Phototransistor-Output-/381374566327?hash=item58cbb20fb7:g:lgoAAOSwr81UQ7KG

It very nicely allows me to identify colors white, green and black. The problem I am having is that the Arduino is powered with batteries so the readings for those colors change as voltage in the batteries reduces.

I tried to make the reading proportional to the voltage in the system, but this still gives different values, I guess the readings change non-linearly as voltage changes.

I wonder what will be the solution to this problem: Specifically, how to make the reading of an IR sensor the same for the same color at different voltages?

This is the code I am using so far:

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

void loop() {
// read the input from the IR sensor on pin A0:
float sensorValue = analogRead(A0);
// read the voltage in the system by connecting pin A1 to Vcc, with the same resistor value used in the IR sensor:
float Vref = analogRead(A1);

// adjust reading value to voltage in system:
float AdjustedReading = sensorValue/Vref;

Serial.println(AdjustedReading);
delay(100);
}

It sounds to me like your system works, but you have trouble if your voltage drops.

First of all here's 2 tips that might solve your problem.

instead of just making 1 reading do 10 and take an average - this reduces noise.
the voltage reference is allready based on the voltage that powers the system so with your adjusted reading you try to accomplish something which has already happened an therefore has the opposite effect and actually increase the error.

see http://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/ for a very good explanation.

Add a RC filter to removes random fluctuations in the signal from you photoresistor

see https://electronics.stackexchange.com/questions/17754/where-to-place-a-capacitor-to-smoothen-ir-sensor-reading for a short description and the calculated example.

If however it is correct, and your readings of colors don't follow a linear scale, you would have to deduce that actual curve and apply it in the code - but that might not be easy.

So it would be much more easy to remove that variable by ensuring that the voltage is constant. Most Arduino boards have an 5V onboard voltage regulator that will keep the voltage exactly at 5 Volt when connected to battery via the power Jack!

(USB bypasses this regulator and have a little voltage drop so it is sligthly lower than 5V, and more very prone to fluctations if coming from a AC source affecting your analog read considerably)

The battery connected onboard voltage regulator however requires a higher input to do the regulation so the battery needs to supply atleast 6.2V or higher, in your case you would have to use a voltage source of less than 6.2V if this is the source of your problems.

(the voltage regulator on original arduino boards needs voltage of 1.2V higher than the needed output - clones might differ and require upto 2v more than the needed output)

hope this can help solve the issue

Mikael


Cannot send two arguments from a WebClient I am using the Arduino WifiWebClient to insert records into a RoR (Ruby on Rails) app. It works but it only inserts one field regardless of the number of arguments I send.

For example, if I test with Curl

curl -d "sale[itemId]=1234&sale[machineId]=4567"  http://myapp.herokuapp.com/sales

It will create a Sale record and populate both fields itemId and machineId. Everything OK.

But when I send the following instruction from the Arduino, it will only populate the first field:

(I am only including the POST method to simplifly the code, the rest of the code is similar to http://arduino.cc/en/Reference/WiFiClient)

void sendPOST() //client function to send/receive POST request data.
{
if (client.connect(URL,PORT)) {  //starts client connection, checks for connection
Serial.println("connected");

Serial.println("POST /sales HTTP/1.1"); //download text
Serial.println("From: Arduino1");
Serial.println("Host: evening-sierra-3769.herokuapp.com");
Serial.println("User-Agent: HTTPTool/1.1");
Serial.println("Connection: close");
Serial.println("Cache-Control : no-cache");
Serial.println("Pragma: no-cache");
Serial.println("Expires: -1");
Serial.println("Content-Type: application/x-www-form-urlencoded");
Serial.print("Content-Length: ");
Serial.println(31);
Serial.println();
Serial.println("sale[machineId]=\"09876543211234\"");
Serial.println("sale[itemId]=\"09876543211234\"");
Serial.println();

client.println("POST /sales HTTP/1.1"); //download text
client.println("From: Arduino1");
client.println("Host: evening-sierra-3769.herokuapp.com");  // Will be needed if apache is configured for VHOSTS
client.println("User-Agent: HTTPTool/1.1");
client.println("Connection: close");
client.println("Cache-Control : no-cache");
client.println("Pragma: no-cache");
client.println("Expires: -1");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(31);
client.println();
client.println("sale[machineId]=09876543211234\r\n");
client.println("sale[itemId]=09876543211234\r\n");
client.println();

Serial.println("ARDUINO: HTTP message sent");
delay(3000);
if(client.available())
{
  Serial.println("ARDUINO: HTTP message received");
  Serial.println("ARDUINO: printing received headers and script response...\n");

  while(client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
}
else
{
  Serial.println("ARDUINO: no response received / no response received in time");
}

client.stop();
}

Solved!

Changed the following lines:

client.println("Content-Type: multipart/form-data");
client.print("Content-Length: ");
client.println(63);
client.println();
client.println("sale[itemId]=123456789012341234&sale[machineId]=123456789012341234\r\n");
client.println();


How well will the Arduino Uno survive in a vacuum? Im doing some experiments with Pocketlab and Arduino, Vacuum will get to around -30inHg. I tried with my raspberry pi and it just kept dying everytime a vacuum was pulled. The only problem I can image is the arduino heating up.

Interesting question. You're right- heat is your enemy. Given the power dissipated by a Pi even when idle I'm not surprised it died. Most chips depend on convection to get rid of heat. A loaded Pi might require a (convective) heat sink and/or fan to keep it's core temperature down to an acceptable level, and that's at normal pressure and temperature. An Arduino -might- be able to work in a vacuum- it can lose some of it's heat through lead conduction- it'll only draw ~.25 watts normally vs 2.5 watts plus for a loaded Pi.

Ultimately it will depend on your application. If you have idle time when you can put the Arduino to sleep that will help keep it cool. If you have a conductive heat sink you can use then that would certainly help.


Global JsonObject (ArduinoJson) I know a global JsonObject shouldn't be used, but I have my reasons.

I have a JsonObject* functions and I want him to save the content of a file.
With

functions=new JsonObject(jsonBuffer.as<JsonObject>());

I can access the JsonObject, but not when I leave the method. Can someone help me to understand why?
(Don't give me a solution like: copy into a struct, I need a JsonObject ready to be read in all my code.

Full code:

JsonObject* functions;

void loadFunctions() {
  File file = SPIFFS.open("/functions.json", "r");
  if (!file) {
    Serial.println("Failed to open the file");
  }else{
    size_t size = file.size();
    if (size > 512) {
      Serial.println("File size is too large");
    }else{
      std::unique_ptr<char[]> buf(new char[size]);
      file.readBytes(buf.get(), size);
      DynamicJsonDocument jsonBuffer(256);
      DeserializationError error = deserializeJson(jsonBuffer, buf.get());
      if (error) {
        Serial.println("Failed to parse file ");
      } else {
        functions=new JsonObject(jsonBuffer.as<JsonObject>());
        Serial.println((*functions)["test"].as<String>()); //this doesn't work in another method
      }
    }
  }
}

jsonBuffer is local to the function. When you leave the function the contents of jsonBuffer are lost.

functions just points to the internals of jsonBuffer to get its data (to save memory).

You can either:

Make the jsonBuffer global so it sticks around all the time, or
Have a secondary DynamicJsonDocument or StaticJsonDocument that is global to which you copy your objects once read from jsonBuffer.


Generating an 8V PWM signal I have a control module that accepts 8V PWM signals.  My goal is to send a 500Hz PWM signal from an Arduino to an 8V PWM input on the control module.  Looks like everything generated from the Arduino is 5V.  Is there a way to generate an 8V PWM output or method of manipulating that signal to reach 8V?

I'd suggest you use a power-source that delivers you 8V. Your Arduino takes anything from 7-12V to power it and it regulates it down to 5V. But you still can access the 8V from the RAW pins. Use a MOSFET like D1703L to control the 8V with an 5V Arduino digital pin.

You just connect Drain (D) to GND and Source (S) to your RAW 8V (don't forget to put your device between the Source and RAW 8V). Your Arduino digital pin goes to Gate (G), but to not draw to much current from the pin you might want to use a resistor of roughly 1kΩ.

This is the safest way that also allows for much higher voltage and also current for up to a few amps.

EDIT

You should not connect the PWM pin to Ground on your Arduino. But you have to connect both grounds together. I'm not sure where your 8V comes from so I made a sketch where the 8V is an external source and powers your device along with the MOSFET.


Getting my keypad to reset when wrong password is entered I am working on a puzzle for my nephew. I currently have an arduino mega, SD card reader and keypad. Everything is wired correctly and I have it currently programmed so when you enter the right password than an audio file plays and a green LED lights up. Where I am struggling is I do not know how to program it so that when the wrong pass code is entered then my red LED light flashes and the code resets to position 0. I also noticed that my current password is 1,2,3 and when I add a random number between my pass code, say, 1,5,2,3 or even 1,3,2,2,3 then the audio file still plays and my green LED lights up. Any suggestions?

#include <Keypad.h>
#include <SD.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 53

TMRpcm tmrpcm;
char* password = "123";
int position = 0;
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[ROWS] = { 8, 7, 6, 9 };
byte colPins[COLS] = { 5, 4, 3, 2 };
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int R = 12;
int G = 13;

void setup(){
  pinMode(R, OUTPUT);
  pinMode(G, OUTPUT);

  LockedPosition(true);
  tmrpcm.speakerPin = 46;
  if (!SD.begin(SD_ChipSelectPin)) {
    return;
  }
}

void loop()
{
  char key = keypad.getKey();
  if (key == '*' || key == '#')
  {
    position = 0;
    LockedPosition(true);
  }
  if (key == password[position])
  {
    position ++;
  }
  if (position == 3)
  {
    LockedPosition(false);
  }
  delay(100);
}

void LockedPosition(int locked)
{
  if (locked)
  {
    digitalWrite(R, HIGH);
    digitalWrite(G, LOW);
    position=0;
  }
  else
  {
    digitalWrite(R, LOW);
    digitalWrite(G, HIGH);
    tmrpcm.setVolume(6);
    tmrpcm.play("matt.wav"); ;
    delay(10000);
    digitalWrite(G,LOW);
  }
}

You have the part checking if the key equals the position in the password and if so you increment the position.  But if it is not equal then you don't do anything.  You should probably have an else there that resets the position to 0 and tells the user they entered the wrong password.


Mirror text on 8 way 7219 While this was seemingly answered in another forum question, the answer given of using an alternative library of...  #define HARDWARE_TYPE MD_MAX72XX::FC16_HW  was tested and resulted in a worse situation of totally jumbled display with nothing meaningful displayed (no actual letters or numbers).  When using MD_MAX72xx.h library the text is displayed but is mirrored  e.g. letters are displayed backwards.
I'm using the latest downloads of MD_Parola and MD MAX72XX downloads yesterday.

I'm at a total loss as what to do to reverse the letters. Can anyone help please in simple terms, as I'm still very much a novice and on a steep learning curve with Arduino!

Thank you.

Sorry for the delay in replying.
I'm totally unsure where to add the line suggested in the MD_MAX72xx.h file?? (Said I was a novice!!).

The library file is just the basic MD_MAX72xx.h as downloaded. The other files being used are MD_Parola.h and SPI.h

This is a video of what is happening and what needs correcting .. [1]: https://youtu.be/LVuyTmeNFQ8 It will be removed from YT in a few days

I'm unable to paste the files details here as it exceeds the 30000  character limit

The MD_MAX72xx library has a transform function.

Depending on how you want to mirror the text (along which axis), you give that function the MD_MAX72XX::TFLR or MD_MAX72XX::TFUD argument.

Though I'm guessing that you might actually want to rotate the text 180deg. In that case use transform(MD_MAX72XX::TRC).


error: stray '\' in program with servo I'm doing a project for school using Arduino to make a catapult, but I have this error that I didn't have the previous week.

Can anyone see the program and search where is the error?

#include <Servo.h> //libreria necesaria para utilizar el Servo

Servo catac; //motor de giro continuo utilizado

int ledPin = 13; //led conectado a agujero 13
int button = 8; //boton conectado a agujero 8
int estado = 0; //varaible que permite saber el estado del boton

void setup()
{
    pinMode(ledPin,OUTPUT);
    pinMode(button,INPUT);
    catac.attach(12); // servo unido al agujero 12
    catac.write(180); //coloca al servo en 180 grados
}

void loop()
{
    estado = digitalRead(button); //la variable obtiene el estado del boton
    if(estado == LOW)
    {
        digitalWrite(ledPin,HIGH); //prende led
        catac.write(70); //servo levanta a 70 grados la catapulta
        delay(500);
        digitalWrite(ledPin,LOW); //apaga led
        catac.write(180); //servo coloca a la catapulta en posicion original
    }
}

Error:

cataoukta:6: error: stray '\' in program
cataoukta:8: error: stray '\' in program
cataoukta:9: error: stray '\' in program
cataoukta:10: error: stray '\' in program
cataoukta:13: error: stray '\' in program
cataoukta:14: error: stray '\' in program
cataoukta:15: error: stray '\' in program
cataoukta:16: error: stray '\' in program
cataoukta:20: error: stray '\' in program
cataoukta:22: error: stray '\' in program
cataoukta:23: error: stray '\' in program
cataoukta:24: error: stray '\' in program
cataoukta:25: error: stray '\' in program
cataoukta:26: error: stray '\' in program
cataoukta:9: error: expected constructor, destructor, or type conversion before 'void'
cataoukta:6: error: expected initializer before 'u037e'
cataoukta.ino: In function 'void loop()':
cataoukta:20: error: 'estado' was not declared in this scope
cataoukta:20: error: 'button' was not declared in this scope
cataoukta:20: error: expected `;' before 'u037e'

You have bad Unicode characters in your code. All your semicolons are something completely different and need replacing with real semicolons.


SD card failed to initialize I have a Pro Micro board and I try to make it list my files as in the example of the Arduino IDE.
The pins I use are the following:

board    micro sd module
   D4  ---> CS
   D15 ---> SCK
   D14 ---> MISO
   D16 ---> MOSI
   GND ---> GND
   VCC ---> VCC

On the serial monitor I get "initiallization failed".

What is wrong with my setup?

This is the code running:

#include <SPI.h>
#include <SD.h>

File root;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  root = SD.open("/");

  printDirectory(root, 0);

  Serial.println("done!");
}

void loop() {
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

And this is my wiring:

The SD library works only with FAT and FAT32 format. SD.begin() reads the 'disc volumes' and opens the root folder. If the card is not formatted or formatted with other file system standard, begin() fails.

EDIT: and the pin headers must be soldered


Use 5V pH sensor with 3.3V NodeMCU I'm trying to use a pH probe with NodeMCU, the problem is that NodeMCU is 3.3V and the pH analog sensor requires 5V, at first I thought using the VIN pin but didn't work, then I used the VU pin from NodeMCU V3 (by Lolin) but it didn't give me the right values, like if it missed more power. Is there any other way? Or any esp8266 board which supports 5V into it's analog input?

The simplest method is just a voltage divider - just as if you were interfacing a 5V logic signal output with a 3.3V input. However it may not work.

A voltage divider will only really be of use if the output of the pH sensor is low impedance. If it's not then you will need a very high impedance voltage divider, and the analog input of the ESP8266 isn't high enough impedance to support a very high impedance voltage divider - it will skew the results horribly.

So you may need to buffer the output of the pH sensor through an op-amp first.

If you use a unity gain non-inverting buffer you can then use a voltage divider to reduce the output voltage.

simulate this circuit – Schematic created using CircuitLab

Alternatively, as others have suggested, use an external 5V ADC chip and logic level conversion to communicate with the ESP8266.


How do I activate emulation in the Coddeblocks Arduino IDE I stumbled upon this question here, so I tried the Codeblocks alternative. After opening an Arduino Project, and leaving all options to default, I ran the Arduino version of the Hello World. A popup opened that requests a serial port to move on. What error did I do?

If more details are needed I'll answer the comments. Thanks in advance!

I have not done extensive testing with the simulator but here is what you do open code blocks start a new project. Then under the target choose simulator. See the picture for details.

I just tested it out for the simple program but this looks pretty cool.


Best way to detect tilt using MPU 6050 I want to make a gesture controlled car using this IMU.. What is the simplest way to detect tilts? I've seen many programs on the Internet that calculate the angles but is this really necessary?
Why can't we just get components of acceleration in the x, y plane and then detect tilts..Pls tell me how to do this!

Well suppose you have a starting position, let's say 0 degrees, then once you detect and angle change, let's say 10 degrees, you know that there is a tilt of 10 degrees on one of the 3 axies.

The MPU6050 is a 6DOF, meaning 6 Degrees Of Freedom. This means that it can detect acceleration on axis: x, y, and z and it can detect gyro angles on axis: yaw, pitch, and roll.

For the best accuracy, use a mix of both acceleration and the gyroscope. This is the best way to calculate position. Heck, the Apollo space program used a gyro and accelerometer to navigate from planet Earth to the Moon.


How do I read a sub-degree angle? I need to measure (and record changes over a short time) the angle of a lever at a sub-degree resolution (The fulcrum can be the sensor) using an Arduino.

I've looked at rotary encoders, but even those with no detents have about 24 pulses per rotation. I need to measure only across a 90 degree arc. 24 pulses per rotation is 15 degrees per pulse. Which I guess results in a measurable resolution of 7.5 degrees!

I could add gears to increase the turns on the encoder, but that would increase the force required to move the lever.

Is there an option I'm not thinking of?

I've looked at rotary encoders, but even those with no detents have about 24 pulses per rotation.

It sounds like you have been looking at encoders intended for user input controls.

Optical Rotary Encoders for machinery applications are readily available with up to several thousand pulses per revolution.  Prices vary depending on if the wheel is glass or plastic, mounting options, brand, etc.

Do be aware that especially at the high resolutions, getting the encoder disk mounted perfectly concentric to the shaft being measured in important.  You would either need to buy a a wheel which already has a bushing of the same diameter as your shaft, have access to a lathe, or have something custom made.  (This is probably a case where a 3d printer is not accurate enough)

Also keep in mind that encoder wheels are often specified in cycles per revolution; with the typical two channel read head and quadrature decoding, there will be four times as many distinct state transitions.  So a mere 300 CPR wheel would give you 1200 counts per revolution.


Recording and playback sound I'm working in an art project, is some kind of loop between contact microphones and walkie talkies. I want to create some kind of noisy feedback.

I'm putting one walkie-talkie inside of a bottle, and in front of the speaker/microphone from the walkie I want to put another contact microphone attached to an Arduino, and record the sounds of the walkie talkie and played with some delay in some buzzer in front of another contact microphone attached to an amp with three speakers. To sum up, I have like 3 parts linked between them, the first one the walkie, the second one with an Arduino and the third one a simple mic whith an amp and three speakers.

Only the second part will be working with the Arduino and I want it to record sound and play it simultaneously with some delay.
I worked with a friend with some servo motors and music shields and I've been doing some research. I found 3 very interesting projects one is this, that it's practically what I want to do Space Replaybut there's so little information about it, and the other two are Arduino Audio Input and Arduino Audio Output
So, my questions are:

If I use a music shield I don't need a DAC or/and an amp? or only an amp if my speakers are too loud?
In the project Space Replay they only use this music shield so with only one music shield I can record and play music simultaneously? or I need two music shields?
That Adafruit Wave Shield is only for Arduino uno, but it will be better or easier to work with DUE or Arduino Mega and another music shields or making my own circuits like in the instructables Arduino Audio Input and Output?

I don't care too much about the quality of the audio, as I said the purpose is make some noise. The only thing is I want to create some kind of echo, or some kind of cannon, between the first sound of the walkie and the others pick up sounds.

Any other comment or advice will be much appreciated and welcomed.
Thanks

Try using this shield from Adafruit. I believe it can record and play audio, and they have versions with and without amps.

I do not know about near-simultaneous playback, so read up a bit before buying.


switch pump on with transistor, mosfet, or relay I would like to control a pump.
The pump rating is 12 volt 60watts.
The pump mfg says to use a 12 volt power supply of 5 - 12 amps but AT LEAST 5 amps. This pump has a pressure turn off at 116 psi and the mfg states that the pump will not make maximum pressure with less than 5 amps.

So the question becomes, to be able to switch this pump on and off based on some sensor reading what would be considered best practice:
transistor, MOSFET, or relay?

Transistor - Big voltage drop between C-E @ 5A (depends on type but it will be about 2V). Power dissipitation is voltage drop times current so about 24Watts. You must be careful with inductive load - induced high voltage must be supressed. Usual way is using anti-parallel fast diode over load.
Mosfet - Voltage drop can be really small, so it might be possible to use it without heatsink. Big Gate capacity needs strong driver to charge and discharge. If not, slow switching causes huge losses (again voltage drop times current). For inductive load it's same as for transistor.
Relay - It must be selected carefully as switch-off causes electric arc (= burning contacts) and because of DC current it's burning for much longer time than AC.


how to send argument to ESP8266WebServer objects on function this probably simple thing to do however I can't think of a way to pass argument to function call

ESP8266WebServer server ( 80 );

void toggleRelayOne() {
  char temp[400];
  String msg = "";
  if (relay1 == 0) {
    relay1 = 1;
    msg = "Light is turned on";
  }
  else {
    relay1 = 0;
    msg = "Light is turned off";
  }

  digitalWrite (5, relay1); //GPIO 5 // Relay 1
  snprintf ( temp, 400,
             "<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU DHT11 Sensor and Relay Board</title>\
    <meta http-equiv='refresh' content='0; url=../'>\
    </head>\
  <body>\
  %d .</body>\
  </html>"
             , 1);
  server.send ( 200, "text/html", temp );
}

void setup ( void ) {

  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );
  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( host ) ) {
    Serial.println ( "MDNS responder started" );
  }
  MDNS.addService("http", "tcp", 80);
  server.on ( "/", handleRoot );
  server.on("/relay1", toggleRelayOne);
  server.begin();
  Serial.println ( "HTTP server started" );
}

in the above function where I am calling toggleRelayOne using server.on("/relay1", toggleRelayOne); I want to be able to pass relay id so I can use same function to toggle multiple relays.

Use server.arg() to pass commands from the web as GET params:

digitalWrite (5, relay1);

becomes

digitalWrite (server.arg("pin").toInt(), relay1);

where the URL is something like http://192.168.1.5/relay1?pin=15

Of course, the rest of your code probably needs to be adapted to manage the extra states, read/write all in one http call, etc.


Strings that always stay empty I wrote an app that listens on the network for command over UDP and sends back an answer. Whatever I try to put into my answer never get sent. The string is always empty. The following code prints a length of 0:

String result;
for(uint8_t i =0; i <6; i++)
{
    result.concat( GetInput(i));
    if(i < 5)
       result.concat(':');
}
    result = "WTF???";
    Serial.print("GetAllOutput => ");
    Serial.println(result.length());
    return result;

I've been trying to debug and I can't figure what is going on. Initializing result to "" doesn't change anything.

So euhmm, I removed a couple of Serial.print() frome my code and now everything is working. Still I have no clue to what happened, but it works now...


I am looking for the source and/or proper definition for the int() function I am looking for the source and/or proper definition for the int() function.
I have searched through the source in Arduino.app, without much success.

The reference gives a terse explanation

int(x)
 x: a value of any type
 Converts a value to the int data type

Passing 1, '1' or 49 returns the int 1. I haven't tested other types.

This seems to be an Arduino specific function - it doesn't seem to be in any c/c++ library.

int(x) is not a function but another way to perform an explicit cast of x to an int. It is part of the C++ language itself, that is why you could not find it in a library.

This is not Arduino-specific.

In C and C++ you can cast a value to an int by doing this:

int y = (int) x;

C++ has extended this notation by allowing to do it this way, which is equivalent:

int y = int(x);

You can find this in more details in C++ language reference.


Water pump control hysteresis I'm using arduino with analog pressure sensor, temperature sensor and a relay to control water pump. The simple code I wrote works, but I want better control.

#include <OneWire.h>
#include <DallasTemperature.h>

 const int pinCidlaDS = 2;
 int pinA0 = A0;
 int teplota;
 int rele;
 float tlak = 0;  //ideal 290+-

OneWire oneWireDS(pinCidlaDS);
DallasTemperature senzoryDS(&oneWireDS);

void setup() {
 senzoryDS.begin();
 rele = 3;
 pinMode(3, OUTPUT);
 Serial.begin(9600);
}

void loop() {
 tlak = analogRead(A0);
 teplota = (senzoryDS.getTempCByIndex(0));
  if ((tlak < 285) && (teplota < 30)) {
   digitalWrite(rele, LOW);
   delay(7000);
 }
   else {
   digitalWrite(rele, HIGH);
   delay(500);
 };
 Serial.print("Tlak: ");
 Serial.println(tlak);
 Serial.print("Teplota: ");
 senzoryDS.requestTemperatures();
 Serial.print(senzoryDS.getTempCByIndex(0));
 Serial.println(" stupnu Celsia");
 teplota = (senzoryDS.getTempCByIndex(0));
 delay (200);

}

So now I'm using delay to get away from the treshold value. And I wanted to write a code that would work like:

Pressure is lower than 'x', relay ON.
Pressure rises to 'Y', relay OFF until Pressure is lower than 'x'.

What should I use? Could you please give me a example, if there is?
Thank you very much! :)

Implementing hysteresis turns out to be quite straight-forward:

float pressure = read_pressure();
if (pressure < x)
    turn_relay_on();
else if (pressure >= y)
    turn_relay_off();


Switch case options get broken after a function call I'm sorry for the basic question, but I have a switch case where any code placed after a certain function call simply never gets called, and I've spent half a day looking at it, so thank you so much for your help.
Running on an Arduino UNO.
Here is the loop, and every option in the switch case after the call to moist_sensor.read() simply never gets in:

void loop() {

  while (Serial.available() > 0) {
    char val = (char)Serial.read(); // read data byte by byte and store it
    Serial.println(val);
    switch(val) {

      case 'O':
            digitalWrite(13, LOW);

            break;

      case 'I':
            digitalWrite(13, HIGH);

            break;

      case 'W':
            water(2000);
            break;

      case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

//it never enters any of these cases below

      case 'M':

        //String reading2 = moist_sensor.packaged_reading();
        //Serial.println(reading2); // send the received data back to raspberry pi
        break;

      case 'W':

        water(5000);
        break;

      default:

        delay(5000);

    }
  }

I've tried changing the name of the function with fears of special keywords, swapping it with other cases (such as putting case 'W' above, where it works, and vice versa), and I always get the same behaviour. If i comment the line, everything works as expected.
I know the method isn't actually called all the time, but for sanity's sake, moist_sensor.readd() right now is just:
int readd() {
return 0;
}

It also works fine if its the last case, but this buggs me, and I want to create other cases with function calls.
Thank you so much!

You seemed to have solved it. For the reason, take a look at the compiler errors:
sketch_nov22a:31: error: jump to case label [-fpermissive]
       case 'M':
            ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
sketch_nov22a:38: error: jump to case label [-fpermissive]
       case 'W':
            ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
sketch_nov22a:43: error: jump to case label [-fpermissive]
       default:
       ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
exit status 1

If you got it to compile your compiler must be configured a bit differently to mine. However you can see that by putting int reading = ... in the case block, the compiler tries to execute that first (to initialize reading) which causes it to jump case labels.
By moving int reading outside the case statement, the compiler no longer has to initialize the variable, and that line merely becomes a function call and assignment (not a variable initialization).

You can avoid that by putting the code into its own block, that is, instead of:
  case 'E':

        int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
        //Serial.println(reading); // send the received data back to raspberry pi
        break;

Use:
  case 'E':
        {
        int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
        //Serial.println(reading); // send the received data back to raspberry pi
        }
        break;


Are INTx pins the only ones eligible for Software Serial? As opposed to PCINT (Atmel's Pin Change INTerrupt, INTx is arduino-compatible interupt)  In other words, does Software Serial use atmel's pin change or arduino falling interrupt?

SoftwareSerial uses PCINT.  AltSoftSerial uses INT0 or INT1, which has FALLING, RISING, CHANGE or LOW LEVEL options.  See Section 12.2, p. 71 of the Atmel ATmega328 spec, for example.


Interfacing accelerometer LSM303DLH with Arduino UNO using I2C I am trying to connet a tri axis accelerometer LSM303DLH to arduino UNO using the libraries taken from the following links (https://github.com/adafruit/Adafruit_LSM303DLHC and/or https://github.com/ryantm/LSM303DLH) but none of them work.
Using the following connection:
SCL on A5,
SDA on A4,
Vin on 5V,
Gng on Gnd.

I should be able to see the values of the accelerometer but the serial monitor is empty.

I've tried inserting a few print in the libraries to understand where the execution stops, basically after a Wire.endTrasmission() the program doesn't go forward.
How can I connect the accelerometer using I2C?

Are you using one module bought from Adafruit?

Make sure the connection is correct between the sensor and Arduino, then make sure that the script doesn’t get stuck when the Wire is begun.

Another thing that you need to make sure, is to have the correct address, it depends from board and each one can have a different one or a selector.

This can be helpful to figure out what the wiring is


Corrupted files generated by Arduino with SdFat library. How to avoid that? I got:

https://www.arduino.cc/en/Main/ArduinoBoardDuemilanove
http://wiki.iteadstudio.com/Stackable_SD_Card_shield_V3.0 (set to 5V logic)

with this sketch using SPI/SdFat+OneWire/DallasTemperature+EmonLib and no matter what I try I got corrupted files like this.

I even haven't attached my sensors yet :(
I have tried with 3 SD cards so far, each formatted with SD Memory Card Formatter and each one has this problem.

There is a separate question like that (Corrupted files generated by Arduino with SD library. How to avoid that?) but it concerns SPI confict but here SD is my only SPI device on the bus.

Any ideas?


Arduino Uno unable to detect serial port on MAC os Mojave 10.14.2 Ive upgraded to Mojave.  I've never used Arduino before.  I was given Arduino Uno.
Arduino Uno does not find any serial ports... can't load Blink example (the first step)

In blind frustration, I tried the three ports available... None of work.

I've loaded the
CH34x_Install_V1.4.pkg
to no avail.

How do I get a serial port package that will enable serial ports in general (and more importantly for arduino)

thx,
Bruce
On a related Note: the list of things that Mojave broke is long!  To solve many problems, re-install xcode FIRST!!! and read articles on apache, there is a "new and improve" apache server embedded in mojave.

If you are using a genuino or genuine Arduino, the most common cause of this is using a USB power only cable to connect rather than a data cable. (You only need the CH34x_Install_V1.4.pkg if you are running an Arduino clone based on that chipset)

If I ran the world, the USB standard would include some way to distinguish whether it's power only or power and data without having to test it with a multimeter. I know, I know, that's crazy talk.


Can I program a factory fresh Atmega328P through UART pins without burning a bootloader? Can I program a factory fresh ATMega328P using the UART pins without burning a bootloader? These pins are TX, RX, VCC, GND, and DTR pins in the schematic below. They are not the ISP/SPI pins 10-13.

Arduino Pro Mini schematic

For example, if you program an Arduino Pro Mini (which requires an ICSP programmer) with a programmer, you're not connected to the ISP pins (basically the SPI interface: MOSI, MISO, SCLK, SS), but rather to the serial i/o and reset pins.

My understanding is that a bootloader is required if you want to program through these pins, because the Arduino bootloader looks for UART traffic at these pins upon startup and hands off operation to the user's code if no attempt at programming happens during this time.

That said, I also understand burning a bootloader is done through the ISP/SPI pins, and my PCB is already manufactured, which makes burning a boatloader somewhat of a hassle. So...

Can I program an ATMega328P through the UART pins fresh off the reel, or will I need rig up a way to burn a bootloader through the ISP pins first?

No, the ATmega's ISP does not operate over the UART pins but only the ISP pins.

To program it via a UART, you need to first load a bootloader, unless your chip was pre-programmed by the vendor, something some offer as a value-added service (or even as an essential stock item, with an Arduino type bootloader)


Decoding a RS232 message in Arduino I have an Arduino Mega with an MaxBotix (MB7066) sonar attached, the sonar has the ability to send serial data with it's reading. It uses a asynchronous RS232 format, except the voltages are 0-Vcc. The output should be a capital "R" (ASCII), followed by four digits(ASCII) and a carriage return (ASCII 13). The baud rate is 9600, 8 bits, no parity with one stop bit.
What I get from the device is as follows: (sonarSerial.read() while sonarSerial.available())

43
192
6
6
179
89
30
0

What do I have to get to the information? Or is my sensor just retuning garbage?
Please see the code below:

#include <SoftwareSerial.h>

#define pin1 3
#define pin2 5 //pwm
#define pin3 6 //analog
#define pin4 10 //RX for sonar, TX for arduino
#define pin5 11 //TX for sonar, RX for arduino

SoftwareSerial sonarPort(pin5,pin4);

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

   pinMode(pin4, OUTPUT);
   pinMode(pin5, INPUT);
   sonarPort.begin(9600);
}

void loop(){
  digitalWrite(pin1, HIGH);

  digitalWrite(pin4, LOW);
  digitalWrite(pin4, HIGH);
  delayMicroseconds(20);
  digitalWrite(pin4, LOW);

  long pulse = pulseIn(pin2, HIGH)/58;
  Serial.print("PM Result: ");
  Serial.println(pulse);

  String buffer = "";
  sonarPort.listen();
  while(sonarPort.available() > 0){
      int inByte = sonarPort.read();
      buffer += inByte; buffer += " ";
      if(!sonarPort.available()){
          Serial.print("Serial result: ");
          Serial.println(buffer);
      }
  }
  delay(500);
}

I contacted MaxBotix with the problem and for my surprise their technical support is really great:

  The Arduino is set up to natively read TTL serial data.The MB7066 outputs its serial data in the RS232 format. Do not worry; this problem can easily be fixed. You can use an inverter such as the MAX232. You can also follow the following tutorial to make your own https://github.com/simonmonk/raspirobotboard/wiki/Rangefinder-Adapter.

  Another option would be to test using this code section SoftwareSerial
  sonarSerial(rxPin, txPin, true); //define serial port for recieving
  data, output from maxSonar is inverted requiring true to be set.


Unable to upload code to the Arduino Nano I tried to to upload a hex file I generated for the Arduino Nano using avrdude but I keep getting the error:

avrdude: stk500_2_ReceiveMessage(): timeout

First the arduino board stops doing whatever it is programmed to do, in this case powering a vibration motor .
Then this error keeps showing up in delays of around 10 seconds.
That error is then followed by

avrdude: ser_recv(): read error: The I/O operation has been aborted because of either a thread exit or an application re
quest.

which appears to be caused by me pulling out the USB cable after waiting a while.

Thanks

I suggest you disconnect the motor while you are uploading. The power it is using, or the electrical noise it is generating, may intefere with the uploading process.