body:
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!

title: Building an AtMega328p from Transistors

Answers: 7

body:
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

body:
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)][1]. 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.

  [1]: https://en.wikipedia.org/wiki/Transistor_count

body:
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.

body:
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 [Megaprocessor][]1 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 discussion]: https://www.embeddedrelated.com/showthread/comp.arch.embedded/14362-1.php

[Megaprocessor]: http://www.megaprocessor.com/
[MOS 6502]: https://en.wikipedia.org/wiki/MOS_Technology_6502
[visual6502.org]: http://www.visual6502.org/
[online transistor-level simulator]: http://www.visual6502.org/JSSim/

body:
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!)

body:
> 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).

body: 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


body:
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.

title: Using two software serial - two UART

Answers: 2

body:
> 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.

body:
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](http://www.gammon.com.au/forum/?id=11329).

The general idea is to add some stuff to the DuT (device under test) to output via SPI/I2C.

Example code:

<!-- language: lang-c++ -->

    // 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:

<!-- language: lang-c++ -->

    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:

<!-- language: lang-c++ -->

    // 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:

<!-- language: lang-c++ -->

    // 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.


body:
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][1]

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 !

  [1]: https://i.stack.imgur.com/u32sj.jpg

title: Can't display text on LCD 1602

Answers: 2

body:
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);`

body: 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.


body:
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

title: pH ORP sensor esp12 esp82666

Answers: 1

body:
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


body:
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?

title: code wont upload to arduino starter kit

Answers: 1

body: 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


body: 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.

title: Uno R3's a4 and a5 not working after installing itead SD Shield 3.0

Answers: 1

body:
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!


body:
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.

title: Arduino Saint Smart Chapter 7 Tri Color Module

Answers: 1

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


body:
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.

[![typical ttl ][1]][1]

  [1]: https://i.stack.imgur.com/4DOst.gif

title: Help understanding SoftwareSerial recv() and PCINT

Answers: 1

body:
> 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.


body:
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.

title: WiFi Password Safety

Answers: 2

body:
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* ;)

body:
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](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-123.pdf) 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.


body:
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.

title: Atmega328p - PCB ISP pins for bootloader and sketch upload

Answers: 1

body:
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.


body: 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.

title: Arduino Mega 2560 Only Powers on with USB

Answers: 1

body:
Looking at [this][1] 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][2] 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.

  [1]: https://arduino-info.wikispaces.com/file/view/arduino-mega2560-schematic-F.jpg/346627792/arduino-mega2560-schematic-F.jpg
  [2]: http://reprap.org/mediawiki/images/f/f6/RAMPS1.4schematic.png


body:
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.
----------------------------------------------------------------------
<!-- language-all: c -->

    /*
      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

title: Board and library updates required caused an error

Answers: 1

body: 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.


body:
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][1], 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 [![command prompt][2]][2]

What could be the possible reason for it to fail? Please notify, if anything is missing.

  [1]: https://asensar.com/blog/2013/programming-arduino-using-avrdude/
  [2]: https://i.stack.imgur.com/nWwWW.png

title: Programming arduino using avrdude from command prompt

Answers: 2

body:
    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:

1. You may not have connected your arduino. If this is the case then you please connect the arduino and retry

2.  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.

body:
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.


body:
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`.

title: How do I split a number into individual digits?

Answers: 2

body:
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; //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();
    }

body:
`% 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.


body:
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?

title: Pass templated function as attachInterrupt parameter

Answers: 2

body:
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.

body:
Please have a look implementation
https://github.com/Yurik72/SimpleButton

There are implementation how to assign function with arguments to interrupt handler


body:
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

title: Testing Logic Gates using Arduino

Answers: 2

body:
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).

body:
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);
    }


body:
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);
    }

title: Arduino servo seems to time out after code runs for some amount of time

Answers: 1

body:
`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.


body:
I have arduino uno and I've bought [12 Volt/350 GPH Seaflo Electric Bilge Pump][1], how to control it directly from arduino?

  [1]: https://www.amazon.co.uk/12-Volt-350-GPH-Seaflo-Electric-Bilge/dp/B00OCHCRBC

title: How to control 12v water pump by arduino?

Answers: 1

body:
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.


body:
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][1], 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.

  [1]: https://github.com/bogde/HX711

title: Initialize a class (HX711) within a class with constructor and parameters

Answers: 3

body:
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.

body:
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;
    }

body:
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;
    }


body:
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.

title: Controlling an OSX app by Arduino

Answers: 1

body:
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


body:
I am using [W5100 Ethernet Shield Network Module with arduino Uno ][1]as a webserver to trigger four relays connected to it.

The relays may be toggled through the four buttons attached to it physically, or through the four buttons on the hosted webpage. There is a counter how many times the relays are toggled which can be reset through a button on the webpage.

My issue is, whenever I toggle the relay through physical button, it does not update the counter on the webpage. And if I refresh the page, the last command from the page, such as togglerelay1 keeps echoing.

