text:
Arduino Serial library (Synchronous or Asynchronous?)
On an Arduino 101, I have this code running:
void setup()
{
 pinMode(2, INPUT);
 Serial.begin(9600);
}

int counter = 0;

void loop()
{
 Serial.print(millis()/1000);
 Serial.print("\t");
 Serial.print(counter);
 Serial.print("\t");
 Serial.println(digitalRead(2));
 counter++;
}

A wire can be used to jump Pin2 between 3.3V and GND.
When running with the Serial Monitor on, I see the values increment at a rate where counter increases by the hundreds very quickly and steadily ticks through the thousands over time.
If I close Serial Monitor momentarily and re-open it, I notice that this counter value has increased dramatically (by the tens-of-thousands).  Another sign of this is when starting the program and waiting a moment to start the Serial Monitor.  As the Arduino 101 does not restart when the Serial Monitor is opened, I see a large initial value in the tens of thousands despite having just started the program.
My question is this: is the Serial library operating synchronously or asynchronously? I was led to believe that it was asynchronous; however, if that was the case, why should the Arduino execute any slower when the serial monitor is on?
While I understand that increasing baud rate will increase the speed at which counter increases, I still see the same dramatic increase in this code when the monitor is closed and then re-opened.
Another possibility I thought of was that maybe counter was being stored in a buffer and what I was seeing was not an up-to-date time or count.  To check this, the program prints the digitalRead value of pin2 as I swap the jumper between 3.3v and GND. This change in value was reflected instantaneously on the Serial Monitor, and I believe this means I am not seeing past data slowly being printed out to the monitor.
One last attempt at understanding what was going on was executing this code:
void setup()
{
 pinMode(2, INPUT);
 Serial.begin(9600);
}

int counter = 0;

