text:
Looking for learning resources to teach the "principles" rather than "follow this" projects
I just got the Arduino starter kit as my background is software developer (C++, python, etc) and I'm interested to get into the electronics side, and I love LED effects and home automation of all kinds.
As such I'm quite comfortable with the type of C programming required (loops etc) but need to learn the principles of electronics.
Can you suggest any resources (websites, tutorials, books - I'm willing to pay for books if they are useful) whose focus is teaching the principles as well as doing specific projects?
The kit came with the "Arduino Projects Book" but I don't really like it as it's focused on "do this, do that, put the circuit together according to this diagram" rather than explaining the principles first. For example I did the "Spaceship Interface" (light up different LEDs in different patterns based on whether a button is pushed or not) and it introduces things like "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino [...] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)
I'm asking about general principles rather than the specific case of why do we have a 10kohm resistor in this case, but this is a pretty good example early in the book.

Google is your best option! It's free and all is there. If you don't understand something, post a question on this Q&A site and maybe we can help you!

Meet your new bible.

Welcome to the Arduino world!
First I'd like to try to answer your question: (This explanation does not apply to his situation as explained in the comments, but, I guess, it's a fun and useful read so I'll leave it here)

"You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino [...] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)

I haven't seen your circuit but I think I know the deal here. The author is basically telling you to create a pull-down circuit. What this does is, what it says. It pulls down the voltage on arduino pin to GND. Now, why would you want to do that? I think because in your project, the author was reading analog values from that pin. He wants the pin pulled down because otherwise when the switch is open, the pin would be floating i.e. not connected to anything. Floating pin means that you will get random analog readings from that pin. Basically, if you don't connect that pin to any source/sink, it will act as an antenna. You will get noise. (You can actually use this to create random numbers for your arduino!)
Now, about that 10kOhm resistor: Its depends on two things. First, if you put a low value resistor, then you will draw lots of current from the supply to the ground when the switch is closed. You normally don't want that, why spend energy more than you have to? So, you pick any big resistor that you can possibly pick. But how big can you really put there? This depends on the analog read pin's current consumption. Whenever you do an ADC (analog to digital conversion) a.k.a analog read, your pin sinks/supplies tiny amounts of current and samples it to determine voltage. Atmel datasheet says that:

As you can see, the good guys in Atmel already did some tests and determined that with the current Atmega328p (Arduino-UNO chip) chip, a source of 10kOhm internal resistance is sampled the best. (When you open the switch, the 10kOhm resistor is basically a 0V source with 10kOhm internal resistance)So basically, I guess, that's why the author used 10kOhm. Could you have used 20kOhm instead? Of course...
Now about the electronics book thing. The best practice with electronics is to both read and do. So, whatever book you pick, make sure it has examples and explanations that you can try. Don't buy a highly theoretical book with lots of math and physics. Don't use a simple do-this do-that book either. I can't provide you a single good book, because that's not how I prefer to learn. But I might have some good suggestions for you if you prefer to study like this as well:

Learn the basics or R,L,C. Study filters, energy, their differential equations etc. Any book, website will do.
Use software and simulate theoretical/explanatory circuits. LTSpice is best. For bigger projects, something like MATLAB is better.

If you do that, you'll gain some insights on how things actually work.

Move on to transistors: BJT, MOSFET etc. What are they and how they behave?
Combine transistors and R,L,C to create some digital-analog circuits. How do you make a RAM cell? Can you make an arithmatic logic unit?

At this point, you should be comfortable with most elements of electronics.

Since you started with arduino, study RISC/CISC architechture. What actually is a microcontroller?
Since you know software, try using assembly code to turn on and off some leds. This is where you meet software and hardware at the lowest possibly level you can.
Try to make your own microcontroller using FPGA! (I've done this -it was a simple and not-so-useful CPU but nevertheless it provided insight. You can invent your own assembly language!!)

At this point you should be able to understand most basic arduino projects.

Read atmega datasheets.
Read Transistor, motor driver IC etc. any driver datasheet and search the terms on google. What do they mean?

After that you can do this:

Pick a project, and do it from scratch. Without, copying any circuits from the internet. Can you place atmega chip to work stand alone, away from arduino board? Can you use that and make for example a BLDC driver?
Pick a project and ask stackexchange. (Well, obviously). There are some really brilliant people here that are willing to help. Personally, I feel I'm learning better if I try to answer other peoples questions and ask questions.

I guess the downside/upside is you never stop learning. Electronics combined with software is a huge area of expertise.
So I wish you Good luck!

Maximus, if you look at the circuit on page 36 of Arduino Projects Book.pdf and the description on page 37 (“Attach one side to power, and the other side to digital pin 2 on the Arduino. You'll also need to add a 10k-ohm resistor from ground to the switch pin that connects to the Arduino.”) you'll see that the input is on digital pin 2, so has nothing to do with analog input.  So 10KΩ source impedance being preferred for ADC inputs is totally irrelevant.  20KΩ to 50KΩ like the built-in pullups would work just fine.

@jwpat7 Well, like I said, I didn't see the circuit. (Don't have the book) However, even if this was a digital input, the logic is similar. Because, there is an input capacitance C, which is at 5V at the time of switch release and it will be discharged through R to GND, right? So, the greater R you pick, the slower the discharge. If the discharge is slower than 1 instruction cycle, then it is possible that the arduino detects noise (because voltage around ~2.5V can be undefined). Oh and I don't think he can use internal pull-ups in that situation. Because, then he'd always get 5V on pin 2.

But I agree with your point on ADC. That one turned out to be irrelevant. (Sorry). I'll leave the explanation there just because I think it applies very well to ADC pins and I think people might find it useful.

I see people are voting to close this as too broad. Well, it is broad, but I'll try to give you some pointers. I used to wonder this stuff too, like "why use 10k and not 20k or 5k?". A good starting point is to watch some of Dave Jones' EEVblog videos.
For example Designing a Li-Ion Battery Gauge with the LM3914 - EEVblog #204 - this is already 5 years old. He has done a lot of them. This particular one describes using the LM3914 chip to make a battery gauge, and in the middle he works through the resistor values using Ohm's Law.
Another entertaining and informative blog is Afrotechmods. He also goes into detail but in a humorous way.
Also try M J Lorton's blog.
My only problem with videos is, if you are trying to reproduce some of their stuff you end up having to rewatch a (perhaps lengthy) video and pause it from time to time to copy stuff off the screen.
For this reason I made some posts of my own on the Electronics part of my own forum. (Some of the more popular ones are also here in Stack Exchange as reference questions, for example How do you use SPI on an Arduino?).
You could also look at the Adafruit and Sparkfun tutorials (amongst many others).


text:
Why doesn't the Ethernet W5100 shield work on Gigabit switch?
I have an Arduino Uno with an Ethernet Shield based on the Wiznet W5100 chipset :
It worked like a charm until I had to move it to another location and plugged it to a Gigabit switch. I had no link, the plug LEDs were off, or just on for a fraction of a second then off again.
I tried several switches, router and Internet boxes (french Freebox), and I ended up with the conclusion that it doesn't work when plugged onto a Gigabit switch. On every 10/100 switches, it works.
BUT
I also have a W5100 small module not designed like the shield :

This one is working on Gigabit switches !!!
I did see another post here : WizNet W5100 not connecting to modern switches and routers, where someone told the lower bits of the first MAC Address byte should be 00. So I changed the MAC address to 08:af:01:00:00:03 with no more luck, the shield still doesn't get connectivity.
I googled for this but didn't find any resources. I'm surprised this hasn't come over, knowing that so much ethernet shields are out on the market!
I tried a second shield (like the first picture), same issue : no connectivity on Gigabit switches.
I know other old NICs or laptops that don't support Gigabit are working correctly with Gigabit switches that should "pull down" the port to 100 instead of 1000.
Does anyone have an answer about why it doesn't work and how we can have an Arduino work when connected to a Gigabit switch? (other shields?)

The fix for this is to solder a 120 Ohm resistor between pins 1-2 and 3-6 of the RJ45 socket (where pin 1 is closest to the left side of the socket when looking at the top of the board. (Credit to keithsw1111 for the fix)
See https://forum.arduino.cc/index.php?topic=372779.0 for full details.
I know this was asked a long time ago however this post comes up quite high on a google search of the issue so its good to have reference to the fix.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Arduino-RS232 converter baud rate problem
i have built a TTL/RS232 converter to send strings via RS232 using an Arduino nano, following the tutorial:Arduino-RS232. My problem concerns the transmission baud rate, because in the tutorial it is suggested a short script which manually generates the code which will become the RS232 signal. In this script some constant delays are used, i.e. "bit9600Delay 100 " and so on. These delays are set for a baud rate of 9600, but i need to double it to have a baud of 19200. Is it enough to divide by two those constant values or should i use a different method? Thank you very much

Do you notice anything when you look at the 4800 baud values?

Dividing by two may not be the best option since bit4800 delay is 188 and bit9600 delay is 100.  Seems like the delay is mainly used for reading the bits that were sent over the RS-232 port.  So this wait time may be good to run at 19200 bps.  After all, it looks to me like it is a simple delay to allow enough time to read back data without having it being distorted (nonsense).

It is never good to base code on delays instead of intervals.  This is especially true for faster intervals where the execution of the code its self consume a significant portion of the interval.  Also note, some protocols only occasionally resynchronize.  RS232 resynchronizes after each byte (about 8 bits of data).  So any accumulated delay errors may impact the integrity of the bits furthest from the resynchronization event.
Instead of delays use the Arduino's built in hardware to send and receive RS232 communications.  The hardware is designed to work independently of code execution and will out perform software implementations especially for the faster baud rates.

The waters might be a bit muddy here.  I think the Arduino's delays are based on the number of ms passed (intervals of time).  So they might be somewhat immune to interrupts.  (That is to say, they may not be simply dumb loop counters.)  Still, the built in processor HW is a much better choice for RS 232 communications.  But, if you need a SW implemented RS 232 port, there are libraries which have already lamented over these problems of balancing code execution time against the necessary delays needed to generate the proper baud rate.

Yes, the normal delay is based on time. delayMicroseconds is a tight loop. This is partly because of the granularity of the timer used for millis, micros and delay.

This Arduino sketch is a wonderful opportunity for you to learn the very basics of serial communication.
You should be very careful scaling the constants given in any baud rate program (whether using a hardware or software UART) as they are normally off by some small percentage, and without understanding the implications you may eventually introduce timing errors.
There is a great description of the timing sensitivities in this Picaxe note.
The table below shows the actual bit times for various baud rates:

Notice here that for 9600 baud the sketch uses a constant which will use a 100 uS delay function for the bit times. From the table above you can see that this is slightly inaccurate, and the more correct delay would be 104 uS. This is an error of about 4%.
Would this error prevent successful reception of characters in the sketch?    Single characters with inter character spaces more than 1 character time, no ....but if you sent a string of characters end to end with no gaps this sketch would fail on receive.
Scaling the constant for 19200 baud --> 100/2 gives 50 but the bit time for 19200 is actually 52 uS, so again an error, this time of about 1%.
If we scaled the constant (100) for 115200 --> 100/12 gives 8.3 uS while 104/12 gives 8.7 uS for an error 4.5% or close to 0%.
There is IMO an error in this sketch for the serial receive routine, since it's hard wired to expect 2 stop bits. Any concatenated characters separated by only one stop bit will fail (you miss the second character start bit).
int SWread()
{
  byte val = 0;
  while (digitalRead(rx));
  //wait for start bit
  if (digitalRead(rx) == LOW) {
    delayMicroseconds(halfBit9600Delay);
    for (int offset = 0; offset < 8; offset++) {
     delayMicroseconds(bit9600Delay);
     val |= digitalRead(rx) << offset;
    }
    //wait for stop bit + extra
    delayMicroseconds(bit9600Delay);     ....hard wired two stop bits
    delayMicroseconds(bit9600Delay);     ....or 1 stop and 1 bit time gap
    return val;
  }
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
ArduCam ESP8266 and (Not-Mini) OV2640 Camera Module interface?
I bought ArduCam ESP8266 and a OV2640 Module. However it is not the mini-version. At the time it didn't seem like it was necessary.
I might have made a big mistake here.
The board has 8 female pins specifically for the camera module. But the OV2640 module has 20 male pins. A mini-version of the same camera leaves 8 pins, and has a nice interface.
I might have to send this back and get that one, but I want to know if it's possible to simply use this one and wire it up with certain pins instead?
Links to the two products to be specific:
http://www.arducam.com/camera-modules/2mp-ov2640/ (Camera)
http://www.arducam.com/arducam-esp8266-uno-board-arduino-camera/ (Board)
Thanks for your help,
Fred

No, you can't "mix and match" like that. The 8-pin header has I2C and SPI on it for a "cooked" video interface. The 20-pin interface has the "raw" camera CSI interface.
The difference is, the mini version has its own small video processor and FIFO chip on it which processes and buffers the video image allowing you to take a picture then slowly stream that data back through to the slow Arduino at a speed it is comfortable with. The non-mini version doesn't have that and relies on the host controller board having enough power to process a live CSI video signal, which the Arduino cannot do.

Okay. Thanks for the info.
From the data sheets I understand what you mean now. I'm going to have to send this back then...
I was wondering about the rest of the pins of the board. I see they are linked to certain elements of the 8-pin header. Would the board still have some pins (say 3) free for extra PWM motor controllers?
It seems pins such as D4 D3 may not be used, but I'm not 100%...
Thanks,
Fred

It looks like they have a lot of pins doubled up on that board. I'd be surprised if you could really use the Uno-format headers for anything much TBH. That's the problem when you choose the wrong chip for the job. That board should have been made with a completely different chip on it so that it had enough pins to actually provide the GPIO it purports to provide. It's really not clear from their pinout diagram which pins can be used for PWM, and quite unclear that you only have a fraction of the actual GPIOs that it looks like you have. Even within the Uno footprint headers themselves ...

... there is a massive amount of pin duplication. You would probably be better off interfacing the Arducam Mini manually with a more capable board, such as a Mega2560, which has more pins available so you don't have any doubling up. After all, it's only 8 wires to route, and that 8-pin header isn't anything special.

I have just done a count: you have a massive 11 GPIO in total on that board. 6 are used by the 8 pin header. 1 is used by the SD card. That leaves a grand total of 4 GPIOs that are of any possible use - GPIO0 or GPIO1 (depending on board version), GPIO2, GPIO3 and GPIO15. That's less than useful really - and only one analog input as well. As I say, better off using a more capable board and interfacing things like the camera, WiFi, etc manually.

Lets say I didn't use the SD card. And that I wanted to two 3 servos and two motors. Doesn't that require 5 GPIOs left? Aren't all GPIO's PWMs?
What would happen if I tried to use the GPIOs for something?
Another options is to just get another small ESP8266 Dev board like Wemos, which is relatively cheap. Another battery I guess but maybe easier?

I think the ESP8266 does purely (timer based) software PWM. I would be tempted to add a real Arduino into the mix for your hardware interfacing. Use the ESP8266 purely for the WiFi and the camera, and as a "master controller". That then interfaces to a real Arduino through some serial protocol of your choice (I2C maybe?) to perform real hardware PWM and give you lots more GPIO available. Kind of like an IO-expander-on-steroids.

In the end I bought another board - nodeMCU Esp with motor break out. It does 2 DC motors and a bunch of servos, as well as a stepper. So I Think it's a lot better. I'll have to see about integrating it into something like you said later too.


text:
How to transmit characters or just use xbee like serial monitor
I have an arduino mega and an uno, mega has an xbee s2c as coordinator and uno an xbee s2c as router, both in AT ( transparent ) mode. When I send integers from uno with Serial.write() coordinator receives just fine, but when i try float, negative numbers and chars, i get still integers but as I found out sending chars it is in ASCII. I tried Serial.print() but no result. Is there a way to send a negative float from one xbee to the other in AT mode?
Coordinator code
void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial1.begin(9600);
  Serial.println("Comersing test!");
}

void loop() {
  if(Serial1.available()>0){
         Serial.print(Serial1.read());
    }
}`

UNO code
#include <SoftwareSerial.h>
 SoftwareSerial xbSerial(8, 7); // RX, TX
void setup() {
  xbSerial.begin(9600);
  xbSerial.write("First data sent!");

}
int x=4;
void loop() {
  // put your main code here, to run repeatedly:
      xbSerial.write(x);
      x++;
      delay(1000);
      delay(1000);
      delay(1000);
}

if I change x in Uno to float, negative or char, I get weird values.

If you can send ASCII and you have control over both ends of the data then you could send the numbers as text strings (not very efficient).  If the number have a limited range i.e. -127 -> +127 then you could send 0 when you wanted to transmit -127, 1 for -126, etc.

XBee cannot send negative integers, as it is working in hexadecimal and it has range between 0-255

I'm afraid that's not true, if it was then no computer would be able to represent negative numbers.  It all depends on the encoding.


text:
Arduino as wireless network host
I have a rather simple question, which I cannot seem to find the answer to online.
I would like to host a wireless network using an arduino. Other devices could connect to and communicate with the arduino. Could I do that with a shield like this?
Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?
Thank you!

While not impossible, this is generally a bad idea - a classic Arduino is desperately short on memory and computational resources to manage network communication with one other station, let alone several.  There are far more capable alternatives out there at lower prices - esp8266, router chipsets, etc.

Yes!
You can absolutely do the above said task with the shield that you provided information about.
All you have to do is to connect the Shield to the Arduino and upload the WiFiWebServer sketch from the Arduino's examples in the WiFi library!
Then you'll have to replace the SSID and Password with your WiFi's password.
Once uploaded, then you'll get your Arduino's (Server's) IP Address on the Serial monitorl.
Note the IP Address and open any browser on any device of your choice.
NOTE-
Your device must be connected to the same WiFi network to which your Arduino is connected to. If you wish to access the Arduino server from outside your LAN then you'll have to forward/open a port on your WiFi router and direct it to the IP Address of your Arduino. But I am assuming that you just want to access it from your LAN therefore the port forwarding can be ignored.
You'll see the default webpage in the Sketch which you can change/edit as per your own wish by using HTML.
Here's the link to the detailed explanation from arduino.cc itself.
Coming to the Second part of your question: "Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?"
Well once the server is started on the Arduino all you do is type the IP of Arduino in the browser of the device and then the browser sends a HTTP request to the server.(This is the same way in which the browser sends requests to any other website or server like google/youtube/stackexchange . It is same for all ).

Can a device connect directly to the arduino? Rather than both connecting both devices to an existing network, I would like to broadcast a network FROM the arduino.

Yes ! Absolutely but not with this shield. That requires both the device and the Shield to support ad hoc wireless mode, most of the devics do have the ad hoc conectivity but the Shield does not! So you have to find another shield for that and then it would work! But as far as this shield is concerned This is the only possible way to set up a server!

It looks like the ESP8266 supports this! Thank you :)

If my answer helped you then you can upvote/ mark it correct answer Thank you :)


text:
Motor shield for Arduino Nano ATmega328
I am looking for a cheap and not so space consuming motor shield for my Arduino Nano ATmega328. I would like to charge the whole thing with a 9V battery. The shield must have at least 2.1A of output current so I can run 3 brushed DC motors on it. There will also have to be some pins left for a Bluetooth card and 3 analog pins for sensors.
Do you know any shields that meet my requirements?

In short:
Nano + Shield = no possible

[...] 9V battery. The shield must have at least 2.1A of output [...]

You can't invent power out of nowhere.

Options for the shield
Option 1:
Use an other Arduino. It will simplify everything.
Option 2:
Use a Nano to Uno adapter.
Option 3:
By an Uno shield and connect it pin by pin to the Nano.
Option 4:
Use MOSFETs. They'll work fine for what you are trying to do.

Options for powering
Option 1:
Use a 2s lipo. Voltage is above 5V so you have to reduce it with a down converter, but you should have enough juice for the motors.
Option 2:
Use a lot of AA, some in series to augment the voltage and then in parallel to augment the current.
Option 3: (just the the crazy minded)
Use a lead-acid battery (aka car battery).

Is  there a way, when using MOSFETs to switch the direction of the motor's rotation?

H-bridge. https://www.youtube.com/watch?v=iYafyPZ15g8

But why can't I use the regular 9V battery?

9V doesn't have enough current.

What is its current?

Depends, but they are mostly below 500mAh

Doesn't that mean I can run all of them for just 0,2 hours?

If it doesn blow up because you draw too much current.

Ok, I will try the AA battery tehnique. Thank you btw


text:
Why is the loop() stopping?
I would like to move my servo motor (SM-S2309S) between random angles. In order to do so, I used this simple code:
#include <Servo.h>
Servo servoMain; // Define our Servo

// SM-S2309S angular speed
float speed = 0.12/60;

void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}

void setup()
{
   servoMain.attach(10); // servo on digital pin 10
   Serial.begin(115200);
   // move to center as a start
   servoMain.write(90);
   delay(1000);
}

void loop()
{
  // the previous angle, initially set as center (per the setup() call)
  static int oldangle = 90;
  // apparently 15 to 165 deg is a safe range
  int newangle = random(15,165);
  Serial.println(newangle);
  move(oldangle,newangle);
  oldangle = newangle;
}

It starts by placing the arm in the center (in the setup() function) and then should generate a random number (the new angle to go to), in a loop.
What I get is the initial position, then two moves (counterclockwise, then clockwise). The output on the serial console shows 22 and 64, which is consistent with the two moves.
Then everything stops. There is no error message on the console (I do not expect one to be, but I am not sure if there could be any feedback from the Arduino, being a complete beginner). What can be the reason for this stop, after two successful loops?

Does it STOP or it RUNS but nothing happens?

@DatHa: sorry, I do not really understand your question - should there be a feedback informing me whether the program still runs or has stopped/crashed? I saw the two random values for the angle output on the console (associated with the two movements of the servo motor) and then nothing else. How can i check if the program is still running or whether it has crashed (it should at least output the new random angles if it was still running, I believe).

flash a led in the background

@DatHa: ok, thank you very much for the hint. I will look at how to have the LED blink independently of the main loop() (I guess that this is what you meant, otherwise the output of the new angles on the console would have been enough, no matter of the servo moves or not)

Just a small mistake! Not much big of a deal :D
In the move function
void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}
suppose the values passed are 20, 35 then the last line would be 1000*speed*(-15) Which is negative therefore the arduino delay function converts the - signed bit to a very large unsigned number.
All you have to do is to take the magnitude of from - to ie |from - to | by calling the abs() function.
your move function would look like this:
void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * abs(int(from-to)));
}
Just alter your move function or copy mine and you'll have no problem at all!

Ah! Thank you! I used int() when I actually meant abs() to exactly handle the case you mention.

Hahaha Pleasure is mine!

“The arduino delay function hangs as it does not allow negative parameter”  is absurd nonsense.  That is, it is wrong, wrong, wrong.  The parameter to delay() is an unsigned long, which is never negative.  When (as in your example) from-to is -15, the delay called for is about 2147483618 ms, or about 3.5 weeks.  So  delay() isn't hung, it's just doing what it was told to do.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Code is supposed To extract data between * ie *989*= 0989*; Runs only once then doesn't please help
void loop() {
       char *stptr=&string[0];
       if(Serial.available() > 0)
       {
          data = Serial.read();
          if(data=='*')
          {
            ib=1;jb=0;
            string[0]='0';
            //Serial.print("GOT INTO IF");
            while(string[ib-1]!='*')
            {
              //Serial.print("Got into reading while");
              //Serial.print(string[i]);
              if(Serial.available() > 0)
              {
                if(string[ib]!='*')
                {
                  string[ib]=Serial.read();
                  ib++;
                }
              }
            }
         }
      }
}

Please put your code in a code block so it is readable.

Do you seriously need those commented lines?

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  State a question and a context clearly in the body of the post, rather than just vaguely hinting at it as in the title.

Something like this should work:
void loop()
{
    char *stptr = string;
    if (Serial.available()) {
        data = Serial.read();
        if (data == '*') {   // Check for starting *
            *stptr++ = '0';  // Copy '0' to string

            // Loop until: no data in port, or second * received
            while (Serial.available() && '*' != (data = Serial.read())) {
                // Copy to string
                *stptr++ = data;
            }
            // Terminate string
            *stptr = '\0';
        }
    }
}


text:
Programming ATMega328p using VP812 programmer (for AVR/Atmel chips)
I bootloaded an ATMega328p (the one that uses the basic Arduino bootloader). Then, I used the VP812 for dumping other programs written in C (in Atmel Studio).
The process of erasing, blank test, programming and verification are all working fine and it seems that the program is actually being flashed. However, when I insert the same chip (controller) back in the Arduino Uno board, the controller doesn't function as programmed. Also, I am not able to dump any other example sketches.

Does this mean that the chip is damaged?
Does using the bootloaded chip with VP812 cause such problems?

Also, I used the "Write Fuse" option with the standard fuse configuration (all marks checked) in the VP812 configuration dialog box. Did this setting in any way create the problems I am facing now?

There is no way for us to tell, you have to check power and comm, the oscillator. You could have ESDed the chip and get intermittent results.

Yes - the settings created this problem. You have erased and disabled (via default fuses) the bootloader. It means that your application will run perfectly fine on an Arduino board, but you will not be able to flash over USB.
If you want to use Arduino USB bootloader again then you have to follow this guide


text:
Several Piezo contact mics with Arduino
I'd like to connect about 6 contact mics to my arduino and receive simultaneous signals to be used in my computer for an art installation.
Nonetheless, I don't know what's the ideal way to go. Shall I use Analog pins or Digital? How should I connect them - what schematics shall I follow? I read that ADC is CPU intensive, but I couldn't really find any viable alternative that explicitly shows the Digital deal.
Can I connect several contact mics to different analog pins and receive their input simultaneously as shown here? If this works, then it's perfect.
https://www.arduino.cc/en/Tutorial/Knock

What are you trying to do with the audio?

You'd probably damage your Arduino using that method - nothing to stop excess voltage or current from the piezo if hit too hard.

Thanks for comments! I'm going to create other audio :). So I only need data actually, which in turn I can use to create audio... So should I connect digital pins, or use some different parts in the circuit? Andy, how can I simply connect then?

Without a spec for the signals these transducers put out, and what you want to interpret from those signals, there is no question here.

Just a heads up, processing 6 audio signals and synthesizing other audio is a task unlikely to be able to be performed by the Arduino. Even a single-in, single-out audio is fairly limited, and typical synthesis requires assembly-level optimization.

simulate this circuit – Schematic created using CircuitLab
A piezo element can be connected to an analog input (A0 for example) of your microcontroller, but extra resistors are advisable if you wish to have a digital sample that is linearly proportional to the element's alternating voltage.
Andy's caution about over-voltage is relevant too - these elements can produce voltages far greater than your Arduino's DC supply voltage. Such over-voltage can cause damage. Resistor R3 helps limit potential damage.
Each piezo element will require its own set of three resistors (duplicates of R1, R2, R3). Many microcontrollers have multiple analog inputs - you can have as many piezo circuits as there are analog inputs. You cannot sample them all simultaneously, since most microcontrollers usually have only one analog-to-digital converter, which is switched between its various analog inputs by program control. A piezo element would have to be sampled, then switched to the next element for sampling, then the next....etc.
Sampling can be done fast enough that "audio" (however you define it) is fairly represented by the digital sample stream. However, be aware that processing these audio samples may be beyond the speed capability of simple microcontrollers like Arduino. That part is up to you.
Be aware that piezo elements make poor microphones. Units mounted in plastic shells are designed to output audio tones, and have significant resonant peaks. Frequency response is not flat, as required by a proper microphone.

You're a GOD. Much more information than I asked, but all needed. Thank you very much! I'll surely give it a try! By the way, it'll be activated with touch, so all I need is just the basic data to when people are touching, and in what degree... So the ideal seems to be to connect to digital pins but not sure how to do that either... But thanks!

@Emo , Thought your application was audio, not finger-pushes. Piezo's are sensitive for finger-pushes - a hard push will easily produce full output. With no push, data should eventually settle to half-way. "Release" should yield data opposite a "push". A constant-pressure "push" will also settle to half-way. These piezo elements are very brittle - cannot take much pressure before snapping (but then you have TWO piezos).


text:
Why does the serial monitor needs to be repeated a command?
I am experimenting with the serial monitor in an Arduino Uno. My project consists in a simple LED turning on and off at will with the commands "ON" and "OFF" respectively.
To achieve this, I use an HC-06 Bluetooth module, but because of the nature of the test I decided to disconnect it and 'debug' my project using the serial monitor as an equivalent.
The circuit has the following connection table:
LED +: Pin 12 on my Arduino.
LED -: GND on my Arduino.
...as you can see, I have tried to simplify as much as I can the circuit, as I wanted to make sure I didn't have wire problems.
Here's the code:
char command;
String string;
#define led 12

void LEDOn()
    {
          digitalWrite(led, HIGH);
    }

void LEDOff()
    {
      digitalWrite(led, LOW);
    }

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

void loop()
{
     if (Serial.available() > 0)
           {string = "";}

     while(Serial.available() > 0)
    {
           command = ((byte)Serial.read());

           if(command == ':')
           {
                  break;
           }

           else
           {
                  string += command;
           }

           delay(1);
    }

    if(string == "LO")
    {
           LEDOn();
     }

   if(string == "LF")
    {
           LEDOff();
    }

The problem comes when I type the commands. Normally, an LED in the board will react (I think it's the RX one), but the LED in pin 12 will not react at all. After testing ten times with each command alternatively, I calculated the serial needs an average of 6 command repetitions in order to react. Exactly the same happens when the HC-06 is connected.
Is there a reason for this?

Does the problem occur at higher BPS?  For example, try changing Serial.begin(9600); to Serial.begin(115200); (and change serial monitor BPS also).  Note, you should do string = ""; only in setup() and after processing :, LO, or LF, or something like that, since it perhaps could be loop() loops before getting a complete command

Please read and digest this, then re-write your code accordingly: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

@jwpat7 There's no response at all if I set a baudrate higher than 9600.

There is a problem with your code: Serial.available() > 0 might be false at your if test, but true at your while loop condition, which means that string has a chance of not being correctly initialized to "" before you start chaining characters to it. I would also add some sanity check on the input stream, because as it is now any failure is silent. When you exit the loop, either string == "LO" or string == "LF". If not, then you could print the content of string to Serial and see why the command was not taken. What's the point of delay(1)?

The baudrate needs to be changed both within the Arduino program and on the serial client you use on your pc, otherwise they can't talk to one another. I doubt that's the cause of it, though.

Another problem in your code is that whenever there is nothing to read on serial input, the Arduino keeps going through the loop and repeating the last instruction it received. You could look up how to put the Arduino to sleep while it waits to be awaken by more input on the Serial interface pins. As it is, you should at least reset string right after executing the command.

So how should I implement this to my code? I'm still new at programming Arduino.

I said that you could do something better, just to mention that it is possible, not that you should now. First fix those things in your code and see whether it solves the issue or not.

Your problem is, amongst other things, that you are assuming that all the serial data arrives at once, which doesn't necessarily happen at all.
I have a discussion about this sort of thing.
Rewriting your sketch using the ideas presented there we get this:
#define led 12

void LEDOn()
{
  digitalWrite(led, HIGH);
}

void LEDOff()
{
  digitalWrite(led, LOW);
}

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
{
  Serial.begin (9600);
  pinMode(led, OUTPUT);
} // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
{

  if (strcmp (data, "ON") == 0)
    LEDOn ();
  else if (strcmp (data, "OFF") == 0)
    LEDOff ();
  else
    {
    Serial.print (F("Unexpected command: "));
    Serial.println (data);
    }
}  // end of process_data

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

  switch (inByte)
  {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }  // end of switch

} // end of processIncomingByte

void loop()
{
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

}  // end of loop

with the commands "ON" and "OFF" respectively.

I changed the test to be for "ON" and "OFF" not "LO" and "LF" which seems a weird way of meeting your requirements.
For this to work you need a delimiter (which tells the Arduino when you have finished sending a command). I have used linefeed which you can automatically send in the IDE's serial monitor (see bottom RH corner).

I also put in code to show "Unexpected command: " if you don't get ON or OFF (note that "on" is not the same as "ON").

Nice! Now it works perfectly from the serial monitor. But if I wanted to send this command from an external device via Bluetooth (a smartphone, for example). how could I force the newline after the command? Using ON\n or ON"\n" does not return anything.

Sending "ON\n" should work. You could of course use a different delimiter. Instead of checking for \n in the code you could check for :.

It worked with ':'. Is there a reason why it's not working with '\n'?

No, not unless you didn't send "\n" properly.

It worked fine for me, if I typed the entire command, "LO:" or LF:" (without the quotes of course). However, if I typed and sent one character at a time, it failed. The problem is quite likely the code:

   if (Serial.available() > 0)
         {string = "";}

If you send all of the characters at once, the while( Serial.available() ) loop will get the whole line and match it. But if there is any pause between characters, what does that if statement do? (Hint: loop() executes way faster than you can type!)
I was using the serial terminal built into the Eclipse IDE. Different terminal software might behave differently when you type a string and send it. Remember, any gaps between characters, and that first if statement gets time to do its dirty work.


text:
Hardware logic gates for a simple demo with LEDs
I need some logic gates for a simple demo like this one. I will use a regular breadboard and an Arduino UNO as a 5 V and GND supply.
I found these ICs from Texas Instruments SN74LSxxN (NOT, AND, OR, NAND, NOR, XOR). For my demo I only need two inputs (well obviously only one on NOT) and one output on each chip. I want to connect the output to a LED via resistor to demonstrate that for example 1 XOR 1 equals 0 (LED off), or NOT 0 equals 1 (LED on):

My LSs seem to work as expected without an LED connected:

int value;

void setup() {
 pinMode(10, OUTPUT);
 pinMode(11, OUTPUT);
 Serial.begin(1200);
}

void loop() {
 digitalWrite(10, LOW);
 digitalWrite(11, LOW);
 value = digitalRead(5);
 Serial.println(value);
}

…but it would be great to make an LED demo too.
These ICs are probably a better choice in my case?

SN74ACT04N (NOT)
SN74ACT08N (AND)
SN74ACT32N (OR)
SN74ACT00N (NAND)
CD74ACT02 (NOR)
SN74ACT86N (XOR)

For everyone who isn't happy with Arduino as power supply here an alternative circuit with the same question - which IC family should I use?

Update: Well, probably I should better use something like LogicBlocks for my demo.
There is no NOR, XOR or NAND in this set, but it should be much easier to handle.

No, that is not OK. Those chips have ±4mA outputs at 5V. You are asking around 15mA (depending on LED forward voltage).

Majenko could you recommend some suitable ones?

GeMir, you can increase the resistor, say to 2K, and see if you have enough brightness.  Some high-brightness LEDs are ok with up to about 15K series resistance at 5V.  Note, see Ohm's law.   5V/200Ω = 25 mA, too much for typical 74HC outputs to source. [Actually, the calc. should be (5V-Vled)/200]   5V/4mA = 1250Ω, so a 2KΩ is ok.  Or you could add a buffer to drive LEDs.

@jwpat 1.8 kΩ carbon ones?

GeMir, those should work ok.  The current calc. for red LEDs at say 1.6V drop would be (5-1.6)/1800 = .00188, a little less than 2 mA.  You could go as low as about 1K; (5-1.6)/1000 = .0034.  With white LEDs at say 3.4V, (5-3.4)/1000 = .0016 = 1.6 mA and (5-3.4)/470 = .0034 = 3.4 mA.  Anyhow, you don't need anything except a meter, an LED, a resistor, and a 5V supply to test if LEDs are bright enough at low enough current.

@jwpat7 Should I better change the family? The ACT family outputs are ±20mA.

You cannot drive only one gate on each chip. The other floating inputs could cause power issues, so tie them to one of the rails.

@IgnacioVazquez-Abrams sure, I'll use only two inputs and all other ones will be connected to GND. Thank you.

GeMir, first run a test with a meter, an LED, a resistor, and a 5V supply to see how much LED current you actually need.  If you need more than 3 or 4 mA, you could change families or use a buffer.  For example, run a 74HCxx output through an SN74ACT245, or through 2 inverters on an SN74ACT04.  Note, if you are only making one of these demo units, the chip costs might not be a factor; if you are making several, the 74ACT parts probably will cost several times as much as 74HC parts.

A 1k resistor will let around 3 mA through an LED with a 2V forward voltage drop (from a 5V source). On a test here with a cheap LED it was quite visible when on. (5 - 2) / 1000 = 0.003. See LED calculator site

@NickGammon I found something very similar to the demo I want to make on YouTube (see the first post above).

Note: Lengthy series of posts by the OP on the same issue on the Arduino Forum.

The circuit I was looking for looks like this:

And the HC family seems to do the job. Thanks to dlloyd (link).

I gather you have decided to source 9.7 mA from the 74HC08N output driver. Since the device is specified to provide ±4 mA I'm just curious to know why you did that? You are running at 243% of its documented ability.

@NickGammon It was dlloyd's recommendation, I've got HC- and ACT-family chips and use ACTs now.

The SN74HC04 has a documented output driver capability of ±4 mA when running at 5V:

Assuming you are using red LEDs with a forward voltage of 1.6V (as I measured one of mine lying around on the bench to be), then to not exceed this you need to get a resistor of:
(5 - 1.6) / 0.004 = 850 Ω

A reasonable (and safer) value would be a standard 1k resistor, which you are likely to have lying around (and if not, get a few hundred of them). That would give you 3.4 mA current through the output pin, which is in range.

I found something very similar to my demo on YouTube ...

Yes, well, people on YouTube aren't always doing things exactly like they should. :)
See Mike Cook's tutorial The care and feeding of LEDs. As he points out, a lot of people use the wrong, or no, resistors because "it seems to work".
It may well seem to work for a while, but if you want a design that will last for a long time, you work within the manufacturer's specifications.
The problem with people disseminating wrong information is that someone will then copy it, and repeat it, and before long you find people saying "everyone does it this way".

Thank you very much for your time and explanations! Since SN stands for "Texas Instruments" and there is no SN74ACT02N (NOR), shouldn't I look for CD74ACT04, CD74ACT08 etc. (I prefer buying parts of same manufacturer)?

Ok, found it. CD means "CMOS digital logiс IC". These chips were made by Harris Semiconductor.


text:
How to execute commands on Arduino (via PC) without touching the current sketch?
I am working on my first Arduino project. It's a Reverse Geocache. Basically, it's a puzzle where a battery-powered Arduino is mounted inside a locked box, and is able to unlock the box if the user brings the box to the correct GPS coordinates and presses a push-button (that activates the Arduino, that runs a sketch, that checks the GPS, and operates a servo to release the lock).
It's all working, but I am trying to build in a backdoor, so I can unlock the box when I need to.
I have made the Arduino USB port accessible, and my hope is that I could connect a PC, and execute the appropriate command to operate the servo to unlock the box. The command is:
servo.write(OPEN_ANGLE);

The sketch that drives the whole puzzle depends on these libraries, but I am guessing the only one needed to operate the servo is PWMServo.h:
#include <PWMServo.h>
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <EEPROM.h>
#include <LiquidCrystal.h>

I would like to be able to operate the servo without altering/replacing the uploaded sketch.
Is it possible to execute code "command prompt" style? Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?
Finally (not the main question, but I would appreciate clarification), I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true). If forcing an unlock via the backdoor required uploading a new sketch, I seem to have a problem... For the puzzle to work within the locked box, the battery must be permanently connected, and also connecting to a PC via the USB seems to immediately power up the Arduino too. Does this mean uploading a new sketch would be impossible?

The simple thing would be for your sketch to read from the serial port continuously. If it finds something it stores it and when a newline arrives it sees if that happens to be a password known only to you. So, for example, all you would have to do is plug in the USB cable, activate the Serial Monitor on your PC, type swordfish and the servo opens the box.
You would need to allow for garbage arriving, so make sure that you discard input if it exceeds the size of the buffer you allocate for this purpose.

I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true).

I don't see how that can be true as you have to reapply power to upload the sketch. I never do that.

Is it possible to execute code "command prompt" style?

No, you upload compiled code.

Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Then all the person you give the box to has to notice the USB port, plug something in, and it unlocks. I think not.

An even simpler solution would be to have two locations that unlock the box. For example, your kitchen could be one, so to unlock it you just take the box to your kitchen. The other location would be the "real" one that you want your friend to have to find. All the stuff about "you are 200 km from your destination" would of course refer to the real destination. You just make the code check that if it happens to find itself in your kitchen it unlocks the box.


text:
Programming an ATmega328P by holding it on an Uno's
I was looking at this Uno clone, the Nanino and then happened to read this article on "Manhattan style" circuit design. Anyway, that got me thinking...
If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

No, the programming scheme on the Uno only works when there already is a bootloader in the chip, and would likely be confused by a second chip if it did have one.  There have been some rumors that certain other programming schemes might somewhat tolerate parallelism, but those are not what the Uno supports.

It's easy enough to use a Uno to program a bootloader onto another chip. I describe this process here.
The idea of holding one chip on top of another is likely to fail for various reasons. Both chips will try to respond to the programming attempt at slightly different times, probably making them both fail to be programmed.
See my post about making a breadboard Arduino. It only takes a few wires to program the target chip.

However this isn't just "paralleling the pins" - it is using one chip to program another, in the way it is designed to do.

If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

Well burning a bootloader(over a SPI communication) is quite different than simply uploading code(Serial communication), therefore it requires a specific setup which is an AVR-ISP.(In-System Programmer).
So you can't burn a bootloader by simply holding it over the other because of the Uno design.
The IC socket for the Atmega chip on the Uno board is not set for SPI communication so you can't burn a bootloader onto it directly. Instead, you'll have to do a similar setup to Nick Gammon's. Use one arduino as an ISP to burn the bootloader onto another.
Therefore placing the 'raw' chip in the socket and trying to burn the bootloader won't even work.
Note that in this setup, the Uno is communicating as an ISP and it uploads the code to the 'raw' Atmega328 chip. The chip on the Uno already has the bootloader(in fact it is configured/programmed to be an ISP).
Hope it helps!
Best of luck!


text:
Servo/Motor for barrier gate
I am working on a small project that will need to check for proper UPC's then if validated, lift a barrier gate to move along cardboard boxes. The Arduino comes in with the gate lifting. I have this barrier gate working with a very small servo that came included with the Arduino Starter Kit, but this could not hold the weight that might be pushing up against it with a longer arm. Has anyone had any experience with something like this or could someone direct of a power supply/servo combo that would be up to the task? These boxes could weigh up to 20 pounds.
Thanks!

You may find Robotics Stackexchange  useful for questions like this.

This is really not an Ardunio question.  Keep in mind also, that a system strong enough to do what you want is also potentially hazardous to people working on or around it, so you will probably end up needing to pay more attention to making it safe than you do to making it actually work.

You may purchase a servo motor with greater torque.
You may find both DC as well as AC servo's. If you are using it in a real industrial scenario I would suggest you to use the AC, as you may not have to convert the ac power to DC and these motors will need real high current. So it would be better if it works on the main voltage. I did find PANASONICs ac servo as google search result.
If you have problems with integrating the greater torque motor to your current system let me know i can help you out.

You could look at larger DC gearmotors such as automotive power window or power door motors and use limit switches for position sensing. To power this you would need a 12V power supply capable of at least 5 amps.


text:
Implementing AT commands with Arduino and ESP8266
Being a newbie to Arduino, I'm trying to implement AT commands in the serial monitor, though in vain. After connecting the ESP8266 (01) module to an Arduino Uno, I tried to scan for the nearest network present [code link: https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/scan-examples.md#simple-scan] and it worked perfectly.
But the moment I am trying to connect to send AT commands (even manually), it shows nothing. In addition, if(Serial.available()) and if(esp8266.available())< both are giving false value.
What am I doing wrong?

Show your code, since maybe the problem lies with Softserial + native serial

You don't give a circuit diagram or very much detail about what you've done, but if I guess correctly...
You have flashed the code in your link to the ESP-01 (perhaps using the Arduino as a serial port adapter). That code is now running on the ESP itself - it's not running on the Arduino and controlling the ESP.
Flashing the ESP erases the stock firmware, so the ESP can no longer respond to AT commands.
I don't know of a way to reprogram the 'AT' firmware into the ESP but perhaps Google will help.
If I've guessed incorrectly, please explain exactly what you have done - with circuit diagram, setup steps and code.

This is exactly what has happened. I reprogram the 'AT' firmware into the ESP then AT was working perfectly. The moment I tried to access ESP programmatically [sendData("AT+CWMODE=2\r\n",1000,DEBUG)] it again showed the same problem. I think Program Address Offset [Hex] value for firmware and my *.ino are same. I am trying another range with no result. Can you tell me how to change the Program Offset for Aurduino [0x000000]. Any able comment is solicited.

If my answer answers your original question, please feel free to accept it, and optionally up-vote it. That will encourage people to answer further questions. If you have a new question, please read http://stackoverflow.com/help/how-to-ask and ask a new question.

created a new thread, please assist there as well. [ref: http://arduino.stackexchange.com/questions/32899/esp8266-firmware-update-problem]

Anyone who is new to using ESP8266 module should consider following before interfacing it with Arduino

Try connecting ESP Module directly with your computer and test out all the AT Commands you will be implementing with Arduino. This approach is better because (a) this will give you confidence that your communication works perfectly (b) you will figure out all the problems that people face when sending AT commands and receive reply (c) this is a more visual approach so you will know what is going on and where you are going wrong.
Use Computer based communication tools and make a simple power adaptor to solve communication and wiring problems once and for all.

authors: الكترونيات صفوان


text:
UART from Arduino to NodeMCU
I'm trying to connect an Arduino nano to a NodeMCU 1.0 via the hardware UART, in order to send information one way from the Arduino to the NodeMCU (and from there to the network).  I'm connecting the Arduino TX to the NodeMCU RX via a reduction of voltage from 5V to 3.3V but I'm getting nothing read at the serial.  The connectivity part is tested, since if I connect the NodeMCU via USB and write something with the Serial monitor, the data appears on the server.
Is there anything missing from the code on either parts?
The circuit is connected as follows:

and the code that runs on the Arduino (as a test) simply sends a string over and over, but at a low rate

    void setup() {
      Serial.begin(115200);
      while (!Serial) delay(10);
      pinMode(LED_BUILTIN,OUTPUT);
    }
void loop() {
  digitalWrite(LED_BUILTIN,HIGH);
  delay(100);
  digitalWrite(LED_BUILTIN,LOW);
  delay(100);
  Serial.println("Hello");
}

The code that runs on the NodeMCU is as follows:
WiFiClient client;

void connect_to_wifi()
{
  WiFi.begin(ssid, password);
  int tries=0;
  for(tries=0;tries<20 && WiFi.status()!=WL_CONNECTED;++tries)
  {
    digitalWrite(D0,(tries&1)==1?HIGH:LOW);
    Serial.print(".");
    delay(500);
  }
  if (tries>=20)
  {
    status=0;
    Serial.println("Failed to connect to WiFi");
  }
  else
  {
    Serial.println("Connected to WiFi");
    if (client.connect(addr, port))
    {
      Serial.println("Connected to server");
      client.println("Connected");
    }
    else
    {
      Serial.println("Failed to connect to server");
      status=0;
    }
  }
}

void setup() {
  pinMode(D0,OUTPUT);
  digitalWrite(D0,LOW);
  Serial.begin(115200);
  while (!Serial) delay(10);
  connect_to_wifi();
}

void loop() {
  if (status==0)
  {
    digitalWrite(D0,HIGH);
    delay(300);
    digitalWrite(D0,LOW);
    delay(300);
  }
  else
  {
    digitalWrite(D0,HIGH);
    delay(100);
    digitalWrite(D0,LOW);
    delay(100);
    int av=Serial.available();
    if (av>0)
    {
      client.println(av);
      for(int i=0;i<av;++i)
      {
        int c=Serial.read();
        client.print(char(c));
      }
    }
  }
}

EDIT 1:
I connected a scope to see the serial signal and see only high.  I then disconnected the NodeMCU and see a valid signal coming out of the Arduino.
Then I moved the receiving part to D5 on the NodeMCU and used a version of SoftwareSerial for this board, which worked.
For some reason, the hardware Rx is pulled high no matter what.
I would prefer to use hardware Serial, but if no solution can be found, I guess I will have to do with Software.

Your schematic is showing 3 resistors and only 2 are needed to a 5v to 3.3v logic adapter. Could you provide more details about that interface ?

The hardware receive pin is probably being driven high by the node MCU's onboard USB-serial chip, and your voltage divider means the signal from the arduino will clearly loose that battle.  See if you can disable the USB serial chip, perhaps by holding it in reset, or if there's a way to cut the connection.  If you have the CH340 version try making R10 a lot bigger, or else maybe put a diode in your level shifter or switch to a MOSFET style level converter so that you can actively drive low.

The reason for the 3 resistors is to make a 2/3 divider using 3 identical resistors.   Regarding a level shifter, I have tried that before and it didn't help.   If there's nothing that can easily be done in software to remove the pullup on the Rx pin, I'll settle for soft serial on another pin.   Thanks for the suggestions.

What about using a optocoupler to handle the different voltage issue?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Port Manipulation and serial communication
i'm working on a laser timer using arduino and i saw that using direct port manipulation can have a really better time precision. My only concern is about serial communication, because i am using some pins for a software serial, and i don't know how to set them in the ports register. The pins are the 4 and 5, and the number 3 is the trigger output, unluckily this pinset cannot change. How should i set them in the DDRD? I'm using an Arduino Nano board

Don't. Just avoid touching them.

To manage a SoftwareSerial object different from the default Serial, take a look to the "Arduino - Software Serial Example". A possible setting could be SoftwareSerial mySerial(4, 5); // RX=4, TX=5.

A DIY attempt to revise the software serial libraries may not yield improvement - experienced programmers have already done that and published their versions, looking at those alternatives might be productive but reworking the implementation itself will require a fairly advanced understanding to end up with something functional, let alone better.  Also keep in mind that changing the direction of an I/O more efficiently is only a win if it happens often, which wouldn't be the case for an interface where RX and TX have distinct wires.

You can modify a single or multiple bits in a register by using a Read-Modify-Write approach. Essentially something like this:
byte temp = DDRD;
temp = (temp & ~(bitmask)) | bits_to_set;
DDRD = temp;

In the above code, bitmask is some value with the bit or bits you want to modify set - e.g. if you want to change bits 4 and 5, it would be (_BV(4) | _BV(5)) or just (0b00110000). bits_to_set is a value with all bits that you want to be one set - e.g. if you want bit 5 to be a 1, it would be (_BV(5)) or (0b00100000).
What the code does is to first get the current value of the register you want to manipulate. Then it will clear only the bits which you want to modify to 0 by using bitwise AND on the temp value. Next it will set only the bits you want to change to be set by using a bitwise OR. Finally it writes it back to the register.
If you are using interrupts which, you may wish to do this atomically (so that the register is not changed by an interrupt occurring before the new value is written back). You can do this by wrapping the above code in:
byte oldSREG = SREG;
cli();
...
SREG = oldSREG;

Which will clear the global interrupt flag to pause any interrupts, and then will restore the value of it afterwards.

If you just want to change a single bit in a register you can optimise this code down to one of the following examples:
DDRD |= _BV(4); //Set bit 4
DDRD &= ~_BV(5); //Clear bit 5

Again you may want to do this atomically as it may compile to a Read-Modify-Write access.


text:
Making an automated watering system with Arduino
I am trying to make an automated watering system using an Arduino.
Here is my wiring diagram:

And here is my circuit wired up:

Here is the code that I'm using with Arduino. The code seems alright and the wiring on the Arduino seems okay as well, but I don't know where to place a speaker on the Arduino. The biggest problem is that the program doesn't run like I coded. After I uploaded this code to Arduino, the water pump just keeps running forever. Can anyone check up my code to make this run properly?
/**automated watering program **/

#include <avr/sleep.h>
#include <avr/wdt.h>
#define BEAT 300 // define time for the tone.
#define PINNO 12

int led = 13;

void setup() {
  // setup code to run once:
  pinMode(led, OUTPUT);
}

void loop() {
  // main code here, to run repeatedly:
  tone(PINNO,262,BEAT); // C(do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,262,BEAT); // C (do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,392,BEAT); // G(so)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,262,BEAT); // C(do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  delay(1000); // Wait for 1 second
  digitalWrite(led,HIGH); //Make No. 11pin output HIGH = 5V
  delay(500); // Watering time
  digitalWrite(led,LOW); //Make No.11 pin output LOW = 0V
  // Shut down program to save battery using by watchdogtimer 24h standby mode
  int var = 0;
  while(var < 10800) {
    delayWDT(9); // 9seconds of shutdown
    var++; // 10800times repeat ＝24h
  }
}

void delayWDT(unsigned long t) {
  // delay excute while using powerdown mode
  delayWDT_setup(t); // watchdog timer setting
  ADCSRA &= ~(1 << ADEN); // ADEN bit clear and stop ADC
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Powerdow mode
  sleep_enable();
  sleep_mode(); // sleep mode
  sleep_disable(); // WatchDog Timer times up and start working again
  ADCSRA |= (1 << ADEN); // turn on the ADC
}

void delayWDT_setup(unsigned int ii) {
  // setting up timer
  // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
  // 6=1sec, 7=2sec, 8=4sec, 9=8sec
  byte bb;
  if (ii > 9 ) {
    // get rid of strange numbers
    ii = 9;
  }
  bb =ii & 7;
  if (ii > 7) {
    bb |= (1 << 5);
  }
  bb |= ( 1 << WDCE );
  MCUSR &= ~(1 << WDRF); // MCU Status Reg. Watchdog Reset  Flag ->0
  // start timed sequence
  WDTCSR |= (1 << WDCE) | (1<<WDE); // allow to edit watchdog
  // set new watchdog timeout value
  WDTCSR = bb;
  WDTCSR |= _BV(WDIE);
}
ISR(WDT_vect) {
  // the work after time up, WDT
  //  wdt_cycle++;
}

Maybe if you try controlling pin 11, where the pump is connected, and not pin 13, it may help. Also I can't understand your wiring there (but it looks wrong - there are components missing). Please provide a schematic (which you can do using the schematic editor available when you edit your question).

As for where to place a speaker - how about pin 12, like you have already decided in your code?

Thank you, I uploaded a diagram i wire them exactly like the diagram.

What model transistor is that?

it says BC5478, It came with Arduino Starter Kit.

also it was not speaker, it was Piezo. I don't know where to place it.

I'm missing a resistor between the arduino and the transistor. Also missing a (flyback) diode on the motor.

Problems with your setup:

Your pump is connected to pin 11 but you are controlling pin 13 (int led = 13;)
You have an LED in line with your transistor base. That should be a resistor, and the LED should be in parallel with the base (with its own resistor).
Your transistor is wired wrong. According to the datasheet the pins are C-B-E as viewed from the angle in your wiring diagram. You have the Arduino connected to E instead of B, the pump connected to B instead of C, and ground connected to C instead of E.
You don't have a flyback diode across the motor.

simulate this circuit – Schematic created using CircuitLab

Why does it need the resistors ??

i tired this but didnt work

this time, speaker worked but the pump didnt work

authors: Олтиной Божаева


text:
Couldn't connect to local server using Ethernet Shield and Arduino Mega 2560
I'm trying to connect the arduino mega and ethernet shield and try to send some data to a php script. I have connect the ethernet shield to the laptop. Lap is connected to router through wi-fi. Any help in advance please.
#include <SPI.h>
#include <Ethernet.h>

/******************** ETHERNET SETTINGS ********************/

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD9 };   //physical mac address
byte ip[] = { 192, 168, 1, 5 };                   // ip in lan
byte subnet[] = { 255, 255, 255, 0 };              //subnet mask
byte gateway[] = { 192, 168, 0, 1 };              // default gateway

IPAddress server(192,168,1,2);
EthernetClient client;

void setup() {
    Serial.begin(9600);  // Initialize serial communications with the PC
    while (!Serial);     // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    Ethernet.begin(mac,ip,gateway,subnet);     // initialize Ethernet device
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
      Serial.print(Ethernet.localIP()[thisByte], DEC);
      Serial.print(".");
    }
    Serial.println();
    Serial.println("connecting....");
}

void loop()
{
  if (client.connect(server,1234)) { // REPLACE WITH YOUR SERVER ADDRESS
    Serial.println("Server connection OK");
    client.println("GET /add.php?temp1=10&hum1=20 HTTP/1.1");
    client.println("Host:" + server);// SERVER ADDRESS HERE TOO
    client.println("Content-Type: text/plain");
  } else {
    Serial.println("connection failure");
  }

  if (client.connected()) {
    client.stop();// DISCONNECT FROM THE SERVER
    Serial.println("disconnected");
  }

  delay(5000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

Serial Out Put
My IP address: 192.168.1.5.
connecting....
connection failure
connection failure
connection failure
connection failure
connection failure
connection failure
connection failure

and one more thing to add, I create a server on the shield instead of the client. It's working fine, I checked the IP and port using the laptop browser and I can connect to the server. Shield's client is the issue...

I had this problem for quite a long time and then I did a little bit of research!
Here it is in an easy explanation-
When you connect your Ethernet Shield to the Laptop the laptop takes the Ethernet Shield as a source of internet and tries to get an IP Address and other network stuff FROM the shield! BUT what we want is the other way round.
We want the Ethernet shield to take the laptop as a source of internet and get itself an IP assigned by the laptop!
What I do is I make a Laptop-Ethernet Shield network and a Laptop-WiFi network.(Simply means that I connect my laptop to WiFi and Ethernet shield)
Then I JOIN the two networks!
This joining of networks is called network bridging and is done easily, I'll tell you how-
If you're using linux then follow this link here.
else if you're running windows-
1) Connect your Ethernet Shield (With Arduino attached obviously) to the laptop and make sure that your laptop is connected to the WiFi.
2) Go to Network and Sharing Center.
3) Go to Change adapter settings.
4) Select your Wifi adapter and the Ethernet adapter together.
5) Right click on any of the selected adapter and click Bridge connections.
6) Wait till a new network bridge is connected and is done verifying after it's creation.
7) Upload the sketch again on Arduino and you'd be connected.
NOTE
DHCP may not always work as it's a feature of your router/WiFi and not your laptop so try assigning a mannual IP by calling Ethernet.begin(mac,ip) instead of using DHCP by caling Ethernet.begin(mc);
AND do change your ip to 192.168.1.XXX I mean change the last tuple so it does not clash with the ip of any other device.(XXX any number less than 255, generally 100-200)
Do let me know the outcome after trying this out! :D

I did as you pointed, then it created a  new connection with wifi and ethernet, but stii I can't connect.
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD9 };   //physical mac address
byte ip[] = { 192, 168, 1, 5 };                   // ip in lan
Ethernet.begin(mac,ip);     // initialize Ethernet device

and one more thing to add, I create a server on the shield instead of the client. It's working fine, I checked the IP and port using the laptop browser and I can connect to the server. Shield's client is the issue...

Hi @Manav, now it's working.. I check the apache access log and the request is there, but it's returning 400 - bad request ?
`data = "temp1=10&hum1=20";
client.println("POST /add.php HTTP/1.1");
client.println("Host: " + server); // SERVER ADDRESS HERE TOO
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(data.length());
client.println();
client.print(data);'

192.168.1.120 - - [31/Dec/2016:10:19:52 +0530] "POST /add.php HTTP/1.1" 400 472 "-" "-" 192.168.1.120 - - [31/Dec/2016:10:19:57 +0530] "POST /add.php HTTP/1.1" 400 472 "-" "-"

changing following line worked 'client.println("Host: localhost");' tnx for all the support

Hahaha you're welcome  The key here was network bridging

First your network config is wrong. The gateway is outside the scope of your netmask. This is invalid and may fail the tcpip stack depending on how the Arduino library is implemented.
Second, once you fix this, your laptop needs to be configured as a router to access resources on your network resources unless 192.168.1.2 is the laptop you are connected to.

1)then what is a correct gateway?
2)192.168.1.2 is the laptop

and one more thing to add, I create a server on the shield instead of the client. It's working fine, I checked the IP and port using the laptop browser and I can connect to the server. Shield's client is the issue...

I would say that you need to set the gateway to the IP of the laptop (i.e. 192.168.1.2) in this kind of setup.
So with IP 192.168.1.5/255.255.255.0 with gateway of 192.168.1.2, anything in the range 192.168.1.XXX will be local. If the arduino tried to access anything outside of 192.168.1.XXX then it will be routed through the gateway IP to then routed through the proper route.


text:
ATtiny85 AC Phase Control for dimming a light bulb
I'm trying to dim a light bulb via an ATtiny85, which accepts commands sent over I2C. My problem is that the bulb is barely dimming and is flickering quite a bit.
My circuit can be seen here:

The opto-isolator (and thus the triac) is controlled via pin 2 (AKA PB3, AKA PCINT3) and AC zero cross detection is done on pin 3 (AKA PB4, AKA PCINT4) on the ATtiny85.
The code uses Pin Change Interrupt Enable rather than the single External Interrupt Enable, because the External Interrupt pin is pin 7 (aka PB2), which is used as the SCL for the I2C communication.
The 8MHz internal clock is used and the timer/counter prescaler is 1024, which means that I have an effective input range (see level variable in the code) of roughly 0-65. My AC source is USA (60Hz).
#include <avr/interrupt.h>
#include <avr/io.h>
#include <TinyWireS.h>

#define PULSE 4       //trigger pulse width (counts)
#define I2C_SLAVE_ADDR 0x4 // the 7-bit address (remember to change this when adapting this example)

byte trigger = 3;
byte detector = 4;
byte level = 50;
byte maxLevel = 65;
byte minLevel = 0;

void setup() {
    TinyWireS.begin(I2C_SLAVE_ADDR); // join i2c network
    TinyWireS.onRequest(requestEvent); //setup i2c requester
    digitalWrite(detector, HIGH);  //enable pull-up resistor
    pinMode(trigger, OUTPUT);// Set AC Load pin as output
    TCCR1 = 0;     //stop timer
    OCR1A = level;    //initialize the comparator
    TIMSK = _BV(OCIE1A) | _BV(TOIE1); //interrupt on Compare Match A and  enable timer overflow interrupt
    GIMSK = 0b00100000; //Enable pin change interrupt
    PCMSK = 0b00010000; //PB4, physical pin 3 PCINT4
    TCCR1 = B00001011; //Prescale the timer
    sei();  // Turn on interrupts
}

ISR(PCINT0_vect) {
    //interrupt looking for zero crossing
    TCNT1 = 0;   //reset timer - count from zero
    OCR1A = level;
    TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
}
ISR(TIMER1_COMPA_vect) {
    //comparator match
    digitalWrite(trigger,HIGH); //set triac gate to high
    TCNT1 = 255-PULSE;
    //trigger pulse width for a few cycles for triac to latch on. 255 bc the counter can only count up to 255
}

ISR(TIMER1_OVF_vect) {
    //timer1 overflow
    digitalWrite(trigger, LOW); //turn off triac gate
    TCCR1 = 0;  //disable timer stop unintended triggers
}

void loop() {}

void requestEvent() {
    if (TinyWireS.available()) {
        level = TinyWireS.receive();
        if (level > maxLevel) {
            level = maxLevel;
         else if (level < minLevel){
            level = minLevel;
        }
    }
    TinyWireS.send(OCR1A);
}

I have tried a variety of bulbs (incandescent and dimmable LED), with none working any better than another.
Here is a video showing the zero cross detection (yellow) and the ATtiny85 trigger (blue) on an oscilloscope as I send it different dimming levels Bad phone video
I've thought about the snubber, I just don't have the parts on hand right now. I think it will help but I don't think it will correct whatever my larger issue is.
I'd appreciate all and any help. Thanks.
(Note: I also posted this here. Apologies if crossposting is frowned upon).

Are you able to turn the bulb off? Maybe the signal needs to be inverted. The triac circuit looks very minimal to me, but I'm not that into triacs.

Sending the max level does turn it off... But I don't know if it actually doing it the way I want it to.
Hmm What do you mean the signal needs to be inverted?
I was inspired by this

I meant a normally high signal with a short LOW pulse. So the blue trace upside down. But I'm just guessing here.

Are you sure about 47k R1 to the optotriac? Trigger current is 15mA for the MOC3021 and you have less than 0.1mA (with 5V power supply)

It's 0.47K. Poor picture quality . And using a 330ohm doesn't fix anything.

@thread9000 well, it should be about 220R on 5V. It's better to measure it.

Thanks @KIIV  but it still doesn't change the result. Any other thoughts?

This is really an electronics question not an Arduino one, especially as you are configuring the ATtiny hardware directly and not really going through the Arduino framework in more than the most trivial sense.  The snubber situation really can't be ignored.  Ultimately what you need to see is the behavior of the triac, but trying to measure that with a scope has too many dangerous pitfalls to recommend.  Are you sure you need to build this yourself?  It can be done, but it's not something to play with unless you really understand what is going on and how to do it safely.

@Gerben the circuit appears to be driving the Anode of the opto-triac device, so it would be an active high pulse to turn on the triac.   A typical dimmer like this achieves PWM by delaying some time after zero crossing before turning on the TRIAC, which will then remain on (regardless of input) until it shuts itself off at the next zero crossing.

Hi @ChrisStratton. The reason I am posting it here was to verify my code, which is very much using the Arduino API. Any electrical help and verification is a bonus, so I appreciate your input.
I'm currently waiting on a triac with a built-in snubber to be delivered.
I agree it would be nice to see out triac's output. I will reach out to an electrical engineer that I work with.

So I think there were (was?) two issues.
1) Pin change interrupts on the Attiny85 are triggered on rising and falling edges which I think was causing the flickering.
I changed the code to rising edge only triggering:
ISR(PCINT0_vect){ //interrupt looking for zero crossing
        if (digitalRead(4) == HIGH){
                TCNT1 = 0;   //reset timer - count from zero
                OCR1A = level;
                TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
       }
}

2) Attiny85 #reset pin. Pulled that guy high with a resistor.
Anyways, here's the oscilloscope and dimming led blub video: youtube