What solution do you propose to this problem:

    #include <SPI.h>
    #include <Ethernet.h>

    int Relay1 = 2;
    int Relay2 = 3;
    int Relay3 = 4;
    int Relay4 = 5;
    int Button1 = 8;
    int Button2 = 9;
    int Button3 = 10;
    int Button4 = 11;

    String on = "On";
    String off = "Off";

    String Relay1Status = on;
    String Relay2Status = on;
    String Relay3Status = on;
    String Relay4Status = on;

    int count1 = 0;
    int count2 = 0;
    int count3 = 0;
    int count4 = 0;

    byte toggle1 = LOW;
    byte toggle2 = LOW;
    byte toggle3 = LOW;
    byte toggle4 = LOW;

    void toggleRelay1();
    void toggleRelay2();
    void toggleRelay3();
    void toggleRelay4();

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
    byte ip[] = { 172, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
    byte gateway[] = { 172, 168, 1, 1 };                   // internet access via router
    byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
    EthernetServer server(80);                             //server port
    String readString;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
      pinMode(Relay1, OUTPUT);
      pinMode(Relay2, OUTPUT);
      pinMode(Relay3, OUTPUT);
      pinMode(Relay4, OUTPUT);
      pinMode(Button1, INPUT_PULLUP);
      pinMode(Button2, INPUT_PULLUP);
      pinMode(Button3, INPUT_PULLUP);
      pinMode(Button4, INPUT_PULLUP);
      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip, gateway, subnet);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {

      if (digitalRead(Button1) == LOW) {
        toggleRelay1();
        while (digitalRead(Button1) == LOW);
      }
      if (digitalRead(Button2) == LOW) {
        toggleRelay2();
        while (digitalRead(Button2) == LOW);
      }
      if (digitalRead(Button3) == LOW) {
        toggleRelay3();
        while (digitalRead(Button3) == LOW);
      }
      if (digitalRead(Button4) == LOW) {
        toggleRelay4();
        while (digitalRead(Button4) == LOW);
      }

      // Create a client connection
      EthernetClient client = server.available();
      if (client) {
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();

            //read char by char HTTP request
            if (readString.length() < 100) {
              //store characters to string
              readString += c;
              //Serial.print(c);
            }

            //if HTTP request has ended
            if (c == '\n') {
              Serial.println(readString); //print to serial monitor for debuging
              homepage();
              //controls the Arduino if you press the buttons
              if (readString.indexOf("?resetcount1") > 0) {
                count1 = 0;
              }
              if (readString.indexOf("?resetcount2") > 0) {
                count2 = 0;
              }
              if (readString.indexOf("?resetcount3") > 0) {
                count3 = 0;
              }
              if (readString.indexOf("?resetcount4") > 0) {
                count4 = 0;
              }
              if (readString.indexOf("?togglerelay1") > 0) {
                toggleRelay1();
              }
              if (readString.indexOf("?togglerelay2") > 0) {
                toggleRelay2();
              }
              if (readString.indexOf("?togglerelay3") > 0) {
                toggleRelay3();
              }
              if (readString.indexOf("?togglerelay4") > 0) {
                toggleRelay4();
              }
            }
          }
        }
      }
      //clearing string for next read
      readString = "";

    }

    void toggleRelay1() {
      toggle1 = !toggle1;
      digitalWrite(Relay1, toggle1);
      if (toggle1 == HIGH) {
        count1++;
        Relay1Status = on;
      }
      else
        Relay1Status = off;
    }

    void toggleRelay2() {
      toggle2 = !toggle2;
      digitalWrite(Relay2, toggle2);
      if (toggle2 == HIGH) {
        count2++;
        Relay2Status = on;
      }
      else
        Relay2Status = off;
    }

    void toggleRelay3() {
      toggle3 = !toggle3;
      digitalWrite(Relay3, toggle3);
      if (toggle3 == HIGH) {
        count3++;
        Relay3Status = on;
      }
      else
        Relay3Status = off;
    }

    void toggleRelay4() {
      toggle4 = !toggle4;
      digitalWrite(Relay4, toggle4);
      if (toggle4 == HIGH) {
        count4++;
        Relay4Status = on;
      }
      else
        Relay4Status = off;
    }

    void homepage() {
      client.println("HTTP/1.1 200 OK"); //send new page
      client.println("Content-Type: text/html");
      client.println("Connection: Close");
      client.println();
      client.println("");
      client.println("");
      client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
      client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
      client.println("<link rel='stylesheet' type='text/css' href='http://randomnerdtutorials.com/ethernetcss.css' />");
      client.println("<TITLE>Relay Control System</TITLE>");

      client.println("");
      client.println("");
      client.println("
Relay Control System
");
      client.println("
");
      client.println("
");

      client.println("
Relays Status
");
      client.println("
");

      client.println("Relay 1 Status: ");
      client.println(Relay1Status);
      client.println("
");

      client.println("Relay 2 Status: ");
      client.println(Relay2Status);
      client.println("
");

      client.println("Relay 3 Status: ");
      client.println(Relay3Status);
      client.println("

");

      client.println("Relay 4 Status: ");
      client.println(Relay4Status);
      client.println("

");

      client.println("Number of times Relay1 has been activated: ");
      client.println(count1);
      client.println("Reset Counter");
      client.println("

");

      client.println("Number of times Relay2 has been activated: ");
      client.println(count2);
      client.println("Reset Counter");
      client.println("

");

      client.println("Number of times Relay3 has been activated: ");
      client.println(count3);
      client.println("Reset Counter");
      client.println("

");

      client.println("Number of times Relay4 has been activated: ");
      client.println(count4);
      client.println("Reset Counter");
      client.println("

");

      client.println("Toggle Relay1");

      client.println("Toggle Relay2");

      client.println("Toggle Relay3");

      client.println("Toggle Relay4");

      client.println("");
      client.println("");

      delay(1);
      //stopping client
      client.stop();
    }

  [1]: https://www.amazon.com/Qunqi-Ethernet-Network-Starter-Arduino/dp/B015SCPCIE/ref=sr_1_3?ie=UTF8&qid=1469977802&sr=8-3&keywords=qunqi uno r3 board kit

title: Webserver on Arduino: Refresh issues

Answers: 1

body:
Instead of always responding with the `homepage()` for every request you should respond specially to the command requests with a `307` temporary redirect code to make the browser request the index page afresh

    client.println("HTTP/1.1 307 Temporary Redirect");
    client.println("Location: /");
    client.println("Connection: Close");
    client.println();
    client.stop();

So the client gets `/?togglerelay3`, which happens, and then gets sent a reply telling it to `make a new request to get /` which it then does to get the new status. The URL in the browser will not have the `?togglerelay3` in it, so refreshing won't cause the command to be run again.

If you want live updating of the page with new count values as they happen you will have to be more cunning. Either use AJAX and JavaScript in the page to fetch new values to display, or periodically refresh the page (with a [META Refresh](https://en.wikipedia.org/wiki/Meta_refresh)).


body:
I originally asked this [question.][1] Regarding a webserver Refresh issue on arduino.

I am totally new to web development and ethernet. The answer from @Majenko is correct, but I do not understand how to implement it. Should I change the `homepage()` function's first line to `HTTP/1.1 307 temporary redirect` and use `META REFRESH`?

Or do the `homepage()` first using `HTTP/1.1 200 OK` and then for all the following requests, use `HTTP/1.1 307 temporary redirect`?

  [1]: https://arduino.stackexchange.com/questions/28124/webserver-on-arduino-refresh-issues?newreg=fec67955f67e4baea0fc7402e8cb57da

title: Webserver on Arduino: How to 307 temporary redirect

Answers: 1

body:
You need to make a decision on what to respond with depending on what the request is you have received.

If you receive a "command" URL (which you already check for by looking for certain sub-strings) then you need to respond with the `307` response. If you don't receive a "command" URL (so anything *except* the things you are specifically looking for) then you respond with the homepage.

A slight re-formatting of your decision code to use `else if` instead of just `if` would make it easier:

    if (c == '\n') {
      Serial.println(readString); //print to serial monitor for debuging
      // homepage(); << This is now moved elsewhere.
      //controls the Arduino if you press the buttons
      if (readString.indexOf("?resetcount1") > 0) {
        count1 = 0;
        redirect();
      } else if (readString.indexOf("?resetcount2") > 0) {
        count2 = 0;
        redirect();
      } else if (readString.indexOf("?resetcount3") > 0) {
        count3 = 0;
        redirect();
      } else if (readString.indexOf("?resetcount4") > 0) {
        count4 = 0;
        redirect();
      } else if (readString.indexOf("?togglerelay1") > 0) {
        toggleRelay1();
        redirect();
      } else if (readString.indexOf("?togglerelay2") > 0) {
        toggleRelay2();
        redirect();
      } else if (readString.indexOf("?togglerelay3") > 0) {
        toggleRelay3();
        redirect();
      } else if (readString.indexOf("?togglerelay4") > 0) {
        toggleRelay4();
        redirect();
      } else { // If none of them match then send the homepage.
        homepage();
      }
    }

`redirect()` is as simple as:

    void redirect() {
      client.println("HTTP/1.1 307 Temporary Redirect");
      client.println("Location: /");
      client.println("Connection: Close");
      client.println();
      client.stop();
    }


body:
I've been using Arduino UNO for quite sometime and brought a new Arduino Nano. When I connected it to my computer, the power usb lit up and the blink sketch started running ( as expected of course).

Now I opened up the IDE and switched boards. But when I try to upload code to my Nano I get an error-

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

Clearly the IDE can't see my board. Uploading to my UNO goes fine. The serial port option is greyed out so I can't change it.

I have searched extensively online for a solution and have found none. This must be either a very unique issue or a very simple one.

title: Cannot upload sketch to Arduino Nano

Answers: 4

body:
Firstly, you have a clone not a genuine Arduino Nano. They use a different USB chip and require different drivers. Install the CH340 drivers.

Secondly your cable is bad. It sounds like one with no data wires in it used for powering or charging small low-powered devices like bluetooth headsets etc. Replace the cable with a proper one.

body:
I don't really see a question in the OP, but here is the immediate answer:

Go into Control Panel..Device manager.  Open the Ports (COM & LPT) and see what you have.  It should be listed.

If it is a CH340 port it will just give a COMx number.

If you have the genuine article then it will actually say so and give you the COMx number to use.

If no COM ports show then try switching out the cable.  Power cycle the Arduino and try again.

There aren't that many moving parts in this, but sometimes, Windows gets confused and a Windows reboot might be necessary.  That usually only happens if you unplug and replug the Arduino too many times for Windows to keep track of.

body: When using a cheap knockoff Nano, it seems that in the newer versions of the Arduino IDE (at least in 1.8.8), you may need to select "ATmega328P (Old bootloader)" from the Processor options under the Tools menu in order to upload sketches.

body: I've seen this error a few times and renaming the serial port fixed the problem in my case. I documented the steps in detail in Tip #4 of this blog post: https://gyorgybalassy.wordpress.com/2020/10/16/cant-open-device-com-access-is-denied-arduino-upload/


body:
I am trying to both send and receive data using bluetooth module.

Receiving data works fine with this code:

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

    void loop() {
        if (Serial1.available()) {
            Serial.println(Serial1.read());
        }

        delay(20);
    }

But I cannot send any data. This is what I am doing:

    void loop() {
        if (Serial1.available()) {
           Serial.println(Serial1.read());
        }

        delay(20);

        if (digitalRead(bluetoothInput) == HIGH) {
            Serial1.write("2");
            // only "send" prints. Nothing in android terminal
            Serial.println("send!");
            delay(1000);
        }

        delay(20);
    }

What am I doing wrong?

I am using Arduino Leonardo and Bluetooth terminal app on Android device.

title: Sending data via bluetooth

Answers: 1

body:
I've found the problem

It should be:

    Serial1.println("2");

instead of:

    Serial1.write("2");


body:
I declared my enum and called it Dir. I wanted to use value of that type in my function Move(). Here's the code:

    enum Dir
    {
      forward = 1,
      backward = 2,
      left = 3,
      right = 4
    };

    void Move ( Dir direction , int distance )
    {
         direction = forward;
    }

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

    }

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

    }

Unfortunately i get the following errors:

    V2.ino:23:13: error: variable or field 'Move' declared void
    V2.ino:23:13: error: 'Dir' was not declared in this scope
    V2.ino:23:29: error: expected primary-expression before 'int'

What's wrong?

title: Can't use enum as function argument

Answers: 4

body:
I did not experience the problem because I usually use a Makefile instead of
the Arduino IDE. I now tried with the IDE version 1.0.5 and I had the same
problem as you. The fix is to explicitly declare the function before
defining it:

<!-- language: lang-c++ -->

    void Move(Dir direction, int distance);
    void Move(Dir direction, int distance)
    {
         direction = forward;
    }

body:
The Arduino 1.7.x series from Arduino.org uses the old build system that is severely broken when you try and do anything more complex than simple types.

It adds prototypes to your functions to the top of the program so you don't have to get the order right, but it puts them in completely the wrong place.  The result is a C++ file that looks like this:

    #include <Arduino.h>
    void Move ( Dir direction , int distance );
    void setup();
    void loop();

    enum Dir
    {
      forward = 1,
      backward = 2,
      left = 3,
      right = 4
    };

    void Move ( Dir direction , int distance )
    {
         direction = forward;
    }

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

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

As you can see the prototype involving `Dir` has been placed before the definition of `Dir`, and so it fails miserably.

There are some hacks you can do to force it to place the prototypes after your definition, but I can't recall what they are off hand.

The simple answer is to ditch Arduino 1.7.10 and switch to Arduino 1.6.10 from Arduino.cc instead. This uses the Arduino Builder system which does things much better, including placing the prototypes in the right place.

Despite the numbering 1.7.10 is not a newer version than 1.6.10 - it is an older version renumbered. It's all part of the schism between the two halves of Arduino.

Even better is to ditch the awful Arduino IDE entirely and use one of the many far better IDEs that exist.

body:
You have to define a new enum type:

    typedef enum
    {
      forward = 1,
      backward = 2,
      left = 3,
      right = 4
    } Dir;

    void Move ( Dir direction , int distance )
    {
         direction = forward;
    }

without `typedef` your Dir is just static enum variable, it can't be used to define other vars.

body:
As Majenko points out, this seems to be a problem with the parsing of the preprocessor.

You have two options:

Use Edgar Bonets solution and declare the function before defining it

Create a separate header file for your enum in a new tab and import it with #include "[myEnumsHeaderFilename].h"

    #include "myEnums.h"

    void Move(Dir direction, int distance)
    {
       direction = forward;
    }

    void setup() {}

    void loop() {}


body:
I hope I can get some help on how to get this to work.

I have multiple Sensors (32 of these) which values I want to read. I am using a master multiplexer **HC4051** connected to 4 slave multiplexers, this is my wiring:
[here][1]

I tested it using one single multiplexer and it works as intended, but when adding the slave I cannot getting it to work, I am not sure how to code for it.

When using this code:

    // 74XX4051 ADDRESS PINS :
    #define  M_S0 2
    #define  M_S1 3
    #define  M_S2 4

    #define  S_S0 7
    #define  S_S1 6
    #define  S_S2 5

    // 74XX4051 ANALOG PIN :
    #define  Z 0

    void setup() {
        // CONFIGURE ADDRESS PINS
        pinMode(M_S0, OUTPUT);
        pinMode(M_S1, OUTPUT);
        pinMode(M_S2, OUTPUT);

        pinMode(S_S0, OUTPUT);
        pinMode(S_S1, OUTPUT);
        pinMode(S_S2, OUTPUT);

        // CONFIGURE SERIAL
        Serial.begin(57600);
    }

    void loop() {
        int value;

        // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
        for ( byte count = 0; count < 4 ; count++ ) {
             // SET THE ADDRESS
             digitalWrite(M_S0, bitRead(count, 0) );
             digitalWrite(M_S1, bitRead(count, 1) );
             digitalWrite(M_S2, bitRead(count, 2) );

             // LOOP THROUGH ALL THE ADDRESSES OF THE SLAVES
             for ( byte count_1 = 0; count_1 < 32 ; count_1++ ) {
                 digitalWrite(S_S0, bitRead(count_1, 0) );
                 digitalWrite(S_S1, bitRead(count_1, 1) );
                 digitalWrite(S_S2, bitRead(count_1, 2) );

                 // READ THE ANALOG VALUE
                 value = (bitRead(count_1, 2), bitRead(count_1, 1), bitRead(count_1, 0));
             }

             // READ THE ANALOG FOR THE MASTER ADRESSE
             value = analogRead(Z);

             // SERIAL OUTPUT
             // print : ### value
             Serial.print(bitRead(count, 2));
             Serial.print(bitRead(count, 1));
             Serial.print(bitRead(count, 0));
             Serial.print(' ');
             Serial.println(value);

             delay(100);
         }
    }

I am only getting random readings really (the reading LED for the moisture sensor does not switch on when the reading is done).

What I am doing wrong? Any help is appreciated.

**UPDATE:**

i updated my code as follows :

    // Master moisture sensor pins
    #define  M_S0 7
    #define  M_S1 8
    #define  M_S2 9
    // Slave moisture sensor pins
    #define  S_S0 4
    #define  S_S1 5
    #define  S_S2 6

    // PIN from the transistor to power the sensors only when doing a reading
    int sensorVCC = 13;

    //  ANALOG PIN :
    #define  Z 0

    void setup() {
        Serial.begin(9600);
        // CONFIGURE ADDRESS PINS
        pinMode(M_S0, OUTPUT);
        pinMode(M_S1, OUTPUT);
        pinMode(M_S2, OUTPUT);

        pinMode(S_S0, OUTPUT);
        pinMode(S_S1, OUTPUT);
        pinMode(S_S2, OUTPUT);
        pinMode(sensorVCC, OUTPUT);

        digitalWrite(sensorVCC, LOW);
    }

    void loop() {

        // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
        for (int i = 0; i < 32; i++) {
        digitalWrite(sensorVCC, HIGH);
        delay(100); //make sure the sensor is powere

        digitalWrite(M_S2, i & 0b100000);
        digitalWrite(M_S1, i & 0b010000);
        digitalWrite(M_S0, i & 0b001000);
        digitalWrite(S_S2, i & 0b000100);
        digitalWrite(S_S1, i & 0b000010);
        digitalWrite(S_S0, i & 0b000001);

        delay(1);

        int humidityRaw = analogRead(Z); // 1023 to 0 ===> 0 to 100%
        int humidityReal = map(humidityRaw, 975, 523, 0, 100);
        digitalWrite(sensorVCC, LOW);

        Serial.print("Input ");
        Serial.print(i);
        Serial.print(": ");
        Serial.print(humidityReal);
        Serial.println(" % ");
        delay(1000);
    }
    }

and this is my output :

        Input 0: 100 %
        Input 1: 0 %
        Input 2: 100 %
        Input 3: 0 %
        .
        .
        .
        Input 0: 0 %
        Input 1: 100 %
        Input 2: 0 %
        Input 3: 0 %
        .
        .
        .
        Input 0: 100 %
        Input 1: 0 %
        Input 2: 0 %
        Input 3: 0 %
        .
        .
        .

ONLY channel 0 is hooked !! .... it seems that it reads with different delays. changing the delay gives me different sequence. what is wrong ?

title: How to code for cascading multiplexers?

Answers: 2

body:
It becomes much easier if you start thinking in binary.

If you have an 8 bit multiplexer connected to four 8 bit multiplexers that gives you 32 inputs. Four of the inputs on the "master" multiplexer are unused and can be ignored.

You have 32 inputs. That's inputs numbered 0 to 31. In binary that equates to, in full,

    0 = 000000   8 = 001000  16 = 010000  24 = 011000
    1 = 000001   9 = 001001  17 = 010001  25 = 011001
    2 = 000010  10 = 001010  18 = 010010  26 = 011010
    3 = 000011  11 = 001011  19 = 010011  27 = 011011
    4 = 000100  12 = 001100  20 = 010100  28 = 011100
    5 = 000101  13 = 001101  21 = 010101  29 = 011101
    6 = 000110  14 = 001110  22 = 010110  30 = 011110
    7 = 000111  15 = 001111  23 = 010111  31 = 011111

I have laid it out like that especially so that you see a pattern occurring. Four columns with 8 rows. Four slave multiplexers with 8 inputs. A perfect match. Each column has bits that are distinct to that column. Each row has bits that are unique to that row.  So you could split those bits up and know that the left-hand three bits indicate the column, and the right-hand three bits indicate the row. Between the two it's a unique location in the table.

The same applies to the multiplexers.  The left-hand three bits indicate which slave multiplexer to use, the right-hand three bits which input to use on the selected multiplexer.

So you can loop through each of the 32 inputs with a single loop and examine the individual bits of the input number and apply those bits directly to the select outputs to control the multiplexers - the left-hand bits to the master to select which slave to use, and the right-hand bits to the slaves to select which input to use.

So you have:

    for (int i = 0; i < 32; i++) {
        digitalWrite(M_S2, i & 0b100000);
        digitalWrite(M_S1, i & 0b010000);
        digitalWrite(M_S0, i & 0b001000);
        digitalWrite(S_S2, i & 0b000100);
        digitalWrite(S_S1, i & 0b000010);
        digitalWrite(S_S0, i & 0b000001);

        delay(1);

        int reading = analogRead(Z);
        Serial.print("Input ");
        Serial.print(i);
        Serial.print(": ");
        Serial.println(reading);
    }

The `i & 0b000001` etc performs the same function as `bitRead()` but is more explicit using a mask that is far more visual as to what it achieves.

I also include a tiny delay after setting the multiplexers up so as to ensure they have settled into their new settings properly before reading. It shouldn't be needed, but it doesn't hurt.

body:
I think that you have confused your address *encoding* in your code. Your complete address space is only a total of 5 bits, decimal 0 to 31. Your two loops (`for ( byte count = 0; count < 4 ; count++ )` and `for ( byte count_1 = 0; count_1 < 32 ; count_1++ )`) are actually counting through a 7 bit address space, just with the 3 MSBs of the inner loop being ignored.

For your 32-input example, I'm going to assume that the master 4051 only has inputs A-D (`y0` to `y3`) connected to downstream muxes and that the analog mux decodes based on the binary value of the input select. Then your digital outputs should correspond to, for `byte address` as your counter:

- `S_S0` -> `bitRead(address, 0)` (LSB)
- `S_S1` -> `bitRead(address, 1)`
- `S_S2` -> `bitRead(address, 2)`
- `M_S0` -> `bitRead(address, 3)`
- `M_S1` -> `bitRead(address, 4)`
- `M_S2` -> constant `0` (MSB)

Thus, your test should only use a `for ( byte address = 0; address < 32 ; address++ )` to acquire data from all 32 possible inputs. Remember to have a long enough delay from selecting a different multiplexer input to starting your ADC conversion to avoid errors due to signal settling.

Additionally, you should be calling only one analog read location corresponding to the pin connected to the `AnalogInPin` in the schematic. You will have to record what the current multiplexer selection to determine which of the 32 inputs is actually being recorded by that conversion. Basically, there's only one 'master" analog input.

Your use of `value = (bitRead(count_1, 2),bitRead(count_1, 1),bitRead(count_1, 0));` is confusing and seems incorrect. After you `digitalWrite()` the new address for your multiplexers, you shouldn't need to read-back the digital pins to know what address you have selected.


body:
I am writing a software that runs on the PC that has a Arduino 2560 connected to it via USB. This PC needs to communicate with multiple devices through RS232.

Is it possible to use the Arduino's 4 UARTs to communicate with 4 different hardware that uses RS232 serial communication, using just 1 USB connection between the PC and the Arduino 2560?

The Arduino 2560 will basically act as an interface for 1 USB to talk to 4 RS232 devices.

title: Arduino 2560 as an Interface to 4 Serial Hardwares

Answers: 2

body:
No, but it is possible to use 3 of them. The reason being that one of them is the connection to the computer.

The hard part is in the programming. You will need not only a suitable sketch on the Arduino (the easy part), but also some software on your computer that presents three COM ports to the operating system and forwards the data through to the Arduino in a suitably packeted format, and receive data back and sent it on to the right COM port.  Depending on your operating system that may be a very easy task (on Linux and OS X) or a complete and utter nightmare (Windows).

body:
In Arduino terms:

Serial will be committed to receiving data from the PC.

Connecting Serial1, Serial2, and Serial3 via RS232 will be easy.

Adding a 4th Software Serial (or NewSoft Serial or AltSoft Serial) via RS232 will also be straightforward. If you need high speeds for the 4th port, than a UART with SPI (or I2C) interface to the Mega might be a better idea.

The only tricky part is putting in some info in the data from the PC so the Mega can re-send it to the correct port.


body:
Is it possible to connect to an Arduino 2560 using a RS232 (DB9) connection rather than the regular connection using USB cable?

I am thinking of this connection scheme:

    PC -> USB cable -> USB to RS232 Multiplexer -> DB9 Cable -> Adapter board -> Arduino 2560

title: Connect to Arduino 2560 using a RS232 Connection

Answers: 1

body:
Yes, perfectly possible.  You need an RS-232 interface chip - the most common and well-known of these is the MAX232. You can get them as breakouts on eBay.

That interfaces between the DB9 and pins 0/1 (or other UART comms pins) on the Arduino.

If you are wanting to program the board through it you will also need to connect (after converting the voltage through the MAX232) the DTR line to RESET through a 100nF capacitor.

... Exactly like you would with a breadboard Arduino.


body:
I'm looking for a mechanical component that enables me to do two things:

 - contain a gas in a bottle and if opened, the gas should smoothly flow out (with the same pressure as a child blowing out candles on his birthday cake)
 - a valve for the bottle that can be opened by an Arduino when powered via USB

I already figured out that there are outlets for CO2 capsules. This could work, but then I'd need to figure out a way to decrease the pressure in order to receive a gentle gas flow.

Do you know any better approaches? Thanks in advance!

title: Releasing gas from a bottle via Arduino - opening a valve?

Answers: 2

body: If you can tolerate a decreasing flow as the pressure in the bottle drops, a simple restrictor (fluidic equivalent of a resistor) will limit the flow but of course, I = E/R; the flow will be proportional to the bottle pressure. If that is acceptable, it is probably the cheapest, simplest, and most reliable way.

body:
You can use the product "electronic expansion valve" to control gas, also you can control valve openness degree this is optional, then put in CO2 capsules closed box also add air pressure sensor in the box, air pressure sensor controls valve to set up gas pressure, make one hole to box the gas out from here thereafter measure the pressure what you want.
Also do you need a mechanic component to control CO2 capsule?


body:
I am working on a project, where i need to control the flow of a liquid made from food.

For example: making chicken curry, I will separate all the liquid from the meat, and run that tough a pipe, where this control pipe is on.

But I have been unable to find a subtle valve for this, as the liquid on all of them will flow tough the mechanics of the valve, and this would not be optimal as it would make it impossible to clean, and it would diffidently get stuck.

Can one of you suggest a valve that would work for this case?

title: Water valve for food

Answers: 1

body:
I would suggest, instead of a valve, a [Peristaltic Pump](https://en.wikipedia.org/wiki/Peristaltic_pump).

In short, it comprises a set of rollers that squeeze a flexible tube and push the fluid along. It has good advantages for food use:

* Very easy to clean - only the inside of the tube needs cleaning
* Pumped fluid is not in physical contact with the pump mechanism so can't be contaminated.

They are used in many sterile environments - medical, industrial, etc., because they are so easy to keep clean and have no way of contaminating the pumped fluid. They are also good with viscous (sticky, gloopy) fluids like soups and sauces.

They can also deliver precisely measured amounts very easily.


body:
I am running Ubuntu Mate 16.04 LTS, with an Arduino Uno R3 clone. I am having the dreaded serial port graying out problem, and have not found a solution for fixing it. Currently, The serial port will grey out sometimes, and sometimes it will be not grayed out, and I can see that I have selected ttyUSB0. Usually when it is not grayed out, uploading a sketch will not work, and I get the error like it is grayed out:

> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
An error occurred while uploading the sketch

    chmod a+rw /dev/ttyUSB0
doesn't solve the issue, with log out included

    gpasswd -a aaron dialout
doesn't solve the issue, with log out included

I searched preferences.txt and serial.debug rate is set to 9600

I have tried entering preferences.txt and deleting all of the serial entries. They are recreated the same after deletion, and this doesn't solve anything.

I tried running as sudo, doesn't work.

I tried solving this originally on Arduino IDE 1.0, didn't work.

I have upgraded to Arduino IDE 1.6.10, still not working.

running lsusb in terminal yields this while Arduino is plugged in:

    Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 001 Device 003: ID 0a5c:21e6 Broadcom Corp. BCM20702 Bluetooth 4.0 [ThinkPad]
    Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Checking var/log/syslog after plugging in Arduino:

>kernel: [42043.787178] usb 3-2: new full-speed USB device number 109 using xhci_hcd

>kernel: [42043.916241] usb 3-2: New USB device found, idVendor=1a86, idProduct=7523

>kernel: [42043.916249] usb 3-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0

>kernel: [42043.916253] usb 3-2: Product: USB2.0-Serial

>kernel: [42043.916964] ch341 3-2:1.0: ch341-uart converter detected

>kernel: [42043.918199] usb 3-2: ch341-uart converter now attached to ttyUSB0

>mtp-probe: checking bus 3, device 109: "/sys/devices/pci0000:00/0000:00:14.0
/usb3/3-2"

>mtp-probe: bus: 3, device: 109 was not an MTP device

Ran to add to dialout group, then logged out

    sudo usermod -a -G dialout aaron

No solution.
So it looks like Arduino board is not being recognized. Not sure what to try next. It is important that I have uploaded sketches before, but am not sure if there is a pattern to when it does not work. It does not work 95% of the time.

Thanks for the help!

title: Serial Port greyed out Ubuntu 16.04

Answers: 1

body:
I have the same problem,
I believe that the problem is related to the 4.x kernel, since I have already tried another distribution with the kernel mermo and the problem persists. Using a windows virtual machine as guest works, which excludes communications and hardware issues.


body:
As part of the research I am involved with, the detection (not imaging) of UV (ultraviolet) sources, either emitters or reflectors is an important factor.

I am aware of the [SparkFun UV Sensor Breakout - ML8511][1] component, which, according to the [product specifications][2], has a decent broadband response across the UVA and UVB, with little amount of visible light.

Is there an Arduino component that only detects the UVB waveband (280nm to 320nm)?

  [1]: https://www.sparkfun.com/products/12705
  [2]: https://cdn.sparkfun.com/datasheets/Sensors/LightImaging/ML8511_3-8-13.pdf

title: UVB sensing with Arduino

Answers: 1

body:
The SparkFun board you mentioned should detect UVB and UVA, but I guess, from your question, that you want one that cannot detect UVA.

Basically any device that has an I2C interface *should* work with an Arduino as long as you know how to interface with the device in the code.

If your intention is professional research, than a demo device such as the SparkFun may not fit your needs anyway as it will not be particularly accurate and is mainly intended as a little board to play about with on your Arduino and say "Hey, look, there's UV light there!"

The answer to your question is that the best place to look is above the consumer range, at some higher-end UV sensors that are not generally suitable for the little Arduino demos due to price, but may give you much more accurate readings and only sense the UVB waveband.


body:
my project involves:
1 ultrasonic sensor.
1 servo motor.
3 leds.
when a person comes in range of ultrasonic sensor (7 to 20),servo turns by 150 degree.
then ultrasonic sensor check again if the person is in range, if yes then led1 turns on for 10sec n turns off, still if the person in in range then led2 turns on for 10sec and turns off, still if the person is in range then led3 turns on for 10sec and this keep on repeating for the leds(led1, led2, led3 but servo is still in 150)
once detected and the person is not detected the leds should not glow and servo should return to 0

code:

    if ((distance1>7)&&(distance1 <= 20))
     {
      myservo1.write(150);
      delay(1000);
     }
     {
      if ((distance2>7)&&(distance2 <= 20))
       {
       digitalWrite(led1,HIGH);
       delay(1000);
       digitalWrite(led1,LOW);
       }
      if ((distance1>7)&&(distance1 <= 20))
       {
       digitalWrite(led2,HIGH);
       delay(1000);
       digitalWrite(led2,LOW);
       }
       if ((distance1>7)&&(distance1 <= 20))
       {
       digitalWrite(led3,HIGH);
       delay(1000);
       digitalWrite(led3,LOW);
       }
    else
    {
     myservo1.write(0);
      }

but this code does not work the way i want.
it blink the leds even when there is no person in range.
need help in programing so that the leds blink only when ultrasonic detects the person in range and stops when person is not detected.
thank u in advance

title: help with arduino programming

Answers: 1

body:
Your indenting doesn't match your code.

Right after the very first `if` (without an `else`), you have a new open brace (`{`). This looks wrong:

    if ((distance1>7)&&(distance1 <= 20))
     {
      myservo1.write(150);
      delay(1000);
     }
     { // <<<< What is this?

The very very final `else` matches the very very final `if` - certainly not the first `if`!

Also, what is the difference between `distance1` and `distance2`? You only have one ultrasonic sensor - there is only one `distance`!

### EDIT:

I think what you need to do is use `loop()` more effectively. At the moment, you're pausing in the middle of your code, rather than letting the rest of the code work and using `millis()`. That function returns the number of milliseconds since the program started - which you can use for your problem (with a little mathematics):

### EDIT 2:
I've added a little extra code to play different tunes depending on the current state. It uses the library at http://www.rhydolabz.com/other-widgets-c-205_124/mini-mp3-player-module-p-2159.html

    static unsigned lastMilli = 0;
    static byte lastLED = 0;
    static const byte LEDs[] = { led1, led2, led3 };

    distance1 = // Whatever you call to get the distance...
    if (distance1>7) && (distance1<=20)) { // Too close?
       if (lastMilli==0) {       // Is this new???
           lastMilli = millis(); // Yes! Record that...
           mysero.write(150);    // ...and set servo.
       } // if
       unsigned delay = millis() - lastMilli; // Get how long it's been
       byte which = delay / 10000 % 3;        // Which LED / tune?
       byte LED = LEDs[which];                // Which LED?
       if (LED != lastLED) {                  // Has LED changed?
           if (lastLED!=0) {
               digitalWrite(lastLED, LOW);    // Yes! Stop that one
           } // if
           mp3_single_loop(true);             // Play forever!
           mp3_single_play(which+1);          // Play "mp3/000#.mp3"
           lastLED = LED;
           digitalWrite(LED, HIGH);           // And start the new one
       } // if
    } // if
    else if (lastMillis!=0) { // They're gone!
        digitalWrite(lastLED, LOW); // No LED
        myservo.write(0);           // No servo
        lastMilli = 0;              // So start again
        lastLED = 0;
        mp3_stop();
    } // else