void loop()
{
counter++;
if (counter%1000==0)
 {
  Serial.println(counter);
 }

In this example, counter can be seen ticking through quite fast, by the hundreds of thousands, which indicates that the program is capable of running very quickly until a print statement is made. The effect is notably less when baud rate is increased to something like 115200 but is that saying that baud rate is literally slowing the processing speed of the controller?
Any kind of explanation as to what exactly is going on would be very appreciated.
Thank You for your Time.
Source of Arduino being supposedly Asynchronous:
https://itp.nyu.edu/physcomp/lessons/serial-communication/serial-communication-the-basics/

The Arduno 101 doesn't communicate to the PC using a UART. It uses CDC/ACM over USB, which looks like a UART to the PC.  But it isn't.

USB sends packets of data, not individual characters
It only sends if there is something to receive it at the other end
There is no such thing as baud rate with USB.

Basically, when the CDC/ACM port has been opened by an application (e.g., the serial monitor) the Arduino 101 starts to send the data down the line. When the port is closed all data to be sent gets silently dropped by the Arduino since there is nowhere to send it to.
Hence when the port is closed it runs much faster since the data that would normally have to be packed into packets and sent down USB isn't. It's just thrown away.

To address your confusion:
You are misunderstanding the concept of synchronous and asynchronous with regards to serial. There are basically two types of serial communication: Asynchronous, where both ends have to (pretty precisely) agree on the speed of communication (baud rate), and synchronous, where one end tells the other end what the speed is by providing a discrete clock signal. UART (RS-232, RS-485, etc) is asynchronous. It sends at a specific rate and has to rigidly stick to that rate for the other end to be able to receive it properly.  SPI and I2C are synchronous - they both (as master) provide a clock signal to the receiving end (slave) and the receiver synchronises its reading and writing of data with that clock signal (hence synchronous).
You are confusing those concepts with another meaning of synchronous and asynchronous - terms that could better be used would be parallel and sequential processing. If something happens in parallel then two (or more) things happen at once. This is the case of the hardware UART where you submit characters to be sent to the buffer and they get transmitted out by the hardware separately to the sketch - in parallel. Sequential would mean that one thing has to happen after the other. If the UART behaved like that your program would stall every time you wanted to send a single character.
So UART processing happens in the background, in parallel to your sketch. So does USB data processing for CDC/ACM. These things are generally coupled with interrupts to allow the CPU to handle tasks such as placing more data in the buffer or storing data that has arrived somewhere that you can get to it.  Interrupts aren't strictly parallel, in that they do stall your program while they run, but they are kind of in a different thread, or context. So they appear to be parallel.

Your explanation of the CDC/ACM being the cause makes alot of sense but from what I'm seeing, adjusting the baud rate in the program makes quite a difference in the rate at which information is displayed.  Do you have any explanation as to why this has an effect? Are the packets simply being filled with more information before they're sent at some other rate?

Maybe the 101 is doing some artificial throttling to make it seem like the baud rate is real. Who knows? Baud rate is meaningless (normally) though since the USB runs at a constant rate. The baud rate setting is only (normally) used to configure whatever device is at the end of the USB connection - e.g., if the data is being forwarded on to a real UART output it would configure that UART output for the requested baud rate.

The Universal asynchronous receiver/transmitter (UART) is a chip that control the actual wires for serial communication. The UART operates independently and asynchronously.
As far as I know the UART (or USART) has a buffer, and the serial.print* functions will write to this buffer, and if it is full will block until the buffer has room. The UART will consume the buffer and transmit it over the wire. So your code will run full speed until the buffer is full then it will have to wait for the UART to make space.

... but is that saying that baud rate is literally slowing the processing speed of the controller?

When the UART's buffer becomes full, the Serial API has no choice but to wait for the buffer to empty so it can fill it again. This makes it appear as if the code is running synchronously; waiting on the buffer is essentially acting as a synchronization device. So yes a slow baud rate can slow the micro-controller down since the code is forced to wait for the UART even though it is asynchronous!
You may not notice any of the above effects, since even 9600, a relatively slow rate, is much faster than humans can read. 300 baud is approximately the rate at which humans can read comfortlably. If you repeat your experiments with a higher baud rate you should see the text fly past on the serial monitor much faster than at 9600; if you lower the speed to 300 (the lowest supported by the library) you should be able to read along, and see that things do go slower. The buffer on the UART is rather small, and even when slowing down to 300 baud, it might be difficult to see the buffering behavior.
When the serial monitor is closed the serial communications are still happening, the UART on the receiving side is receiving the data, but it gets dropped on the floor since no one is reading it. If you were to disconnect the serial wires at some point this should stall the sending UART which should cause the serial.print* functions to block (alternatively the UART could be configured to drop the data if it can't physically transmit it over the wire.)

I went ahead and tried setting baud rate to 300 as you suggested.  It is more than easily legible; however, I still find that moving between 3.3V and GND, the change is instantaneous. With that being said, I do agree that baud rate does seem to affect the rate at which the microcontroller runs as counter's increase is dramatically slowed. So in short, I don't think there's a buffer being filled and drained but instead maybe the baud rate effects the timing for how long the Arduino waits while in the Serial.print() statement.


text:
nRF24L01+ packet loss caused by Arduino reading and communicating with sensors
I have 2 Arduinos communicating with each other. My problem is that one sends packets every 1.5-2 seconds but the other Arduino does sensor reading and data uploading with a Wifi module, which may take up to 5 seconds until the next time the nRF24L01+ is available to receive data.
This results in about 4 packet losses and if I am lucky sometimes 2. Is there any way that when the nRF24L01+ sends data, the other Arduino stops everything to get the data? Like a communication between these two Arduinos that will be open 24/7, so that the other Arduino can multitask (reading sensors and upload the data through wifi).
I am using the code from this tutorial. Here is a my problem in an image (I hope this helps you understand it). Thanks in advance.

Are you using software serial for WiFi module?

Yes and I am communicating using AT commands.

The NRF24L01 has a RX FIFO buffer of 3 packets. So I don't see how you could miss 4 packets. My guess is that something else is going wrong. Could you post some minimal code that still produces that error.

It's not clear right now if the reason you are missing packets is because you are operating the wifi in a blocking way, or if it is because the wifi radio is interfering with the nRF24 one in the same general frequency range.  Both are potential issues.   Could you have your nodes number each reading and send it at multiple points in time?  So a given transmission might include readings 1345, 1346, and 1347 while the next transmission would have 1346, 1347 and 1348, etc.

You need to re-factor your program somewhat (I would imagine).  The nRF needs to be read at the same time as doing other things. That means interleaving it with your other operations.
There is a concept called a finite state machine which is the best way of writing a complex program like this. The idea is that nothing ever blocks, it just changes states. And all the time other things can be happening, such as reading the nRF24L01+ module.
I have a little tutorial on the Finite State Machine here:

https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/

If you use the Finite State Machine concept to run the reading of your sensors and the writing of data to the WiFi the nRF can then be polled constantly outside of the FSM constantly - maybe with an FSM of its own to deal with reception etc.
Things to remember:

Avoid delay(), certainly for anything longer than a couple of ms.
Avoid while(), for(), etc except for very short loops that finish quickly.
Any operation that takes more than a few ms to complete should be broken down into a number of sub-operations and coded as separate states of the FSM.

I see this is an old thread, but thought I'd chime in.
For an example implementation of a finite state machine, there are libraries built for this or you can use simple loop timers with if statements to "poll" sections of code instead of using ANY delays. Delays stop execution and waste your MCU time, preventing it from doing anything else, as already mentioned. Checking for wifi or serial messages can then execute with higher priority. An example pseudo-code would look like:
int update_ms = 500;
int last_update_ms;

setup{

last_update_ms = millis(); // or 0, to execute immediately

}

loop{

if(millis() - last_update_ms >= update_ms){
    last_update_ms = millis();
    execute_thing();}

check_for_wifi_msg();

}

There are libraries that do this essential behavior for you with more eloquence, as well, such as PollingTimer. I'm often surprised this isn't given as tool early on when people learn Arduino/ MCU programming, or in example codes. It is easy and so powerful.
You could accomplish the same "finite state machine" functionality with a real-time operating system built for microcontrollers. I can recommend FreeRTOS as a user-friendly entry to this. This makes your single core machine work like a multi-core machine, with a task scheduler. You can define several continually running while loops that the RTOS thread handler then interleaves for consistent execution. You could have 1 thread for your RF and 1 thread for your WiFi, with set execution rates, and RTOS handles the rest, e.g. it will try to fit RF reads inside of the Wifi loop whenever it can find downtime. This will likely make your Wifi loop somewhat longer as a sacrifice.
You can get started with these:
FreeRTOS Kernel Quick Start Guide
The FreeRTOS Reference Manual
Other solutions, which I won't elaborate on here include using a multi-core chip, like a ESP32, or to make use of WiFi interrupts to break out of other execution. Though, I do not know if this is specifically supported on the nRF24L01+.

source: Stack Exchange

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

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

sort: votes


text:
IR basic connection
Can I know how to change or connect from this circuit (three pin IR receiver) to two pin IR receiver because when I change the connection (3 pin to double pin), my arduino cannot receive the signal from transmitter.
I dont know because of my connection or because of there are different between tree and double pin IR receiver. Can anyone help me.
My code too long, so I just paste IR sensor for detect signal from transmitter.
{
  indicator();
  irrecv.resume();
  while(1)  //-------loop M1
  {
      HM_1();
      if(irrecv.decode(&results) >0 || digitalRead(SBB) == HIGH )
      // if IR receiver detect signal or button pressed
      {
         indicator();
         break;
        //irrecv.resume();
      }//
      else
      {    //-------else "if(sensor 2)"
          //go back to else "if(sensor 1)"
      }//-------else "if(sensor 2)" end
      //nothing
    }//-------while end
}

What is the part number? It looks like an IR LED (transmitter) to me.

There are some two pin receivers at the cheaper end of the market.  A part number would really help, but I suspect you haven't got one and can't find it.  I can't find any diagrams and I can't test one at them moment so this is a guess.  You need to leave out the red (vcc) wire from you diagram and connect the signal wire to +ve pin of the Receiver.  If that doesn't work switch the connections over.

To use a plain phototransistor to detect remote control signal with an Arduino at meaningful range in real world conditions, you will need to add either a circuit or software to select only signals with the desired modulation from the noise.  This is probably just barely possible with an Arduino's ADC, but will be a non-trivial project.  Unless you really want to spend time learning about signal processing and writing optimized AVR code, better to just buy the usual 3-pin type with an internal demodulator.

From what you have described, i think you are getting confused between the function of the two types. The 3 leg style is designed to receive coded pulses from remote controls (TV,Video, etc) where as the 2 leg is typically used, but not limited to, IR switching, where a signal is generated when the light path between the sender and receiver is broken with an opaque blade or similar or a beam is reflected back from an object as it passes. So trying to use the same code for the two types is provably where you are having problems.
Two example of this are here this uses a reflected IR beam where as this slot sensor is the break a beam type, often used in a limit or timing situation. One half of this is similar to the 2 leg diode you show.
It just depends on what situation you are using it in as to which is appropriate.
Without seeing your code, this is about as far as i can go, post your code so the forum can view it and make suggestions.

I already put my code.

To expand on Doug's answer:
There are two types of IR receiver. The two-pin one you have is basically a photodiode with infra-red filter. When infra-red light hits it the transistor gets biased and turns on. This is the most basic type you can get and is very hard to work with for anything other than simple on-off signals.
The second type is the IR receiver module. This contains a photodiode as above, but also contains extra circuitry. It receives IR light on the photodiode and filters it through a band-pass filter. A remote control sends a sequence of pulses of light which itself is further made up of high frequency pulses (36KHz square wave, for example). It's this high frequency pulsing that is allowed through the band-pass filter. The internal circuitry then turns these pulses of high frequency square waves into pulses of ON or OFF signals by low-pass filtering them to remove the high frequency component.
This latter type of receiver is far easier to work with for sending of data or commands from (eg) a remote control. But it can't detect a steady-state IR signal. The modulation and filtering means that a much weaker signal can be extracted from the background IR light meaning much greater distances can be achieved using much weaker transmission LEDs.
So while it is possible to use the former type with an Arduino you have to realise that the software required to do all the filtering and detection, as well as the extra hardware required to interface it, makes them considerably harder to use. That is why almost everyone uses the three-pin versions that do all that for you.
One thing to note with the three-pin versions: they have to match the carrier frequency of the transmitter. So a 36KHz transmitter has to be paired with a 36KHz receiver. Otherwise it won't be able to detect the signal. Just like a radio - it has to be tuned to the right band.

Thanks for expanding Majenko, I am not that technically proficient. Doug

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


text:
What are the Ramps pins on my Arduino mega?
I've been working on a 3D printer and I've come to the last step, which is wiring it all up.
The 3D printer I'm making works ONLY with the Arduino Mega. No Ramps. If I need to get Ramps later, I will, but for now, can someone please help me understand which of the Ramps pin goes with which Arduino pin. For example, in the Repetier firmware, the code is like this:
#define X_STEP_PIN         54
#define X_DIR_PIN          55
#define X_ENABLE_PIN       38
#define X_MIN_PIN           3
#define X_MAX_PIN           2

But Arduino doesn't have a 54 and a 55 pin. I've been googling this and I found that Ramps pins 54 - 69  are the same as pins A0 - A15 on the Arduino Mega.
I know this but not for the other pins...
Can someone please tell me the connection of all the Ramps pins to the Arduino pins?
Like: pin 54 on Ramps = A0 on Arduino. I need this for all of the pins.

As explained in schematic, we have Rx and Tx pin and d2* and d3*. If we check in arduino mega pin outs, Rx is D2 pin. this creates the confusion, please explain me the difference between D2 and D2*

You are right, your have all the information in your question.
Pin 54 Refers to the Arduino PIN Number, nothing to do with RAMPS.
0-53 are the digital pins and the 54 is A0, etc.
So the pin numbers should go higher than 69, which is A15.

You're very close to your answer.  Here are the specifics:
Name      software pin  Mega2560 board label
X_STEP_PIN    54         Analog A0
X_DIR_PIN     55         Analog A1
X_ENABLE_PIN  38         Digital 38
X_MIN_PIN     3          PWM 3
X_MAX_PIN     2          PWM 2

http://reprap.org/mediawiki/images/3/3f/Arduinomegapololushieldschematic.png shows the mapping.

thanks,
but when I insert the pins for the X axis directly on the mega, I doesnt work. I'm using a driver.


text:
ESP8266 does not respond after changing baud rate to 9600
I have ESP8266 WiFi module and Arduino Mega Board connected. I use external 5 to 3.3 V regulator to power up the module. Common (-ve) line on the external power source and Arduino Mega GND is connected. Then I used 1K and 2K voltage divider for WiFi module RX and TX use as same. I am sure my circuit is well works.
Then I connect RX0-RX and TX0-TX. Then i put CH-PD to 3.3v
Then I opened the Arduino IDE and upload the Blink sketch. Done.. Then I opened Serial Monitor and set baud rate to 115200. Then power up the module. It gave me a lots of garbage values and ready. Fine.
Then I downloaded the FLASH_DOWNLOAD_TOOLS_v0.9.5. configure the 0x0000, 0x1000 and 0x7c000

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

Then O power off the module and connect GPIO0 to ground and again power on.
Then push start button. Then it downloaded to the chip. It worked. Done. Success fully uploaded. Then I again disconnected the GPIO0 and power on. Then I put AT and it results OK.
AT+GMR gives version 0.9.5 updated.done.
The problem was the module was responded for 115200 baud rate, not 9600. Then I:
AT+IPR=9600

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

The command to change baud rate is AT+UART_DEF. Have you tried re-flashing the module?

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

Thank you reply me. I tried to reflash it. use baudrate 115200 .then the blue Led is blinking. after a little time blue LED went off. the software shows me to IDLE mode to Download mode but prograss bar doesn't update.it is stucked.

@KolithaWarnakulasooriya The flashing completed successfully? Have you tried sending AT?

No it didnt uploaded to the chip.software didnt show the success message.yes i tried to send AT. I set the end charachter type as Both NL & CR. baud rate 115200 ; nothing.

when i power up the module it gives me garbage values

Note:Serial port connected.
Note:Begin find ESP8266.
Note:ESP8266 ACK success.
Error:Read ESP8266 register timeout.

chip sync ok!    .
chip_flg 1 ,
r1: 0a; r2:88 ; r3: 31,
MAC AP : 1A-FE-34-0A-88-31 ,
MAC STA: 18-FE-34-0A-88-31 ,
filename:   ,D:\Adruino\FLASH_DOWNLOAD_TOOLS_v0.9.5_150414\FLASH_DOWNLOAD_TOOLS_v0.9.5_150414\bin_tmp\boot_v1.1.bin_rep
offset :  0,
Erasing flash...,
head: 1 ;total: 1,
erase size : 4096,
erase flash error,
com closed,

Thank you for help me to figure this out. I have made it. http://www.pratikpanda.com/completely-format-erase-esp8266-flash-memory/ this was helped me

@KolithaWarnakulasooriya What did you change? Does it respond now?


text:
Pros and Cons of using a non-pointer class object
In this example I have an one object which uses a pointer and one object which does not.
class MyClass {
  public:
    void myMethod() {
      // do nothing
    }
};

MyClass* mc1;
MyClass mc2;

void setup() {
  mc1 = new MyClass();
}

void loop() {
  mc1->myMethod();
  mc2.myMethod();
}

Is one implementation better than the other? Why?

Are you looking for an answer from an Arduino/small scale embedded programming perspective or general C++. "new" implies using a heap and pointers implies using indirection (which is slower but may be used for dynamic binding, e.g. redirecting mc1 during the execution of the program to another instance such as mc2; "mc1 = &mc2").

@MikaelPatel That's a tough one. I would love to hear both sides if you have the time.

In this situation, where you are just working with globals, the static declaration is preferred, although it makes little difference.
The static declaration (MyClass mc2) will reserve space in the BSS. The dynamic allocation (mc1 = new MyClass()) will allocate space on the heap at run time at the start of your sketch. Both are in pretty much the same area of RAM (the heap is directly above the static data area).
The only trouble starts to come when you want to free (delete) the object created with new. That can, over time, make a complete swiss-cheese mess of your heap which can cause memory allocation problems.
For that reason the dynamic method is shunned, but if all you ever do is allocate at the start and never deallocate then there is little practical difference between the two methods.

Fortunately I'm familiar with C style garbage collection as wall as ObjC retain/release. I assumed Arduino followed a similar suit so thank you for pointing out the effects of allocation.

It depends on what you are trying to do and partly a matter of taste but I tend to take this one step further when the class corresponds to a specific hardware resource. In this case you can use static methods exclusively to guarantee a 1 to 1 correspondence. Templates come to rescue when you want to bind a specific physical instance of some finite resource (e.g. one of the timers) and this can be further refined using specialization and traits (each timer has different characteristics).


text:
No data from U-Blox Neo-6M
I'm trying to get Neo-6M module to work with Arduino Uno, but it just isn't transmitting any data. It is getting 3.3V.
I've tried measuring the Amps and I got zero, so I'm afraid that the module could be broken.
Neo-6M wiring:

Arduino wiring (power):

Arduino wiring (data):

Arduino code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

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

  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. "));     Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop()
{
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();

  if (millis() > 5000 && gps.charsProcessed() < 10)
  {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo()
{
  Serial.print(F("Location: "));
  if (gps.location.isValid())
  {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();
}

I have tried several Ardiuno GPS sample data and could not get any data, but
I just used this 10lines software, and got data.

I run my board from the 5v Arduino tap as it has a 3.3v low drop off voltage regulator on board. So my belief is that you should also tap off the Arduino boards 5v supply.

Mine draws about 60ma from the Arduino board. The device should get a fix, then start transmitting over the tx line.  Indicated by the 'Position Fixed' led indicator on board, flashing once a second (at 9600 baud.)
Good luck, keep in mind that these boards are only about $7.50 on Amazon, order a couple for peace of mind. :)

It isn't enough to power the module with 3.3V. You also have to level-shift the Arduino's 5V TX signal to 3.3V that is acceptable by the GPS module's RX pin, using a 1:2 voltage divider.

You should also know that the Arduino's 3.3 V pin can't source more than 50 mA; your module's current draw may sometimes exceed this limit (max is 67 mA). Instead, connect the Arduino's 5 V pin (which can source up to 500 mA) to the VCC of the GPS module through an LM1117T 3.3 V regulator:

The input goes the Arduino 5V pin and the output goes to the NEO-6M VCC. Connect all GNDs together.
Then run a basic sketch like this:
#include "SoftwareSerial.h"

SoftwareSerial gps(4,3);

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

void loop(){
  while (gps.available())
    Serial.write(gps.read());
}

This will basically make the Arduino grab any NMEA data sent by the NEO-6M and forward it to your PC's serial monitor. If you receive legible data, it means you've established comms with the module. You can then upload your original sketch.

Acording to all those tutorials out there on this module it IS enough to use 3.3V from Arduino. The problem is it isn't drawing any current from the Arduino. And I don't need to transmit any data to the module.

@freemanovec It doesnt matter if you need to transmit; as long as you connected the module RX to the Arduino TX, the IDLE voltage of the line is 5V going into the module. You can simply disconnect the wire since you feel you dont need it. Also, unless you've studied the library code, you don't know how it performs its task; perhaps it is transmitting data even if its only to initialize the module.

The factory default for a ublox module is to output NMEA at 1Hz, you should get something even with no GPS signal. Assuming no one has changed the defaults on the module.  If you have some way to connect the module to a PC (e.g. TTL-232RG-VREG3V3-WE ) then trying to connect with the ublox U-Center software is a good idea, that makes it easy to change the power up default behavior.


text:
Talking to Eurotherm 2416 temperature controller over modbus rs232
I am trying to implement the modbus library written by smarmengol to read process values and to set new setpoints (e.g. temperature) on a Eurotherm controller. The Arduino sketch looks like this:
/**
 *  Modbus master example 2:
 *  The purpose of this example is to query several sets of data
 *  from an external Modbus slave device.
 *  The link media can be USB or RS232.
 *
 *  Recommended Modbus slave:
 *  diagslave http://www.modbusdriver.com/diagslave.html
 *
 *  In a Linux box, run
 *  "./diagslave /dev/ttyUSB0 -b 9600 -d 8 -s 1 -p none -m rtu -a 1"
 *  This is:
 *      serial port /dev/ttyUSB0 at 9600 baud 8N1
 *      RTU mode and address @1
 */

#include <ModbusRtu.h>
#include <SoftwareSerial>

SoftwareSerial mySerial (3,5);

uint16_t au16data[16]; //!< data array for modbus network sharing
uint8_t u8state; //!< machine state
uint8_t u8query; //!< pointer to message query

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram[2];

unsigned long u32wait;

void setup() {
  // telegram 0: read registers
  telegram[0].u8id = 1; // slave address
  telegram[0].u8fct = 3; // function code (this one is registers read)
  telegram[0].u16RegAdd = 1; // start address in slave
  telegram[0].u16CoilsNo = 1; // number of elements (coils or registers) to read
  telegram[0].au16reg = au16data; // pointer to a memory array in the Arduino

  // telegram 1: write a single register
  telegram[1].u8id = 1; // slave address
  telegram[1].u8fct = 6; // function code (this one is write a single register)
  telegram[1].u16RegAdd = 2; // start address in slave
  telegram[1].u16CoilsNo = 250; // (Setpoint) number of elements (coils or registers) to read
  telegram[1].au16reg = au16data+4; // pointer to a memory array in the Arduino

  Serial.begin(9600);
  master.begin( &mySerial, 9600); // baud-rate at 9600

  master.setTimeOut( 5000 ); // if there is no answer in 5000 ms,roll over
  u32wait = millis() + 1000;
  u8state = u8query = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    master.query( telegram[u8query] ); // send query (only once)
    u8state++;
    u8query++;
    if (u8query > 2) u8query = 0;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 1000;
    }
    break;
  }
   Serial.print(au16data[O]);

  au16data[4] = analogRead( 0 );

}

I can read process values with telegram[0] very well (temperature and/or setpoint), but I cannot change the setpoint with telegram[1]. If I run the code, it puts the current temperature to serial monitor but resets manually changed setpoints to zero. Where is the error? Should I write the value for the setpoint as HEX or DEC? What does the last command do actually?
Thank you!

telegram[1].u16CoilsNo = looks like this must be 1 NOT 250 (writing single 16 bit register); 2) are you writing to the same register / setpoint you read in telegram[0]? if so why u16RegAdd address is different?

@Flanker You are right, it must be 1 (single register) and not 250. The solution for my problem was to set au16data[4] to a fixed value, e.g 250, or something like that. I think that au16data[4] can be set interactively by sending any number thru a hardware serial, since analogRead(0) is Rx on Arduino. The start address for setting (writing) a setpoint is 2 and 1 for reading of the same value (setpoint). That is why au16RegAdd differs.Thank You for an answer!!

You could also take a look at this github project:
https://github.com/ukos-git/arduino-eurotherm2416
It is specifically designed for the purpose you ask for.
It basically includes Module named Temperature and a possibility to set or read it:
Temperature.set(100)
t = Temperature.getTemperature()

Look at https://github.com/ukos-git/arduino-eurotherm2416/blob/master/app/app.ino.


text:
Building an AtMega328p from Transistors
I'm a little new to circuitry, and the Arduino in itself!
From what I know, I think that it might be possible to actually build one (the processor itself, of course) from transistors. This isn't a practical question, of course, but it would be an excellent learning opportunity.
Would it be actually possible to go through with such a project (Even without EEPROM)?
If so, how would it be completed?
Thank you!

Transistors - :). Gates - yes but just too much work. FPGA - yes. Check estimated number of transistors https://www.embeddedrelated.com/showthread/comp.arch.embedded/14362-1.php