Also, I switched to BTB08-600BWRG for the triac which helps with inductance (so far I've got five (65watt eq) LED light bulbs running just fine). (Note this didn't actually do anything the solve the original problem)


text:
Fatal Exception Error on ESP8266 + Arduino
When I was trying to blink an LED using ESP8266, I had an issue with it. After successfully uploaded the code (https://diyhacking.com/esp8266-tutorial/), the blue LED stayed on & when I opened the serial monitor using Arduino IDE 1.6.12, I only saw "Fatal Exception" error (showed in the picture). I couldn't see how the code works and the worst thing was I couldn't even try the AT command.
The connections:
Arduino <--->   ESP8266 (ESP-07)
Tx  <--->   Tx
Rx  <--->   Rx
GND <--->   GPIO0
GND <--->   GND
3.3v<--->   CH_PD
3.3v<--->   VCC
            GPIO2 -> LED

I have been trying to troubleshoot this issue but haven't got the solution yet. I am afraid there is an issue with the firmware or the worst situation, I spoiled my ESP8266.

GPIO_0 is connected to GND only while programming/uploading code; for normal operation it should be (at least initially) connected to VCC(3.3v).
I believe the same goes for GPIO_02.
Try connecting them both to VCC and then connect GPIO_2 to the LED.

don't forget to add a resistor for your LED :)
220 should be more than enough.

I have tried your solution yet the result is still the same. perhaps I am just going to get the new one

Looking at your serial monitor window it shows "Geuino Uno". I think you forgot to change the target of the compiler to "Generic ESP8266" like shown in the how-to and you probably uploaded bad code to your module.

I used the correct board "Generic ESP8266"

If you are getting fatal error exception like this:
Exception (3):
epc1=0x401003e9 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4000cbd9 depc=0x00000000

In infinite loop in your Serial Monitor of the Arduino IDE then go to this link, download the software, and follow the procedure and erase the flash memory to solve the error.
This does not solve fatal error that occurs due to your program but in case your device goes in such condition that it can't be able to access program memory then it will work and try at least one time to solve the problem.
This is the procedure to hard reset the NodeMCU (https://www.youtube.com/watch?v=MHrm7axsImI&t=146s):

Install latest Python version in your PC. (https://www.python.org/downloads)
Open cmd prompt as administrator.
Go to C:\Program Files or C:\Program Files (x86)->python (your version)->Script. For this type cd c:\Program Files (x86)\python(your version)\Script then press enter.
Type pip install esptool.
Download ESPlorer.zip (v 0.2.0-rc6) from https://esp8266.ru/esplorer
Extract the downloaded file.
Open the executable jar file.
Go to NodeMcu firmware site (https://github.com/nodemcu/nodemcu-firmware/releases) and download file (nodemcu_float_0.9.6-dev_20150704.bin) and copy this file into the C:\Program Files (x86)/python(your version)/Script folder.
Now in cmd prompt just type:
esptool.py --port COM(your port no.) --baud 115200 erase_flash

And press enter.

Note: you can see your NodeMCU board's port number in Device Manager .


text:
clear Arduino as a global variable in Matlab
I'm trying to use Arduino in Matlab. cause I used Arduino in some function I had to define Arduino as a global variable.
clc,clear,close all;
global a
a = arduino();
.
some functions
.
clear a

at the end of my code I clear the variable but as I run the code again this error appear:
Failed to open serial port (user COM) to communicate with board Uno. ...
 Make sure there is no other MATLAB arduino object for this board.

I guess the global function can't be clear by clear command so I tried clear all instead clear in the last line. It works perfect as I run it again and again but as you know this is Matlab tips for clear all command
Using clear all causes MATLAB® to recompile previously cached code,
and can decrease performance.

I've tried delete(a) so the result was:
Error using arduino/delete
Cannot access method 'delete' in class 'arduino'.

any help would be appreciated.

What does contain the global variable a = arduino(); ?

cause it's recall in all sub functions. like writePWMDutyCycle(a,E1, 0);

sub functions use local value by default and save in separated location in matlab. one way is use a as an input argument for all of function. but i'm looking for another solution.

In the MatLab Help Center they had nice description of how to clear a variable from memory. Check it here: https://www.mathworks.com/help/matlab/ref/clearvars.html
In your case should be: clearvars -global a;


text:
Best way to power an Arduino using the Vin pin
I have a powerbank rated 5v. The battery is actually 3.6v, powering the built-in SMPS to give out 5v. I have stripped one end of the USB cable coming from the power bank, powering a motor driver and the Arduino in parallel. The positive end of the power bank, which is 5v, is going into the Arduino and the motor driver IC's Vcc.
I heard that 5v is not enough to drive the Arduino from the Vin pin. And there is only one power out from the powerbank, so directly connecting the Arduino through the USB would leave nothing to drive the motor driver IC.
A USB splitter would be the obvious solution, but is there anything else I can do? The power source has to be mobile. Can I power the Arduino through the Vin with those 9v batteries commonly used in electronics hobby projects?

"I heard that 5v is not enough to drive the arduino from the Vin pin." Where did you hear that?

from another answer on stackexchange.someone quoted from the arduino website that Vin requires 7v to 12v

You want to be careful, depending on the model Arduino has a voltage regulator or hasn't. I can never remember what the exact pin names are ... But one that comes with a voltage regulator also has a pin for 5V ... or 3V3 ... You really want to read the documentation that comes with your exact model.

Its a uno. Yes there is a volatge regulator and yes 3v and 5v pins are also there. So are you saying I should power the arduino through the 5v pin and not the Vin? Isn't the 5v pin meant to draw power and not feed power into the arduino??

Read the data sheet for the arduino, don't expect others to wipe your bottom and smile with a perfect answer for you. Do some research. Dig a bit deeper. Questions like this are quite often closed when talking about uses of "electronic devices". Questions like this are often closed due to lack of research on the questioner's part also.

Can't recall the first one to come up with the sentence: Arduino is the brains, not a power plant.

@Andyaka How do you know I haven't done any research.I have seen you in many answers in Andy.Although your knowledge base is poor you are very good at insulting people

@Andyaka You are always on the hunt for easy questions.And whenever after reading a question you find that you don't know the answer you just write something insulting to protect your ego.Learn to accept defeat.

What it wrong with connecting it straight to the 5v pin? Even better, why not connect to the, say, usb port on the arduino? Just connect it to the usb port, and connect the motor to the 5v pin of the arduino.

@Jippie - you are simply wrong here.  The Vin pin is the input to the regulator, something the poster was well and accurately aware of before you wasted a bunch of comments disputing that.  Frankly they are quite justified in being annoyed by your behavior!

The solutions can be 1) plug the arduino USB cable and then use the +5V pin to power the motor (if the motor needs a low current, since you can source at most 400-450mA this way) 2) power the arduino from the +5V pin (and put a capacitor on it, but note that you are bypassing the fuse this way) 3) strip a USB cable, attach the motor to the two power wires and make a Y cable yourself.

You have a powerbank which has a USB output, right? Why not just plug a cable from that into the Arduino USB port? That will connect the 5V directly into the 5V pin of the Arduino (probably via a switching MOSFET). Then you can connect to your motor driver from the 5V pin on the Arduino (and Gnd of course). There may be some limitations on how large a motor you can drive (based on the capacity of the power bank, and to an extent also the thickness of the traces on the Arduino board).
As others have commented, Vin is not intended for that purpose (ie. to supply 5V). You should supply 7V or more to Vin to force the switching MOSFET to disconnect the USB input. In your case you don't have 7V from the powerbank.

Here is how the Uno Rev3 power system works:

The input jack (circled in blue) goes through a diode (D1) to the Vin line.
Vin then goes through the 5V voltage regulator (U1) to provide +5V.
However on the top left you see 2 x 10K resistors (RN1A and RN1B) which make a voltage divider from Vin to Gnd. This is compared to the output of the 3.3V voltage regulator by U5A op-amp (circled in red). If higher, then T1 (circled in green) will turn off, disconnecting USBVCC from the +5V line. If lower, then USBVCC is connected to +5V. The nett effect is that if Vin in greater than 6.6V (because of the voltage divider) then the circuit chooses to use Vin, otherwises it uses USBVCC (USB power).
That's why they recommend to use 7V or more into Vin.
Note that you lose around 0.7V through the diode, which is why you need something like 7.3V at the input jack to allow for the loss of the 0.7V before the op-amp compares it to 6.6V.

the loads on the motor driver are too heavy to be powered from the arduino.

What are those loads (in mA)? The powerbank might not be able to provide it either.

about 1 amp each,2 motors.although the power bank may not be able to fulfil the required power but  the powerbank's smps will protect the battery...on the other hand if i do the same with the 5v arduino pin it will straight away damage it (from drawing too much current)..am I right?

I had this problem last year when I needed to power a prototype using a LiPo battery which supplies only 3,2 up to 3,7V (and up to 4,2V when charging).
My way of solving the problem was to use a voltage boost module. Boost circuits are a kind of circuit where you the inertial properties of passive components to elevate (or attenuate) DC voltage levels.
But you don't need to worry about the math behind use, there is modules like the MT3608 which will supply your circuit up to 28V starting from as little 2V, check the datasheet.

That is true, you can't power the Arduino with 5V from VIn.
If you have a constant 5V and you are confident that no major spikes are going to happen, then you might as well connect it to the Arduino's 5V pin.
Other wise, you need at least 7V power the Arduino from the VIn pin. Some say you can put in 6V, but that is just from test. The 7V is more reliable. Thus, you can power the Arduino with a 9V battery is you wish.


text:
DFPlayer library using RT TX pins
I am using the DFRobotDFPlayerMini-1.0.1 library by Angelo. I am trying to use the actual RX TX pins on a Uno R3, but it doesn't connect unless I type in an alternate digital pin number. This is no good for my application as I have a major pin shortage. I have tried typing in (0,1) but that is not being accepted.
The reason for using this library is because it provides a LOOP function that works well.

How do I use the RX TX pins with this library?
Is there another library that has a good LOOP function in it?

Thanks.
Doug

Guys....I haven't posted code as this is a question more about Library function. thanks

On a classic Arduino pins 0 and 1 are used for serial communication with the host PC, so you cannot use them to talk to a peripheral without conflicting with that.  The library may well be coded to trap and reject such an attempt.
On various alternate (ARM, Atmega32u4, etc) boards these pins may be usable, though the library may not be aware of that.  Also on such boards you would generally want to use an available hardware UART rather than a software simulation of one, which may be fairly ATmega-specific anyway - the end result of which is that library code may well need modification to work on a non-traditional device.

Thanks Chris.....Yep...that seems to be the reason..the PWM usage is in conflict. I am working on an alternative using the DFPlayer 0nly...I will post final results in a couple of days hopefully.

PWM does not seem to have any role in the issue.  The output of the DFPlayer may be PWM, but that doesn't touch the Arduino - the issue is with the Arduino's serial command communication to it.

Sorry Chris...Long Night and wrong post...the question is how do i get to use the RX TX pins on a UNO R3 with this Library....however You have answered the other question that I had.

You simply can't use them, unless you give up the connection to the PC.  If you do that, you should re-write the library to use hardware serial.

Chris..this may be what the default :- software serial library is doing as it works on the RX TX pins      #include <softwareserial.h>
#include <dfplayer_mini_mp3.h>   I have found several instances of this , example link   http://stonez56.blogspot.com.au/2015/03/arduino-dfplayer-mini-mp3-module.html    but the problem is how do i LOOP with this library as that function is not well documented??? thanks

When you say "type in (0, 1)" I suppose you mean this:
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;

Reference
You cannot use (0, 1) in SoftwareSerial. However, what you could do is pass Serial to the init string:
void setup() {
  // mySoftwareSerial.begin(9600);
  Serial.begin(9600);
  // if (!myDFPlayer.begin(mySoftwareSerial)) {
  if (!myDFPlayer.begin(Serial)) {
    //Use softwareSerial to communicate with mp3.
  }

However that means you cannot use Serial for debugging. You'll have to find another way to log errors and messages.

OK ...with library I have to select digital pins, thats just the way it is built. no options. thanks for the comments...closed

D0, D1 are digital pins. The problem is not there. See my answer.

That true and i did try that but the library didn't like it..however with some round about coding i am now able to get an acceptable result for my project...thanks for the input.


text:
Convert ASCII output to human readable form and assign to a variable
I'm reading the RFID output and I can print it to the serial monitor as human readable. But what I want is to assign that to a variable. But I'm getting the ASCII. Is there any way to convert it and get to the variable like Serial.write() do.
byte readbackblock[19];

for (int j=0 ; j<16 ; j++)//print the block contents
    {
      Serial.write (readbackblock[j]);
      cardNumber += readbackblock[j];
    }

Serial.print(cardNumber);

Serial output
read block: 1234567890123456

49505152535455565748495051525354

Any help please.

What do you mean "assign that to a variable"? It is in a variable already or you wouldn't be able to print it. It looks like the variable is called readbackblock.

I want to convert this ASCII 49505152535455565748495051525354 number to this 1234567890123456. I can do that on the Serial.write(), but what I wan't is to send the output to some other without printing on the Serial.

@Majenko thank you very much, that did the trick :) (Y)

I don't think it is possible.
The Arduino is 8-bit microcontroller, and can't handle integers larger than 32-bit. The maximum value for a unsigned 32-bit integer is 4294967296. This is a smaller number than your readblock, so it wil never fit.
If you want to do this with smaller numbers, you can use these 2 function:

atoi -> convert char array to integer
atol -> convert char array to long integer

Can't handle is a bit of a long bow to draw. I have a sketch here that calculates 3^160 = 21847450052839212624230656502990235142567050104912751880812823948662932355201 - now that's quite a big number. The issue isn't the size of the number.

The issue isn't how to "assign to a variable". The issue is something else. Perhaps the question could be clarified?

I want to convert this ASCII 49505152535455565748495051525354 number to this 1234567890123456. I can do that on the Serial.write(), but what I wan't is to send the output to some other without printing on the Serial