Start easy and e.g. build a 4-bit adder. The go for a 4-bit ALU. I.e. start small, and keep extending it.

I'd highly recommend you take a look at Ben Eater's video series about building an 8-bit computer on breadboards: https://www.youtube.com/playlist?list=PLowKtXNTBypGqImE405J2565dvjafglHU
He doesn't build it from transistors, and it isn't an AVR CPU, but he explains in detail the function of each IC he uses for this project, including possible circuits to duplicate the IC's functionality with transistors. With this approach he keeps the whole thing relatively compact, and still manages to visualise every detail of the CPU's inner workings using plenty of LEDs and a single-step clock mode.

Yes, it is possible - after all, the Arduino is essentially just a bunch of incredibly tiny transistors. Early computers, before ICs were invented, were built from transistors. Before that it was valves. Before that it was relays. All just, at the end of the day, switches.
Would it be a practical project? Not really, although someone has done it (not for the AVR CPU, but the concept is the same): http://www.megaprocessor.com/
How would you start? Well, first off you'd create the basic building blocks of a CPU, which is logic gates. There are two basic ones that can be combined together to make any other gate: the NAND gate and the NOR gate. You'd pick one of those and put lots of them together to make the basic sections of the CPU. Then those blocks connect together to form the CPU. More logic gates go together to make the IO functionality, memory, interfaces, etc.
Basically:

Transistors combine to make NAND gates (or NOR gates if you prefer that form)
NAND (or NOR) gates combine to make complex gates.
Complex gates combine to make logic functions
Logic functions combine to make logic blocks (like the ALU)
Logic blocks combine to make the CPU

Wow! Thanks! This is really helpful! This looks really, really hard, but I still might try it... Thank you!

If I really were doing this by hand, I would not make complex gates out of NANDs (nor NORs), as it would be more efficient to make them directly out of transistors. As an example, NOT(A AND B OR C) can be made with 6 transistors in CMOS (and only 3 in NMOS or PMOS). Many more transistors would be needed if one would be restricted to use only universal gates.

@EdgarBonet That's the same as what you end up with after optimization of your discrete gate circuits.

But then, going through an all-NAND design seems like useless extra work.

@EdgarBonet Which is why it's an essential step in the project. The whole project is useless extra work. And if you have to ask the question that the OP asked then you obviously have no understanding of logic gates etc so starting simple with NAND is a basic requirement.

I do not think you could build an ATmega328P out of discrete parts: you
would need floating-gate transistors for implementing the flash, and
these do not seem to be available as discretes.
If you forgo the flash (or replace it with RAM or ROM), then it should
in principle be possible. This processor, however, is probably not a
good choice for such a project. From the discussion linked to by
Mikael Patel, it seems you would need something like 80 K
transistors for the core alone, and much more if you include the RAM and
the peripherals. It would be a daunting task to assemble all this by
hand. For comparison, the Megaprocessor1 as about
42 K transistors total (core + RAM + LED drivers).
If you want to pursue such a project, I recommend you target a simpler
CPU. The MOS 6502 may be a good choice. This CPU, which was very
popular in the late 70s and early 80s, has “only” 3,510 transistors and
is well documented. See for example the resources at visual6502.org.
They have an amazing online transistor-level simulator built from
the actual layout of the chip.
1Thanks Majenko for the link

The ATmega128 have 800000 transistors. (+-200000 transistors)
So If you want to take some transistors and breadboards and build an ATmega128p
first count the money for transistors (if 1 transistor costs 0.01€ then 800000 x 0.01 = 8000€ and the breadboards is much more expensive than transistors!)

Try to build out the entire thing inside a simulator instead of buying 10s of thousands of transistors and several other components....less messy and gets the job done at almost no expense

Please suggest a few simulators in your answer, otherwise it may get flagged as a comment / not an answer.

There's too many, check out: https://en.m.wikipedia.org/wiki/List_of_free_electronics_circuit_simulators and https://en.m.wikipedia.org/wiki/Electronic_circuit_simulation and https://en.m.wikipedia.org/wiki/Comparison_of_EDA_software

https://www.electroschematics.com/2249/pcb-design-software/

Even an entire plant with all equipment and processes running live can be simulated: https://en.m.wikipedia.org/wiki/Plant_Simulation

https://en.wikipedia.org/wiki/Robotics_simulator

There's a startup/website called labster that has all sorts of simulators for students. Facebook's metaverse and Nvidia's omniverse will soon incorporate such virtual labs and twin factories.

Why not? Atmel did it.  But if you mean by soldering up discretes...
In the mid 70s the Zilog Z80 had 8,500 transistors; a couple of years later, the Intel 8088 had 29000(source: Wikipedia). Neither of those had on-chip memory. The AtMega 328p has 2K of RAM and 1K of EEPROM on chip, so factor in for those and their drivers. At 20 MHz it will probably be fun 1) keeping signals where they belong; and 2) keeping the wire runs short enough and suitably arranged that capacitance doesn't slow and distort the signals to unusability.

While it is possible, you will have to spend a lot of money and a lot of time. I think about thousends of dollars and months of work. Even when accomplished you will have learned more about electronics than about the ATmega328P. In order to accomplish, you will also have to ask Atmel to hand you over the schematics to get the inner working right. I highly doubt they will aggree since it is not Open Hardware.
I highly discourage you to do that. Instead I suggest you start with an Arduino UNO and discover the capabilities and then go a step further and use a bare ATmege328P.

Although you cannot get the schematic of the real Atmel’s AVR, there are a few AVR clones available at http://opencores.org/

Would it be actually possible to go through with such a project (Even without EEPROM)?

yes.

If so, how would it be completed?

the easiest would be to find or write a soft-core for AVR on a fpga. Get the logic blocks for that softcore , and then implement those logic blocks with transistors.
Before you set out actually doing it, however, check if you have enough of space or bank account (for the electric bills).


text:
Using two software serial - two UART
I have ATMega328p chip, and I have HC-06 on pin A5, A4 (RX, TX) and I have another device on pin 10, 9 (RX,TX).
I want to be able to send some command on BT via Bluetooth Terminal and pass raw (exact) command to that device unchanged just to log on my computer (on my serial monitor) incoming command from BT and to log the response from device the same way on serial monitor and pass unmodified to HC-06.
How can I do that?
I tried by using "listen()" method but sometimes I get some weird character while I'm transferring\reading data, so not sure how to do this.
All baud rates are 9600.

You can only reliably use one SoftwareSerial port at once.

Not even with that "listen" function?

Even with listen(). You can't do anything at all whilst writing on a SoftwareSerial port. That includes listening on another SoftwareSerial port. So anything that arrives on the first port whilst you are writing earlier data out of the second port will become corrupted or not arrive at all.

Your question isn't clear at all. Who sends the commands? Who responds? What exactly do you want to achieve?

I want to log communication between HC-06 and another hardware via Arduino. Mobile phone send command to HC-06, HC-06 to Arduino, Arduino to third device, and vice versa. What isn't clear there?

If this suits you, you can 1) connect HC06 and other devices directly. 2) connect one of the two serial through a resistor to the arduino TX pin, and the other to the RX pin. The arduino should only forward what it receives to the same serial again. The resistor should prevent back-injection in the serial line. BUT the most smart way to deal with this is to use a board with more serial interfaces

You can have high-speed debugging by utilizing either I2C or SPI to send to a second Arduino. That second Arduino can be devoted to receiving debugging information and passing it on (via serial to your PC).
I describe the process here.
The general idea is to add some stuff to the DuT (device under test) to output via SPI/I2C.
Example code:
// make true to debug, false to not
#define DEBUG true

#include <SPI.h>

// conditional debugging
#if DEBUG

  #define beginDebug()  do { SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8); } while (0)
  #define Trace(x)      SPIdebug.print   (x)
  #define Trace2(x,y)   SPIdebug.print   (x,y)
  #define Traceln(x)    SPIdebug.println (x)
  #define Traceln2(x,y) SPIdebug.println (x,y)
  #define TraceFunc()   do { SPIdebug.print (F("In function: ")); SPIdebug.println (__PRETTY_FUNCTION__); } while (0)

  class tSPIdebug : public Print
  {
  public:
    virtual size_t write (const byte c)
      {
      digitalWrite(SS, LOW);
      SPI.transfer (c);
      digitalWrite(SS, HIGH);
      return 1;
      }  // end of tSPIdebug::write
  }; // end of tSPIdebug

  // an instance of the SPIdebug object
  tSPIdebug SPIdebug;

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

The other Arduino (which receives the debugging information) simply echoes it to Serial:
char buf [1000];
volatile int inpoint, outpoint;

void setup (void)
{
  Serial.begin (115200);   // debugging

  Serial.println ();
  Serial.println (F("Commencing debugging session ..."));
  Serial.println ();

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // now turn on interrupts
  SPCR |= bit (SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register
int next = inpoint + 1;  // next insert point

  // wrap-around at end of buffer
  if (next >= sizeof buf)
    next = 0;

  if (next == outpoint)  // caught up with removal point?
    return;  // give up

  // insert at insertion point
  buf [inpoint] = c;
  inpoint = next;  // advance to next

}  // end of interrupt routine SPI_STC_vect

void loop (void)
{
  // insertion and removal point the same, nothing there
  noInterrupts ();  // atomic test of a 16-bit variable
  if (outpoint == inpoint)
    {
    interrupts ();
    return;
    }
  interrupts ();

  // display anything found in the circular buffer
  Serial.print (buf [outpoint]);

  noInterrupts ();
  if (++outpoint >= sizeof buf)
    outpoint = 0;  // wrap around
  interrupts ();

}  // end of loop

SPI is quite fast, so the overhead of doing the debugging should be slight. The receiving end can batch up the debugging information (up to a point which is about 1000 characters) and then send it to your PC via Serial.

I made a library out of the relevant code. The library is available from:
http://gammon.com.au/Arduino/SPI_Debugging.zip
Example using the library:
// make true to debug, false to not
#define DEBUG true

#include <SPI.h>
#include <SPI_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

There is a similar library for I2C debugging:
http://gammon.com.au/Arduino/I2C_Debugging.zip
Example of doing I2C debugging:
// make true to debug, false to not
#define DEBUG true
const byte SLAVE_ADDRESS = 100;  // which address debugging goes to

#include <Wire.h>
#include <I2C_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name
}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

All of the examples illustrate using a #define to turn the debugging output on or off, so you can leave the debugging prints there in case things go wrong, but with debugging disabled they won't have any penalty.

How can I do that?

You can't.
It is impossible to use two SoftwareSerial ports together. Simply because while you are writing to one port everything else stops. Interrupts are disabled, and receiving requires interrupts. So anything that arrives while you are sending will either be lost or corrupted.
The only solution is to use a board with multiple hardware UARTs like the Mega or any of the more powerful alternatives to Arduino such as chipKIT or Teensy.

Would using that hardware UART instead of second software UART fix the problem? For example to use one software serial for that bluetooth, and hardware UART for that other device...

While not having it tested yet. That would be the solution I'd try. The hardware UART gives you all the functionality for free without interfering with other parts of your software.


text:
Can't display text on LCD 1602
Today I tried to display some text with my Arduino UNO and a LCD 1602A screen. I did find some schemas online, but I cannot get any character or "black boxes" on the display.
I connect wires like that :
Pin 1 : GND
Pin 2 : +5V
Pin 3 : 50K Pot.
Pin 4 : Pin 7 from Arduino
Pin 5 : GND
Pin 6 : Pin 6 from Arduino
Pin 11 : Pin 5 from Arduino
Pin 12 : Pin 4 from Arduino
Pin 13 : Pin 3 from Arduino
Pin 14 : Pin 2 from Arduino
Pin 15 : +5V
Pin 16 : GND
You can see my setup here : https://i.stack.imgur.com/u32sj.jpg
The LCD screen is lighten up, but nothing else appears. Pot. is working (increase or decrease light). I tried to change the LCD with another, but both are not working. I tested some many code, here an example :
/*
  LiquidCrystal Library - Hello World

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time.

  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

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

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

Do you have an idea ? Thanks !

Looks like your pot is wired wrong. It should be between VEE and GND with the wiper to VO, not between +5V and GND.

Sorry to ask, but what's VEE ?

Actually, ignore that - I am thinking graphical LCDs that have a different offset voltage requirement.

I realize that your question is based around using multiple connections to the arduino, however if you wish to simplify the setup/operation have a good look into I2C interface, this only uses 2 pins SDA and SCL to operate, you can get an interface board on Ebay for $1.00....just a thought.

Wiring on the photo and description you provided are not consistent. On the photo, LCD-RS (PIN 4) is connected to D12 and LCD-E (PIN 6) is connected to D11?
If so, initialization must be LiquidCrystal lcd(12, 11, 5, 4, 3, 2);


text:
pH ORP sensor esp12 esp82666
I need to know if there is a sensor that mesure pH and ORP, I have already googled about this type of sensor but i found only AtlasScientific that commercialise this kind of sensor
thanks

Yes there are lots.  You might try search for "Arduino PH Sensor" and "Arduino ORP sensor" you'll get a lot more hits for Arduino than ESP8226.
This might be useful:
http://www.instructables.com/id/ORP-pH-Temperature-Data-Logger/?ALLSTEPS


text:
code wont upload to arduino starter kit
My operating system : OS X EL CAPITAN
Please help I was trying to do project 05 Mood cue of the arduino starter kit. I completed setting up my board and writing the code and when I tried to upload I got this error message:
Arduino: 1.7.10 (Mac OS X), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/tty.usbmodem1411": Device not         configured
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

Can someone please help me?

Try to use the official and original Arduino software from arduino.cc current version

@Personagem i tried to download it and it still would not work this is the error it gave me now :
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/tty.usbmodem1411": Device not configured
Problem uploading to board.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

It sounds like there is an issue with your USB serial connection.

@harry_p_6 thanks for the response harry. What do i do now? is there a away to fix it? im very new to all this

@harry_p_6 Thank you Harry i managed to fix it by downloading CH341SER_MAC.zip just in case someone has the same problem http://www.wch.cn/downfile/178

your arduino kid may not be connected properly else configure the board

@PendukeniPandeni Glad you managed to find the solution. Add your comment as an answer and mark it as accepted solution.

You're welcome. As @Personagem said, please answer your own question and accept the answer so that it does not count as an unanswered question.

Thank you Harry i managed to fix it by downloading CH341SER_MAC.zip just in case someone has the same problem wch.cn/downfile/178


text:
Uno R3's a4 and a5 not working after installing itead SD Shield 3.0
I'm working on a data logging project and would like to use all six analog inputs on my Arduino Uno R3.  I've been able to get everything working, including writing to the SD card.  However, with the shield installed I'm getting junk readings from a4 and a5.  They work fine without the shield.

The shield has pull-up resistors for I2C/TWI on pins A4 and A5. Special care (resistor bridge) needs to be taken if using these as analog pins. Please see the schematics for more details.
https://www.itead.cc/wiki/images/4/46/Sch_sd_shield_3.0.pdf
Cheers!


text:
Arduino Saint Smart Chapter 7 Tri Color Module
I am very new to Arduino, I bought a starter's kit and I am working with the user manual that is available. I am in chapter 6 Tri Color Module
I am using the following code:
// Defining the LED driver pins and some other
// variables.
const int numLEDs = 3;

int blueLEDPin  = 3;
int greenLEDPin = 4;
int redLEDPin   = 5;
int ledPin[3];
int ledPinIndex = 0;

// the setup routine runs once when you press reset:
void setup() {

  Serial.begin(9600);

  // initialize the digital pin as an output.
  ledPin[0] = blueLEDPin;
  ledPin[1] = greenLEDPin;
  ledPin[2] = redLEDPin;

  for (int i=0; i < numLEDs; i++)
     pinMode(i, OUTPUT);

}

// the loop routine runs over and over again forever:
void loop() {

  digitalWrite(ledPin[ledPinIndex%numLEDs], HIGH);
  delay(1000);
  Serial.println(ledPinIndex%numLEDs);
  delay(2000);
  digitalWrite(ledPin[ledPinIndex%numLEDs], LOW);

  ledPinIndex++;
}

My problem is that in the setup() method where the following code is
for (int i=0; i < numLEDs; i++)
         pinMode(i, OUTPUT);

From my understanding pinMode OUTPUT is use to send power out of the specific pin. As the code displays pin 3, 4, and 5 are used but the above code is setting pinMode for 0, 1, 2. Is this write? And even if I comment out the two lines up my project no differently as to the previous code.
Can someone verify if the above code is correct, or should it be setting pinMode for 3, 4, and 5.

This code is broken.  Like a lot of cheap import electronics, it shipped "only half finished"  There can still be value if you know what you are getting and are ready to do what was left out, or plan to use things in a different way anyway.

This line pinMode(i, OUTPUT); should probably be replaced by pinMode(ledPin[i], OUTPUT);
Otherwise it won't make sense.


text:
Help understanding SoftwareSerial recv() and PCINT
In the SoftwareSerial library, I see the beginning of recv() as follows
void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {

This comment seems to be testing for if the pin change was from low to high, or high to low.  If you are using inverse logic - where the line is held high, and start bits are low - then a call to rx_pin_read() should return 0.
This doesn't seem correct.  In inverse logic the line is held high and a drop indicates a start bit.
Is the SoftwareSerial library ignoring the start bit and relying on some kind of return to zero break between the start bit and any subsequent bits?
It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

"If you are using inverse logic - where the line is held high, and start bits are low" No, that's normal logic for a UART.

This doesn't seem correct. In inverse logic the line is held high and a drop indicates a start bit.

No, in inverse logic (for a UART) the line is held LOW and a rise indicates a start bit. The diagrams you show in your question show that UART communication normally is HIGH with LOW for a start bit.

It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

The PCINT is only used to identify the falling (or rising in the case of inverse logic) edge of the start bit. From then on it samples at pre-defined periods to read each bit. Accurate timing is needed for that, so assembly code is used to give precise delays (see tunedDelay()). Once the whole 10-bit packet has been received the interrupt handler finishes and control is returned to the main thread again. The PCINT is then free to look for the next start bit.

But, it doesn't look for a start bit.  It just ignores the start bit and hopes that the second bit has a rising edge.  There's no tunedDelay() to wait for the next bit after the start bit.

No it doesn't. It uses the falling edge of the start bit to begin receiving. That is the ONLY edge that is ever looked at. It then immediately delays for half a bit to centre the readings properly, then reads 8 bits with a full bit delay preceding each read. Have you actually read and understood the ::recv() function?


text:
WiFi Password Safety
Are there any best practices regarding password safety?  The following is taken from a wifi tutorial sketch.
#include <SPI.h>
#include <WiFi.h>

char ssid[] = "yourNetwork";      // your network SSID (name)
char pass[] = "secretPassword";   // your network password
int keyIndex = 0;                 // your network key Index number (needed only for WEP)

While I accept that the tutorial is there for learning how to use the shield, I would assume hard coding the password into the sketch leaves this open to attackers.  Is this actually the case?  If so, are there any strategies to harden the sketch, for example with encrypted storage?
I am a relative newbie with physical computing and Arduino, so sorry if I am overlooking something obvious.

Any system which needs to communicate a password between an MCU and a standard wifi module in cleartext is readily open to attack by anyone who has physical access just by sniffing the serial, spi, or whatever channel in between them.  The tools to do so sell for $6-24.

You'll have to physically secure the Arduino device, as the attacker has to have physical access to the Arduino to get to the password. In corporate environments, they would set up a separate wifi network, with a firewall, to reduce the risks when that network is compromised.

On the avoiding hard-coding front, I just found this: https://www.instructables.com/id/Avoid-Hard-Coding-WiFi-Credentials-on-Your-ESP8266/
It basically creates its own network to address the bootstrapping issue. Which makes this a nice way to package a device for someone else to use, too.

I'm not as concerned about someone hacking the hardware on my desk to get the Wifi password. I'm concerned about the code-sharing implications of hard-coding a password into the source. Is there a way to read from environment variables instead of hard-coding for example? Then I can share my sketches on github without concern.

You're actually entering into a very tricky and difficult area.
Yes, having a plain text password in your sketch is a risk. It is stored in flash as plain text. If an attacker can gain access to the contents of the flash through some means (whatever they may be) then they could obtain that WiFi password.
You would think that encrypting the password would be the answer, but that's not the case. The problem with an encrypted password like this is it has to be decrypted to use it. That means that both the encrypted password and the encryption key are both stored together in flash. If you can get one you can get the other, and thus the encryption is null and void.  Encryption security relies on keeping the encrypted data and the key used to encrypt/decrypt it completely separate. After all, you don't leave the key to your house in the front door lock when you go out, do you? It's exactly the same.
So what do you do?
Well, there's lots of different ways of looking at security. In this case there is one specific viewpoint that works best:
Security Through Obscurity
Your system is (pretty much) unique. Nobody but you knows just what it does and how it does it, or how you interact with it. It's not obvious to the casual observer just what it is or what could be done with it. That means that they won't know how to break in to it.
The majority of use of vulnerabilities in systems rely on those systems being ubiquitous - that is, all over the place; easy to obtain. In short, easy to find out what they are, how they work, and even reverse engineer them to a certain extent. Attackers aren't going to be able to do that with your system, since you are the only person in the world with it.
However, it's far from perfect, and you shouldn't rely only on Security Through Obscurity.
Simple obfuscation of the password (not actual encryption, but just storing it in a way that isn't obvious) can help, since it isn't then easy to see where in a memory dump the password would be. Splitting it up and scattering it around the place, too, can be useful.
Basically there is no simple answer, other than make it as hard for an attacker to find sensitive things as possible and don't tell anyone what you have done to hide it ;)

Level-up to Majenko for the thorough breakdown. I've seen some crypto libraries for arduino, and your only concern is the key for your string. I have used some bits unique to systems (and which could be grabbed from C, once just a username and hostname) when I had to obfuscate strings, but I don't think that's a good practice. If attackers (who attack your arduino, inside your house perhaps?) dump its memory, you probably have bigger problems which require a shotgun. But if you insist, I recommend finding some bits unique to the mcu (serial number perhaps) and XOR'ing the wpa key with that.

Unfortunately, I don't have a precise answer to your question currently, but I would like to warn you about the Security Through Obscurity approach proposed by Majenko.
This approach may be reasonable for something very homemade, but it is strongly discouraged by researchers and experts.
For instance, if you have a look at the Guide to General Server Security you will read between the "Server Security Principle":

Open Design—System: security should not depend on the secrecy of the implementation or its components.

So, try always to use a standard approach if you can.


text:
Atmega328p - PCB ISP pins for bootloader and sketch upload
I want to design my PCB with Atmega328p chip on it and I want to be able to burn Bootloader and sketch after that while everything is soldered on the PCB. So my question is, what would be the best way to do that? My current idea is to leave extra pins for burning a Bootloader, and to leave also extra pins for uploading the sketch, and to "unplug" other stuff connected on these pins (for example on hardware UART) by adding\removing jumpers.
I'm pretty new to all this stuff, so I'm not quite sure what's the best approach.

If you're leaving pins (SPI pins, by the way) for uploading the bootloader, why bother with the bootloader at all - just program direct using those ISP pins.

I'm pretty new to arduino programming, I thought that I must have bootloader uploaded first and then to upload my sketch. I didn't know that I can upload sketch directly without bootloader...can I?

Yes, you can. The bootloader is purely for convenience so you don't need a hardware programmer. Since you already have the hardware programmer you don't need the convenience of the bootloader.

By hardware programmer, do you mean another arduino which I can connect to my board like when I'm burning an bootloader, or it can be done even just with FTDI cable?

Another Arduino, yes, or something more convenient like a USBASP ($2 on eBay from China), but not an FTDI cable, no.

Ok, that is excellent news! You just saved me some extra time and space for design traces on PCB :) One more think then, when I'm using that hardware programmer, do I need to change something in my sketch, or I'm still using it as it is, the code I mean?

The code is the same. Just select a different programmer in the IDE.

One further advantage: you don't get the 2 second delay at startup while pin 13 (LED) blinks as the bootloader times out. Your sketch starts instantly and you don't get strange things happening on pin 13.

And based on this http://www.learningaboutelectronics.com/Articles/Program-AVR-chip-using-a-USBASP-with-10-pin-cable.php I basically just need to leave 6 pins, that 4th pin says NC I guess as Not Connected, and there's few for GND which can be just one I guess. @Mayenko feel free to answer and I will accept it as a valid answer. You helped a lot to me today to understand few new things, thanks.

The ISP header is RESET, MOSI, MISO, SCK, GND and +5V.

That USBASP from what I see in description (ebay\aliexpress) looks like it's not for ATMEGA328P, it's for  ATMEGA8 ATMEGA128. Can I use if for ATMEGA328P as well?

Realistically, you should design ATmega boards to support both ISP and bootloader pins.  The logic is simple:

Unless you buy pre-programmed chips, or have a programming fixture, you will need ISP either to load the firmware itself, or to load a bootloader.
Even if you plan to use only ISP for programming, it is still worth providing external connections to the UART pins for interacting with firmware during development; generally with ATmega-based Arduinos you do not have a breakpoint debugger, so debug messages on serial are your primary visibility into what is happening.
You should wire the reset line to somewhere that you can manipulate it, so you don't have to power cycle your firmware every time you want to restart it in testing.

Once you have done all that, you end up with support for both ISP and UART bootloader - regardless if you plan to use them both or not.


text:
Arduino Mega 2560 Only Powers on with USB
I have an Arduino Mega 2560 board running a ramps 1.4 shield for a 3D printer.  For some reason, I can only power the Mega with USB.  It does not get power from the ramps shield and it also will not power on when plugged in to a 12v wall adapter.  I know all power sources are working because I have a second Mega that works fine on all.  What could I check on the Mega board to help figure this out.  Other than being powered only by USB, everything else works as expected with no problems.

Looking at this Arduino Mega 2560 schematic, if IC1 or IC2 failed (assuming only one or the other is installed for a given board), then you would only be able to power the board using the USB port.
Looking at this ramps 1.4 shield schematic it is assumed that the RAMPS 1.4 shield is providing 12 volts through D1 to the Arduino Mega 2560.  And that testing included using a known good Arduino Mega 2560 board with the RAMPS 1.4 shield board with good results.  Thereby eliminating the possibility that D1 on the RAMPS 1.4 shield is damaged.
If these assumptions are correct, this reinforces the likelihood that either IC1 or IC2 has failed on the Arduino Mega 2560 board.

D1 sends power from the shield down to the Arduino. I will look into the IC's on the Arduino.

st2000 In the bottom left there is the power section, where you can see that D1 puts 12V on the net labeled AM_Vin; this net is then redirected to the mega Vin pin. @JeffThomas follow the wires with a multimeter, then share the measures..

I will add a comments that it is assumed the shield is providing 12 volts through D1.   And that it is assumed testing included using a known good Arduino Mega 2560 with the RAMPS 1.4.


text:
Board and library updates required caused an error
I compiled my code several times today,
I would quit and restart randomly through the day.
each time I started I get a error box board and libraries need updates.
I did an AVR board up date, then compiled and now I get this every time.....

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

Yes I have tried rebooting my Windows 7 64 bit AMD machine.
this is on IDE "Arduino 1.6.8"
Of course I made the mistake of not backing up my IDE folders in the belief that an update would not screw my IDE up.
Nothing will upload, not even any of the examples.
I turned on Show Verbose output during Compilation, and upload
I pasted the full output and it was 4500 char to many for this so I turned of the compilation check and left just the upload check on show verbose errors
I loaded in the example blink,
the file followed by the IDE lower window text.
/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the Uno and
  Leonardo, it is attached to digital pin 13. If you're unsure what
  pin the on-board LED is connected to on your Arduino model, check
  the documentation at http://www.arduino.cc

  This example code is in the public domain.

  modified 8 May 2014
  by Scott Fitzgerald
 */

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

END OF FILE
Copy and paste of the lower IDE window  last lines the same as above

Sketch uses 928 bytes (2%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/bin/avrdude -CC:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf -v true -patmega328p -carduino -PCOM10 -b115200 -D -Uflash:w:C:\Users\Lee\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jun 22 2016 at 16:05:21
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf"

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

There is that line again   What do I do to fix this?
besides deleting everything and starting all over again?
I do not want to delete and start over

try to check your setting in Tools->Board and Tools->Programmer.

Possible duplicate of Uploading Error: no programmer has been specified

This sounds very much like the problem I had when I updated my ARV version,I was also getting "no programmer has been specified error", I run Windows 7 32bit, the way i got out of it was to go back to the update screen when it pops up and in Arduino ARV Boards area....select versions....I went back to version 1.6.10...now it all works again.....at this point I am no longer updating my ARV, but I will after a few more version updates come out, there is obviously something that conflicts at this stage, if you google the problem you will find other of ways to fix this.


text:
Programming arduino using avrdude from command prompt
Out of curiosity, I am trying to upload a simple hex file to Arduino UNO using avrdude from windows command prompt.
As per this forum, I tried to implement it. But got stuck at

avrdude: ser_open(): can't open device "COM41": The system cannot find the file
  specified.

This command was directly imported from Arduino IDE verbose, and also it works fine when uploaded with Arduino IDE. I checked both the device and syntax are correct unless I would not be able to generate the hex file by Arduino compiler.
P.S. I have installed Winavr separately although it was pre-installed by Arduino
itself.
Here is a snapshot of the error
What could be the possible reason for it to fail? Please notify, if anything is missing.

I seems like you are using a different avrdude, as normally arduino uses the avrdude binary that is inside the arduino application folder. Also the avrdude conf-file is missing. So it looks to me like you have modified the command "directly imported" from the IDE.

@Gerben I downloaded the software Winavr and installed it separately. This is not the avrdude that was present inside arduino application folder.

After a lot of experiment, I finally made it. I got to know from some forum that when COM PORT is greater than 10, you have to put a '.' after COM PORT setting e.g. -P.COM41.
But, unfortunately that did not work. Then I changed the COM PORT to under 10 in device manager -> Properties -> COM Port Setting -> Advanced Setting; e.g. COM6.
Then it worked. At the time of flash just I have to press the RST button for once.
And now bingo!!
Still, I will try to find out why it didn't work with higher COM Port.

can't open device "COM41": The system cannot find the file specified.

This means there is no device at COM41. This may be due to 2 reasons:

You may not have connected your arduino. If this is the case then you please connect the arduino and retry
Your arduino might be on a different COM port. If this is the case, then, go to device manager and check your arduino's COM port and replace COM41 with that and retry.

No, that is not the case here. As I said I have connected the Arduino and in the device manager it showed COM41. And I can easily program it from arduino IDE, but when I try to upload using Avrdude it shows this particular error.


text:
How do I split a number into individual digits?
How would I split part1 into 2-3 digits and put them into num1, num2, and num3?
int FMSTATION = 10250;

int update_display() {
  int fm_station = FMSTATION ;

  int part1;
  int part2;

  part1 = (FMSTATION / 100);
  part2 = (FMSTATION % 100);
  part2 = (part2/10);

  int num1 = ;
  int num2 = ;
  int num3 = ;
  int num4 = part2;

  matrix.writeDigitNum(0, num1, false);  //1st number on lcd
  matrix.writeDigitNum(1, num2, false);  //2nd number on lcd
  matrix.writeDigitNum(3, num3, true);   //3rd number on lcd and adds "."
  matrix.writeDigitNum(4, num4, false);  //4th number on lcd

  matrix.writeDisplay();
}

I have searched the web from top to bottom, but could not find the answer. In the end what I should get displayed on my LCD is 102.5.

% 10 returns the final digit of a number. Dividing by 10 shifts the number one digit to the right.
So if you have the number 10250 as an integer you can get at each number with:
10250 % 10 = 0
(10250 / 10) % 10 = 5
(10250 / 100) % 10 = 2
(10250 / 1000) % 10 = 0
(10250 / 10000) % 10 = 1

So your code could be written as:
num4 = (fm_station / 10) % 10;
num3 = (fm_station / 100) % 10;
num2 = (fm_station / 1000) % 10;
num1 = (fm_station / 10000) % 10;

No need to mess with "part" variables.

Will try it out

I think this will help you:
int FMSTATION = 10250;
int update_display() {
  int fm_station = FMSTATION ;

  int part1;
  int part2;
  part1 = (FMSTATION / 100); //102
  part2 = (FMSTATION % 100); //50
  part2 = (part2/10); //5

  int num1 = part1/100; //1
  int num2 = (part1 % 100)/10; //0
  int num3 = part1%10; //2
  int num4 = part2; //5

  matrix.writeDigitNum(0, num1, false); //1st number on lcd
  matrix.writeDigitNum(1, num2, false); //2nd number on lcd
  matrix.writeDigitNum(3, num3, true); //3rd number on lcd and adds "."
  matrix.writeDigitNum(4, num4, false); //4th number on lcd

  matrix.writeDisplay();
}

For num1 display, I would also check if it is not 0 before displaying it and clear the digit if it is, so that 95.6 would not get displayed as 095.6.

Ok, i will try it out

Thanks this did work, also i will try and implement the digit clear


text:
Pass templated function as attachInterrupt parameter
So I want to do something like this:
template<int PIN, int CHANNEL>
void initPin() {
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

template<int PIN, int CHANNEL>
void rising() {
    startTimes[CHANNEL] = micros();
    attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
}

template<int PIN, int CHANNEL>
void falling() {
    values[CHANNEL] = micros() - startTimes[CHANNEL];
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

but the compiler gives me this error
no matches converting function ‘rising’ to type ‘void (*)()’

Can I even do this, or do I have to write all the functions by myself?

Try this:
template<int PIN, int CHANNEL> void initPin() {
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

template<int PIN, int CHANNEL> void rising() {
    startTimes[CHANNEL] = micros();
    attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
}

template<int PIN, int CHANNEL> void falling() {
    values[CHANNEL] = micros() - startTimes[CHANNEL];
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

The problem is actually the Arduino preprocessor. It adds illegal forward declarations if template functions are formated as your original code.

Please have a look implementation
https://github.com/Yurik72/SimpleButton
There are implementation how to assign function with arguments to interrupt handler


text:
Testing Logic Gates using Arduino
hello guys is there someone who can help me with my first project.
its basically about logic circuits.
by using tact switch and pull-up resistor to set the values to logical 1 or 0.
the output can be verified by using a LED as an indicator.
so the code goes like this:
//AND GATE
int pin2=1;         //set pin2=1
int pin3=1;         //set pin3=1

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)            //turn led on pin11 when pin2 =1
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)          ////turn led on pin12 when pin3 =1
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF AND

  if(pin2 && pin3)
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

//OR GATE
int pin2=1;
int pin3=1;

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF OR

  if(pin2 || pin3)
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

//NAND GATE
int pin2=1;
int pin3=1;

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF NAND

  if(!(pin2 && pin3))
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

can you guys help me to run this in one sketch by using tact switch  to select the logic gate to be tested or run? thank you in advance

This cannot work: pin2, pin3, setup() and loop() are all defined three times. You cannot paste three programs one after the other and expect the whole to be a valid program. Just run one program at a time. If you have no push button, use a wire that you manually connect and disconnect to/from GND (if using a pullup resistor) or 5V (if using a pulldown).

@EdgarBonet actually combining both programs in one seems to be the actual question here :-)

What about something like this:
const uint8_t    inA =  2;
const uint8_t    inB =  3;
const uint8_t   outA =  4;
const uint8_t   outB = 11;
const uint8_t   outY = 12;
const uint8_t button =  5;

void setup() {
    pinMode(inA, INPUT_PULLUP);
    pinMode(inB, INPUT_PULLUP);
    pinMode(outA, OUTPUT);
    pinMode(outB, OUTPUT);
    pinMode(outY, OUTPUT);

    pinMode(button, INPUT_PULLUP);
}

uint32_t check_time = 0;

uint8_t     counter = 0;
uint8_t       funct = 0b0110; // start with XOR

void loop() {
    // active low: (for usage with buttons connected to ground with internal pullup)
    // uint8_t state = (digitalRead(inA)==LOW) | (digitalRead(inB)==LOW)<<1;

    // active high:
    uint8_t state = (digitalRead(inA)==HIGH) | (digitalRead(inB)==HIGH)<<1;

    digitalWrite(outA, (state & 1) > 0);
    digitalWrite(outB, (state & 2) > 0);

    digitalWrite(outY, ((funct >> state) & 1) > 0);

    // button handling
    uint32_t actual = millis();
    if (actual > check_time) {
        check_time = actual + 4; // check every 4ms

        if (digitalRead(button) == LOW) { // expects pull-up and active low
            if (++counter == 4) { // debounce - confirmed after 16ms (4*4) and every 256*4 ms again
                funct = (funct + 1) & 0xF;
            }
        } else {
            counter = 0; // reset counter
        }
    }
}

It uses push button to cycle through all 16 possible functions of two inputs.
Default is XOR. Assumption is Active HIGH inputs (you can use INPUT instead of INPUT_PULLUP).

For simulating different gates with the same program, an option is to
use the serial port to tell it what gate you want it to simulate. Here I
am also using a function pointer (called gate) to represent the
selected gate:
/* Wiring. */
const int inputA    = 2;
const int inputB    = 3;
const int outputA   = 11;
const int outputB   = 12;
const int outputRes = 4;

void setup()
{
    pinMode(inputA,    INPUT_PULLUP);
    pinMode(inputB,    INPUT_PULLUP);
    pinMode(outputA,   OUTPUT);
    pinMode(outputB,   OUTPUT);
    pinMode(outputRes, OUTPUT);
    Serial.begin(9600);
    Serial.println(F("Type 'a'(for AND), 'o' (OR) or 'n' (NAND)."));
}

/* Available gates. */
bool AND(bool a, bool b)  { return a && b; }
bool OR(bool a, bool b)   { return a || b; }
bool NAND(bool a, bool b) { return !(a && b); }

/* The gate we want to test. */
bool (*gate)(bool a, bool b) = AND;

void loop()
{
    // Select the gate through the serial port.
    switch (Serial.read()) {
        case 'a': gate = AND;  Serial.println("AND");  break;
        case 'o': gate = OR;   Serial.println("OR");   break;
        case 'n': gate = NAND; Serial.println("NAND"); break;
    }

    // Simulate the gate.
    bool a = !digitalRead(inputA);  // input is in negative logic
    bool b = !digitalRead(inputB);
    digitalWrite(outputA, a);
    digitalWrite(outputB, b);
    digitalWrite(outputRes, gate(a, b));
}

Here is another version, that uses an enum instead of a function
pointer to identify the gate. The constants and the setup() are the
same as before, then:
void loop()
{
    // The gate we want to test.
    static enum { AND, OR, NAND } gate;

    // Select the gate through the serial port.
    switch (Serial.read()) {
        case 'a': gate = AND;  Serial.println("AND");  break;
        case 'o': gate = OR;   Serial.println("OR");   break;
        case 'n': gate = NAND; Serial.println("NAND"); break;
    }

    // Simulate the gate.
    bool a = !digitalRead(inputA);  // input is in negative logic
    bool b = !digitalRead(inputB);
    digitalWrite(outputA, a);
    digitalWrite(outputB, b);
    bool res = false;
    switch (gate) {
        case AND:  res = a && b;    break;
        case OR:   res = a || b;    break;
        case NAND: res = !(a && b); break;
    }
    digitalWrite(outputRes, res);
}


text:
Arduino servo seems to time out after code runs for some amount of time
I am running a simple servo program that swings the servo back and forth, it is essentially pressing a button continuously. However, after some time the servo stops moving and it seems like the code stops. I have no code in the program to tell it to stop and I am uploading from a sketch. Can anyone tell me why the servo will stop after some amount of time? is this some kind of safety or programmatic end that is used when you use the sketch compiler to run code?
Here is my code:
#include <Servo.h>

int servoPin = 9;
Servo servo;

int servoAngle = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    servo.attach(servoPin);
}

void loop() {
    // put your main code here, to run repeatedly:

    int randnum = rand()%(40000-1000 + 1) + 1000;
    int randnumreturn = rand()%(600-350 + 1) + 350;
    servo.write(45);
    delay(randnum);
    servo.write(22);
    delay(randnumreturn);
}

What is your power source?

my laptop, i have the board plugged in through the usb cable used to download code onto the board

How long do you normally have to wait for it to stop? Is your laptop going to sleep?

int in AVR architecture is signed 16 bits. This means 40000 is actually an overflow if it gets assigned to an integer. It would work in most cases, but when the resultant number is > 32767, you would get a minus value, which may cause delay not to work properly.
In order to solve the issue, you may either use long int for randnum or use a random interval smaller than 32768.
Edit: I did some calculation, if you hit exactly 40000 you would delay for 4294974529 milliseconds (+/-1). Any value over 32767 will cause delays that are extremely long.

Actually, 40000 is a long int literal, and the whole expression at the right of = is computed as a long int. The overflow happens when that expression is assigned to int randnum.

I'd suggest you complete your answer by mentioning what to do to solve the problem rather than just explaining it. Here, this is a matter of changing declarations of random and randumreturn to unsigned int.

@EdgarBonet I am clarifying so that it would be understood better.

@jfpoilpret Or using a value less than 32767. I am updating for possible solutions.


text:
How to control 12v water pump by arduino?
I have arduino uno and I've bought 12 Volt/350 GPH Seaflo Electric Bilge Pump, how to control it directly from arduino?

Google for MOSFET and you should find the start of a solution to this problem.

It's not possible to control it directly. You need relay module (better one is with opto coupler).
Or you can use some N-Mosfet like IRF540 with antiparallel fast diode to supress induced high voltage from coil. However arduino output might be weak for fast charge/discharge mosfets gate and it gets hot.


text:
Initialize a class (HX711) within a class with constructor and parameters
I am far from being an Arduino specialist, so please bear with me if some of my code below is far from correct.
I am writing a sketch in which I need to use 3 instances of the HX711 library, as I am using 3 different weight sensors.
In order to try to clean up the code, I want to put basically all the code using HX711 in my own class.
Here is what my ScaleMeasure.h looks like:
// ScaleMeasure.h
#ifndef _SCALEMEASURE_h
#define _SCALEMEASURE_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

#include <CmdMessenger.h>
#include "HX711.h"

class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale = HX711(_dout_pin, _clk_pin);
};

and .cpp
#include "ScaleMeasure.h"

ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;
    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

void ScaleMeasure::Setup()
{
    _scale.power_up();
    _scale.set_scale();
    _scale.set_scale(_calibration_factor);
    _scale.tare();
    _scale.read();
}

float ScaleMeasure::Measure()
{
    return _scale.get_units(5);
}

but there is obviously something wrong, as a call to the constructor lock the rest of the program. I believe that my instantiation, of HX711 in ScaleMeasure.h  HX711 _scale = HX711(_dout_pin, _clk_pin); is not correct, or not in the right place. The code compile fine, though.
Thanks for your help.

The right way, in C++, to properly construct a field member b (of type class B) inside a class A is to do it as follows in A's constructor:
A::A() : b(...) {
    // Other init code here
}

In your situation that would mean:
class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale;
};

Note that I have removed the init part for _scale.
ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
: _scale(Dout, CLk)
{
    _clk_pin = Clk;
    _dout_pin = Dout;
    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

Ha! I tried "something like" this BEFORE asking here, but I may have made an error I did not saw. Thanks, I may get back to this, as it would allow to keep HX711  as is<. Thanks!

Unfortunatly HX711 has no default constructor. So the easiest way would be to add one in the header:
HX711() {} // default constructor, empty

Add member function to do the init job (done by original constructor), also in the header file
    void Init(byte dout, byte pd_sck, byte gain = 128) {
    PD_SCK  = pd_sck;
    DOUT    = dout;

    pinMode(PD_SCK, OUTPUT);
    pinMode(DOUT, INPUT);

    set_gain(gain);
}

Now your ScaleMeasure class will be like (header):
class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale;
};

and cpp
ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;

    _scale.Init(_dout_pin, _clk_pin);

    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

Thanks for this different approach. I'll test and let you know how this goes.

Modifying the code of a library that you use is probably not the best way to solve this problem as it will prevent easy upgrades later on if the library in improved.

It's the solution I choosed, as it's simpler and safe, IMHO. If the need .arise, version control will easily allow to implement eventual modifications

The line
HX711 _scale = HX711(_dout_pin, _clk_pin);

would be executed at construction time, which is the wrong time for it to run since _dout_pin and _clk_pin won't be set. Instead (much as it pains me to recommend it) you will have to use dynamic allocation:
HX711 *_scale;

Then you can, in your constructor:
_scale = new HX711(_dout_pin, _clk_pin);

Since you now have a pointer all your accesses to it need to change to -> instead of .:
_scale->power_up();
... etc ...

Also you should add a destructor to your class that deletes the object pointed to by _scale if it has been created.

I would refrain (at any cost) to introduce dynamic allocation (with new) just to solve a problem related to proper use of the C++ language itself.

There are many ways to skin a cat, all of them perfectly valid and correct. Dynamic allocation is absolutely fine in a memory constrained system as long as it is used "statically" - that is, allocated at init time and not deallocated. Heap fragmentation occurs only when objects are deleted, so if deletion is never needed or used then fragmentation never happens. There still more ways of solving the problem including passing a pointer (or reference) to an HX711 object to the custom class which alleviates the need to pass pins to said class. Like I said - skinning a cat.

I finally decided to add a default constructor to the library. Thanks anyway.


text:
Controlling an OSX app by Arduino
I am trying to control an app on OSX with an Arduino Uno.  Specifically, I would like to start and stop play of an MP3 on iTunes, or a track on Spotify, using an Arduino connected to the Apple computer with USB.
Any suggestions would be greatly appreciated.

This sounds more like an OSX question than an Arduino one.  If the things you want to do can be done by a keyboard, you can get a Leonardo type board and be a keyboard.  Otherwise you will probably need custom software on the Mac which takes custom messages from the Arduino and turns them into actions.  The hard part will be coming up with the Mac side - since it is custom, the Arduino side can be trivial, for example just Serial.println("pause itunes");

You could write a small script that interfaces through serial to the Arduino and forwards commands and instructions on to other places using AppleScript.

@Majenko that is exactly what I'd like to do.  But how?  I suppose I should ask the question on 'Ask Different'?

90% of what you are wanting to do would be Apple programming. Not something we know much about here.

We can help you with the Arduino side of things, but that would just be simple serial operations really.

I am now having Screen output to log.txt, and the following applescript works just great!
set trigger to 1
set stopString to ""
repeat until (stopString = "stop")
set testTxt to paragraphs of (read POSIX file "/Users/fed/log.txt")
set countTxt to (count of testTxt) - 1
set lastLine to item countTxt of testTxt
if lastLine contains "Start MP3" and trigger is 1 then
    tell application "Spotify" to playpause
    set trigger to 0
end if
if lastLine does not contain "Start MP3" then
    set trigger to 1
end if
if lastLine contains "Stop Loop" then
    set stopString to "stop"
end if
end repeat

Applescript can read stuff from a .txt file, and cause an event on a specific word? Then you'll indeed only need a program that takes serial input (USB COM-port) and put it in a file.