text:
Problem with running 2 DC motors with ultrasonic sensor
I'm not expert in electrical circuits, maybe I am making a very simple mistake or missing some basic points with my circuit.
What I'm trying to achieve is simple, to run 2 DC motors with an ultrasonic sensor to detect obstacles and change direction. When I unplug the ultrasonic sensor everything is working fine as expected without obstacle detection but when I connect the ultrasonic sensor, sensor always responds with 0 cm distance. Then I removed 9 V battery from the circuit and plug Arduino to computer via USB, sensor works fine but motors are not working properly, it looks like the power from USB is not enough to drive motors at the same time. I've added my circuit scheme below:

Measure the voltage (Vin, 5V, 3V). Check the power consumption for the motors. What type of 9V battery? Can it provide the power required? By measuring the voltage drop you might get a better understand of the issue(s).

Thank you Mikael, I will check the values. Between the power source is a standard Duracell 9v battery.

A 9V battery may have a hard time providing power for both the motors and the board. You might need to rethink this. Or at least use a separate battery for the board.

How (acoustically) loud are the motors?  If they're the typical RC car motors, they can screech harmonics right up into the 40 KHz range typical of ultrasound ranging sensors, interfering with the sensor's ability to work at all.
How (electrically) loud are the motors?  If RC as above, they throw all sorts of transients onto the power lines (and everything else within electrical pickup range).  You might want to put some ceramic capacitors across the motor leads to absorb some of those transients.
Kudos for the suggestions to provide separate power supplies for the motors and the Arduino / sensor combination.  I'd go even further, and provide separate power for all three, and use opto-isolators for the connection between the ultrasound and the Arduino.
Some years ago I used two Novak Super-Rooster motor drivers for a battle-bot competition.  They were driven by PWM outputs of an Arduino, where 50% duty cycle was off, 0% was full speed reverse, and 100% was full speed ahead.  These were powered by a sealed lead acid battery, and driven full-out, the motors got +/- 12VDC at about 40 amps.  There was a common ground with the Arduino, going to the Super Roosters, but not the motors, and the drivers took care of the electrical shielding, with a little help from the ceramic bypass capacitors I mentioned.  Worked great!

Thank you for your detail explanation. I think you hit a good point with the high frequency sound issue. I'll look for ceramic capacitors etc. and let you know about my progress.


text:
Sending data from Arduino UNO as a SOAP request
I have a servo motor on one end which can be turned ON and OFF with web service sending SOAP request. In the other end I have my Arduino UNO with ESP8266. Currently, I am able to send HIGH or LOW status from my Arduino to ESP8266.
My query is: After receiving the status "HIGH" from Arduino to ESP8266, I need to POST the status via SOAP request so that my motor would be "turned ON" . After turning ON the motor in the other end I would like to GET a simple SOAP response.
I am not sure if the above explains to you clearly but I am tired of thinking "how to do this".

Are you directly programming the ESP8266 with your own firmware, or are you communicating to it with AT commands?

Thank you for the reply. I follow this tutorial (http://randomnerdtutorials.com/sending-data-from-an-arduino-to-the-esp8266-via-serial/) to send data from my board to ESP. But I am not sending "HI". Instead I am using two buttons, one for sending "HIGH" and other for "LOW".

OK, so you are programming the ESP8266 in Lua and that is where you want to implement your SOAP transmission. I am sorry, but this probably isn't the best place to help you. We can help with the Arduino programming, and with the ESP8266 if you were communicating with it using AT commands, or programming it with the Arduino IDE in C++. Not many people here will be versed enough in Lua to be able to help you.

SOAP, though, is just XML sent over an HTTP connection (although other connections can be used - you can even implement it as XML through email). The important thing is the XML. Since you only have two states - on and off - you can just pre-program the correct XML strings in your code and send them as a POST request to the remote end. How you would do that in Lua though is anyone's guess...

Thank you for the reply. How this can be done using Arduino IDE using AT commands or Arduino IDE in C++.? Is there any good references..? I also have a WSDL file for the other end Servo motor. Is there any use with that..?

@Majenko, Hi could you suggest me with something on how to proceed further.

Install the default AT command set firmware for the ESP8266 and you should be able to use this library on the Arduino: https://github.com/itead/ITEADLIB_Arduino_WeeESP8266

Support of SOAP occupies a lot of memory, it is better to use JSON-RPC ;)

source: Stack Exchange

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

sort: votes


text:
Wiring a RT314F12 latch relay to an Arduino
I want to automate the lights in my house. To do this, I want to use a latching relay, so it will only use current when switching. I found a quite cheap latching relay RT314F12 but I do not know how to wire it up to an Arduino. Can any one please give a wiring example?

It's a two-coil relay. Treat it exactly two normal relays. The middle coil pin is the common between the two coils.

you send it "turn on" and "turn off" pluses on different pins. instead of setting one pin to a constant state. those pins should go through an opto isolator since you're working with mains. latchers are neat, i played with the idea a lot for the same purpose, but now i use mostly DC lighting with mosfets (i need dimming)...

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


text:
Serial Communication to WPF (Windows Presentation Foundation) giving me odd results. How do I clear up the Strings I am receiving?
I'm trying to make a voltage/temp logger that will post to SQL. I'm using a WPF to make kind of a UI for people to measure the voltage of a cell, and take the temp of the battery acid in the battery. My end goal is to have the Arduino Bluetooth to a computer. the computer will handle all the SQL. The Arduino will have a physical button to post or save the data to my SQL server. Also the Arduino will have a little display to display the battery S/N, Voltage, Temp. (Side Question: Am I going to be able to do the screen and access the serial, with also sending the serial data over Bluetooth?)
My problem is that when I call my function to get that data sometimes it comes out messed up. Sometimes I get, for example: "3.1234 V=" Or "V= 3.123V=" It also happens with the temperature, sometimes I get the voltage in the temp box and vice versa.
More times than not I get a bad result. When I run it in the Serial Monitor with the Arduino IDE It looks fine. Does anyone have any advice how I can clean up the communication and get more reliable results?
Thanks for any help!
I'm using to place the serial port string into a textbox.
txt_Volt.Text = sp.ReadExisting();

I tried using the Serial.flush(); to clear out any old stuff to no avail.
The Arduino code:
else if (c == '3')
 {
   int analog_value = analogRead(A0);
   volt = (analog_value * 5.0) / 1024.0;
   Serial.print("v= ");
   Serial.print(volt, 5);
   Serial.flush();
}

Arduino loop():
void loop() {
  if (Serial.available() > 0)
  { Serial.flush();
    char c = Serial.read();
    if (c == '1')
    {
      digitalWrite(13, HIGH);
      Serial.println("LED is On");
      Serial.flush();
    }

    else if (c == '0')
    {
      digitalWrite(13, LOW);
      Serial.println("LED is off");
      Serial.flush();
    }
    else if (c == '3')
    {
      int analog_value = analogRead(A0);
      volt = (analog_value * 5.0) / 1024.0;
      Serial.print("v= ");
      Serial.print(volt, 5);
      Serial.flush();
    }
    else if (c == '4')
    {
      //Temp Function go HERE
      getTemp();
    }

C# CODE:
         private void Connect_Click(object sender, RoutedEventArgs e)
         {
           while (portNum >= 0) //automaticly connect to correct port.
           {
            try
            {
                String portName = "COM" + portNum;
                comportno.Text = portName;
                //String portName = comportno.Text;
                sp.PortName = portName;
                sp.BaudRate = 9600;
                sp.Open();
                status.Text = "Connected";
            }
            catch (Exception)
            {
                portNum--;
                // MessageBox.Show("Please give a valid port number or check your connection");
                if (portNum == -1)
                {
                    MessageBox.Show("Could not find Arduino\nCheck Connection");
                }
            }
        }

    }

    private void Disconnect_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            sp.Close();
            status.Text = "Disconnected";
        }
        catch (Exception)
        {

            MessageBox.Show("First Connect and then disconnect");
        }
    }

    private void on_Click(object sender, RoutedEventArgs e)
    {
        sp.Write("1");
        rect_LED.Fill = new SolidColorBrush(Color.FromRgb(0, 255, 0));
        // DebugWindow.Text = sp.ReadExisting();
        //  readingStuff();
    }

    private void Of_Click(object sender, RoutedEventArgs e)
    {
        sp.Write("0");
        rect_LED.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0));
        //  DebugWindow.Text = sp.ReadExisting();
        //  readingStuff();
    }

    private void Get_Volt_On_Click(object sender, RoutedEventArgs e)
    {

        sp.Write("3");
        string volts = sp.ReadExisting();
        int volt_length = volts.Length;

        bool isLetter = !String.IsNullOrEmpty(volts) && Char.IsLetter(volts[0]) && Char.IsDigit(volts[volt_length - 1]);

        if (isLetter)
        {
            DebugWindow.Text = volts;
        }
        else
        {
            DebugWindow.Text = "Error";
            sp.Write("3");
        }
    }

    private void Get_Temp_On_Click(object sender, RoutedEventArgs e)
    {
        sp.Write("4");
        txt_Volt.Text = sp.ReadExisting();
    }

    void readingStuff()
    {
        String comdata = sp.ReadLine();
        Dispatcher.Invoke((Action)(() => DebugWindow.Text += "Data\n" + comdata + "\n"));
    }

What a bad result looks like:

A Good result:

Your problem arises from a mix of newline-terminated and un-terminated messages.
The newline terminated values probably would work by themselves as you can use a ReadLine() type method to wait until they have been completely transferred.
But the non-terminated attempts such as your use of the ReadExisting() method cause a problem - these likely fetch whatever has been received up to the time of the call but that will not necessarily be the full message sent (or even anything at all).   Whatever is left over (had not been received by the time of the call) will become the beginning of the data achieved during the next partial or until-newline read.
As a solution you should probably either:

Terminate each message with a newline

or else

Always read only complete lines, and then parse individual messages out of them

or

Always read until you find some delimiter character such as a space or comma, or a newline.  You may have to write your own read method to accomplish this.

Using delays to try to fix a problem like this is bad practice as it is fragile and can easily break if there is an unexpected delay on the other side, or if the execution speed of one of the components changes.  A number of fragile techniques that generally worked with true serial ports subsequently broke when USB converters were introduced in the middle, as USB bunches data into packets with gaps in between, a behavior not necessarily previously seen in many pure serial implementations.

So if I wanted to read both voltage and temp at the same time, I would have to have the Serial.print(volts) and Serial.println(temp) then have some way of breaking the string apart in my C# code?

That is one way (if you put something in between) the point is that reads not looking for a defined end condition in the data itself are causing your trouble.


text:
Does 'digitalPinToInterrupt' work with analog pins
I have an interrupt signal attached to the A12 pin of an Arduino Mega 2560.
Would the following source line activate the interrupt processing?  I am calling the digitalPinToInterrupt function on an Analog pin.  It compiles fine.
attachInterrupt(digitalPinToInterrupt(A12), MessageFromIOBInt, FALLING);

where my interrupt code is
void MessageFromIOBInt(void) {
    ++gNumInterrupts;
}

What Arduino board are you using?

I am using MEGA 2560

Interrupts only work on interrupt pins. Trying to translate a pin number into an interrupt number for a pin that isn't an interrupt pin will never work.

External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low level, a rising or falling edge, or a change in level.

Many pins (including the analog pins) can use the pin change interrupt. This requires an external library which has its own way of interfacing with them (see the examples).

Does 'digitalPinToInterrupt' work with analog pins?

It works in the sense that it compiles. When executed, for a pin that is not one of the interrupt pins it will return the value NOT_AN_INTERRUPT.
Thus a sensible test would be to check whether or not you get NOT_AN_INTERRUPT returned from digitalPinToInterrupt(A12).
A quick test confirms this:
void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (digitalPinToInterrupt(A12));
}  // end of setup

void loop () { }

Output:
-1

In Arduino.h is this define:
#define NOT_AN_INTERRUPT -1

I have a page about interrupts. On that page, amongst other things, is a list of external interrupt pins for various Arduinos:

You can see that the pins on the board labelled D2, D3, D18, D19, D20, D21 are the only ones which support these sorts of interrupts (external interrupts). Various other pins support pin-change interrupts.
On the Mega2560 in particular these pins are supported for pin-change interrupts:

10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69)

As Majenko mentioned, you use pin-change interrupts in a different way, possibly using the PinChangeInt library, or just accessing the registers yourself as described on the page I mentioned above.


text:
Arduino UNO with LMT86LP temperature sensor
I am trying to use the Arduino Uno with the LMT86LP temperature sensor, but I am getting strange output voltages from the sensor.
I have the pins (from left to right, flat side facing forward) as VDD, OUT, and GND. VDD is connected to 5V, GND to GND, and Vout to A0 (analog pin 0). The readings from the Arduino are consistently around 360 mV but should be somewhere around 1800 mV as I measured the output of the sensor using a multimeter and got a constant 1.8 V.
Right now the code is very simple. I am just doing analogRead() and printing to the Serial Monitor.

The result from analogRead() is in counts of full scale, not in volts. Since you are using a 10-bit ADC, full scale is 1024.
1.8V/5V⋅1024=368.64

Ah I see, thank you. However I seem to be getting negative values for the temperature. The calculations I am doing are like so,
int vin = analogRead(A0);
float mV = (vin/1024.0)*5000;
float tempC = (mV-500)/10;

@user1982824: Why are you subtracting 500?

Sorry sorry, this actually what I'm doing,
voltage = reading * (5.0 / 1024);
tempC = (voltage - 0.5) * 100;
and I'm getting values around 12.5 celsius

@user1982824: That equation doesn't match anything I can find in the datasheet.

should i be using the equation T = (10.888 - sqrt((-10.888)^2 +4*.0035*(1777.3-temp))/(2*-0.00347)) + 30

@user1982824: Eh, you could, but unless you need to support the entire temperature range of the device I'd look at using the approximation method just a bit lower down on the page.

thanks, i just made the modification and it works fine. :D


text:
Branching Bus for Sensor
I am looking to setup a system where I have a master Arduino polling a number of sensors.
The way I am thinking is hooking the master TX line to the sensors RX line(and the opposite for the other line)
Questions

How long can the lines be?
Can the lines branch?

I have a page about connecting Arduinos using RS485. You can connect multiple devices up like this:

That has a reasonable range, 20 metres or more.

On that page I describe a Rolling-master system where each device takes turns to be the master and transmit information to the other devices. It also manages some devices not responding.
This screenshot shows the various devices "talking" during their timeslot:

In that particular case there were 3 devices active out of 4 configured.

I have a master ardunio polling a number of sensors.

I'm assuming in my answer that you have an Arduino at each sensor point (you could use a cheap ATtiny85 or something). That would be needed to run the rolling master code.

Does the bus need to be straight or can it branch?

I don't offhand see why you can't branch. The two wires are in parallel to each device, so I suppose you could take a branch off at some point.

From what I can see RS485 does not like branches. However what I have come up with is running two twisted pairs. One being return and that allows me to have T junctions.

How many sensors and what kind are they?
What Arduino do you have?
Basically you could use 1 Arduino Output per sensor if you have enough, or you are going to need to use a multiplex technique via additional electronic components.
The only other solution would be to use communication (I2C/Serial/etc) to receiving nodes at the sensor.

MPU 6050 with an Ardunio on each sensor to send the data onto the bus.

@Catprog Try and read up on SPI. You may not need the Arduinos at each MPU6050 if you use that protocol.


text:
Ethernet shield/WebServer problem: 'server is at 0.0.0.0'. Any suggestions how to debug it?

Ethernet shield problem. When running the WebServer example sketch, the Serial Monitor shows that server is at 0.0.0.0. Any suggestions how to debug it?

The arduino only tells what it reads from the ethernet module and 0.0.0.0 is what you get when Arduino is not connected to it. It's a hardware problem, you either didn't connect the wires right or something's fried. I think it can also happen if your ethernet cable is unplugged.
This is absolutely not a sign that your module is accepting all connections. It would be the case if you set it that way but you are obviously expecting another ip adress. Someone should delete that answer.

If another answer is incorrect then it should be downvoted

That's what it's supposed to be. It's called INADDR_ANY. Read an introductory text on networks and you'll understand what that means.
If you try to connect to the IP address you specified, you'll see that you can indeed connect.

Unfortunately this is not the case in my case :/

If possible, try running the same code on an identical Arduino. I had a similar issue, and it turned out one of my ICSP pins were burned.
Contrary to other answers here, the IP address will show the correct value in the Serial Monitor even though nobody is connected.

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


text:
Arduino-Pyserial communication on Python 3, Windows machine: Pyserial.write() doesn't seem to do anything
I've recently gotten my hands on an Arduino (or rather a Genuino, but the overall architecture should be the same) UNO. I'm now using that Arduino to test how data is transmitted from a USB to Serial Connector to the Arduino.
I've already verified that data transmission from Arduino to the PC is possible, by using hTerm and PySerial. However, whenever I send data from Pyserial or hTerm, it doesn't show up in the Arduino serial terminal. Also, I'm using SoftwareSerial to set up a secondary serial terminal to see what the Arduino receives. (I'm using the standard serial port to send data to the terminal, and the SoftwareSerial Port to connect to the USB to Serial Connector.)
Here's my code so far:
Python side:
import serial
import time
import sys
import struct
ser = serial.Serial('COM3', 9600, timeout=0)
time.sleep(10)
while 1:
    print(ser.write(struct.pack('>B', 0)))
    time.sleep(2)
    print(1)
    sys.stdout.flush()

The Arduino side looks like this, and is essentially the default example:
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  // put your setup code here, to run once:
  if (Serial) {
    Serial.end();
  }
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Serial.println("Godnight moon!");

  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.listen();
  if (mySerial.available() > 0) {
    Serial.println("Hello User");
    Serial.println(mySerial.read());
  }
}

The Terminal never prints "Hello User". Also, no other signals are being printed. By removing the if-condition, I get a whole lot of "Hello User" and "-1" in the Arduino IDE serial monitor.
Concerning my setup:
I've got an USB to Serial converter, which is connected as "COM3". On the other side, I have an Arduino UNO which is connected via USB to the same computer. The TX pin of the converter is connected to the RX pin of the Arduino and vice versa. Also, Ground is connected to Ground. Furthermore, I use Jupyter/IPython notebook to run my Python script, and the default Arduino IDE to compile programs for my Arduino. In the case there I received data from the Arduino, I used the script specified in the URL provided, which is very similar to the one I'm already showing here. Also, ser.write() is replaced by ser.read(1), so that it reads one byte at a time. My system is Windows 7 (64 Bit).
Edit: Here is an established connection between hTerm (a serial terminal) and the Python script while using com0com as a port emulator.

What are you using to connect to the SoftwareSerial pins?

Some cables which came with the Genuino starter kit. RX is connected to TX and TX to RX (USB-Serial to Arduino), and ground to ground

"Some cables" isn't very descriptive. Which TX and RX pins are you connecting to?

Oh, ok. Well, I'm connecting to Pin 10 (RX) and Pin 11 (TX). Or do you mean how I connect on the other end?

OK, that makes more sense to me now.

A diagram of your setup would add a lot of clarity to your question. You checked that the USB-Serial port is COM3? What does the Python shell display when you run the script? To be clear, you connected the RX of the USB-Serial adapter to Arduino pin 11, and its TX to Arduino pin 10? Remove the 'timeout' argument in the 'ser' instantiation in the Python script and try it again.

I updated the description. And that's correct, COM3 is the port that's assigned to the USB-Serial converter. And Pin 10 (RX) is connected to TX at the USB side, while PIN 11 (TX) is connected to the RX at the USB side. Also, I've already received data from the Arduino, so I don't think it's a problem with the setup. I've also switched around the connection cables, but that doesn't solve it either

Does it work if you use the builtin hardware serial port of arduino? That way we could try to see if the problem is in the python part or the arduino part.

Ok, so I used hTerm for this, since this is probably better for debugging right now. When I send a signal from the Arduino Terminal to the Arduino via Serial(Works for both cases, virtual and builtin hardware serial port (Pin 0 (RX) and Pin 1 (TX), right?)), I get an answer in the seperate hTerm window. hTerm is connected to the USB-Serial Converter (COM7). However, if I'm sending data from hTerm or the ipython script to the Arduino, it doesn't respond. (The Arduino IDE terminal and hTerm show nothing). So, my best guess is that the USB-Serial Converter is broken...

@user25642 - Has the COM port changed number or have I misunderstood.  You program says COM3 yet you are connecting hTerm to COM7.

Well, I have two USB-Serial Converters, and I just tried them both. Sorry if that was confusing. And they both don't seem to work

What do you think should come out?
I'm no expert with Python but you seem to be using struct pack, which I think prepends a number of bytes to the data to generate a 4 byte word.  You are using NULL, 0 to pack the structure.  When Serial.println() encounter a NULL it will assume that is the end of the string.  So you seem to be printing a zero byte string.
Oh and Serial.read() only reads one byte of data, so there is an issue with that too. I suspect that the write call has a similar issue, you normally need to supply a size parameter because its binary data.
Does that make sense?

Hi, thanks for the reply. The struct pack has a syntax as follows:
The ">B" stands for a little endian byte that's gonna be packed, while the 0 is just an int that's packed into the byte. If I print it out, I get b'\x00' , which means that it's just an empty Byte. Is that what you meant with NULL, or is that another parameter?

And yes, I know that Serial.read(1) reads only one Byte at a time. That was just for testing purposes, as I was sending only one byte at a time. (To see if the connection works at all)
The pySerialAPI (http://pyserial.readthedocs.io/en/latest/pyserial_api.html)
states that write only takes one argument, the data. For python 3 it has to be formatted, which is why I'm using the struct package. For a 4 byte word, I would need to use something like ">BBBB", since a single B is just one byte.
I hope that clarifies what the code does a bit more :)

Generally, the struct package is used to format variables in python to certain standards. The problem is that a python int only takes up as much space as needed, so it will have a varying length, depending on the size of the number.

A variable length int, what a silly language :)  Yes thanks that clarifies a lot.  By NULL I do mean 0x00, so if that what you are getting its working.  If you print that as a string then it will seem like it is doing nothing.  Can you write (0x42) rather than packing it, you should get 0x42 on the Arduino or 'B'.

Ok, so I just used the pack-function to pack b"B" (Which is the bytes representation of a B. Python 3 is Unicode, so that should work) and send it instead of a 0. The Arduino still doesn't display anything.

Ok, so I c an send data from my python script to hTerm with virtual ports (I'm using com0com). I can also send data from hTerm to my script. But if I connect two USB-Serial Converters to each other, and connect one to hTerm and the other one to the python script, they don't communicate. So now I'll check the drivers and such for the USB-Serial Converters. (Even though they still blink up if they send something)

Don't use pack() that's what is causing the problem.  You are sending 0x00000043 which is Null, Null, Null B.  When the Arduino reads one byte it see Null, which means it prints nothing.  You need to send the single byte 0x43.  If you want or need to send a word then send 0x43000000.  This way it should work.
USB <-> Serial <-> Serial <-> USB will not work unless Serial <-> Serial has the RX and TX lines crossed over.  You don't have these lines crossed over because you can use both convertors to talk to the Arduino.

Can I ask why you are under the impression that pack() is making a 4 byte  number? If I use ">c", I'm packing the string to be its 1 byte character representation. I've checked that with the terminal. Only that one byte arrives, nothing else (I will also try to attach a screenshot of it in my question). And I'm not quite sure what you mean with "crossed over." I connected the TX of Serial-USB to the RX of the other Serial-USB, and vice versa. Is that what you were suggesting?

I noticed the NULL thing but I assumed Serial.println() would display '0', as though you ran Serial.println(0).

@user25642 - I was guessing what pack did, so thanks for correcting me.  Yes by "crossed over" I mean tx to rx and rx to tx.

When you run your python code, do you see the things you are sending on the screen there?
I think you need to be calling  ser.open().


text:
Program an Arduino with another Arduino

Is there any way I can program an Arduino using another Arduino,without the need of any computer. I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, burn this code to the Second arduino. Is it possible? How can it be implemented ?

Just use the ISP interface, which is similar to SPI.

will it work without a computer?

Depends on your programming skills...

This sounds like an XY Problem. What are you really trying to do?

The code which is compiled by the arduino IDE is stored inside the arduino and this code will be burnt to any atmega328p chip which is connected to this arduino using any interface

This will give me the ability to program this chip with a compact circuit rather than connecting it to the laptop and burning it

Stack Exchange isn't google. Please google your ideas and try them out before asking on SE. It's VERY likely someone else has had the same idea/problem and made a tutorial or video on it.

You could store just a small program into an EEPROM. For example ATmega328 has 32 KB of program memory and just 1 KB of EEPROM. Besides that, instruction opcodes are 16 bit  so you could store only 512 instructions in 1 KB of EEPROM space. But yes, you could store the opcodes as data in flash and write a program (or use a bootloader for that purpose) to send the firmware over serial communication to another Arduino board.

Th 328 doesn't have enough memory for this. Memory allowing, it is a simple task. Take a look at the 'Arduino As ISP' examples and code.

Storing the program on an SD card and using an Arduino to read that data and program it into another Arduino is perfectly possible. Either through ISP or through serial using the STK500 protocol for the bootloader.

It is certainly possible to do this.

I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, burn this code to the Second arduino.

I should point out that the EEPROM may not be large enough for this. For example, the Uno has only 1KB of EEPROM.
A more workable solution would be to store a reasonable size program in PROGMEM, or a larger one in external memory, like an SD card.
I have a page about a stand-alone programmer - the first idea presented just uses the Serial monitor to command the programmer behaviour:

Using the Serial Monitor you select the file you want programmed. Another approach, commissioned by someone who wanted to eliminate the external computer altogether looks like this:

In this case you put one or more hex files onto the SD card, choose one using the "file select" knob, and then press the "program" button to program it. This only takes a couple of seconds.
There are also commercial products that do a similar thing.

Worth bearing in mind that something like an ESP-01 has much larger memory than the Uno's 1k - 512kB or 1MB - and is smaller and cheaper. Other models have more memory /flash still.

True, but the question was about 2 x Atmega328P.

Hence why I said it was also worth considering. Perhaps he's not 100% unchangably committed to that particular device for the programmer - an XY problem perhaps.

Quite possibly. :)

Yes. Connect 2 arduinos via serial connection (https://www.arduino.cc/en/Reference/Serial), restart one of them via RESET channel and upload sketch(https://www.arduino.cc/en/Guide/ArduinoProMini#toc1). You will need binary files - google 'arduino get sketch binary'(cannot add any more links).

add as may as you want


text:
Are all the pins on Arduino shields available for use?
Basically, if I put a shield on my Arduino (mine is Uno, but I'm asking generally), can I freely use all the pins that are there on the shield?
I have an Ethernet shield and almost all of the pins that the original Uno has, are available on the Ethernet too.
The best results that I could get from googling are this and this which describe that if a shield uses a certain pin, putting another shield that uses the same pin causes conflict.
But what about using them myself? Can I use all the pins on a shield as Input/Output?
If some pins are unusable, then why are they available on the board? For example why doesn't the Ethernet have pins 10-13 blocked so you can't put any jumper wires in them?
Additional info:

There was also this article which didn't seem very credible to me.
Also I've tried using pins 10-13 to light an LED while the Ethernet was busy transferring data. The result was the LED connected to pin 10 was very dim, 11 was less dim and so on. So my guess is yes, they are unavailable. But the fact that this was so rarely mentioned on the internet and that the pins aren't physically blocked made me doubtful.

Short answer: NO.
Each shield adds some feature to the base Arduino Uno board and to do that it's more than probably going to use some of the PINs.
I say more than probably because Arduino do have support for certain protocols which can share the same pins (I2C and OneWire just from the top of my mind), but they are not the most commonly used approaches for shields.
The only reason the shields expose the same set of pins is for stackability, but not every shield is compatible with any other: it depends on the used PINs.
Some shields provide some level of configuration, usually via jumpers, in order to make them usable in more contexts they would usually be.

Documentation regarding the pins used by each shield is generally available along with the shield, but if you buy cheap clones it's no surprise you might have difficulties finding documentation...
The article you were pointing is somewhat creditable because most of what the author says is actually true and real, including the risk of short circuits.
As an example, the test you run with LEDs connected to the Arduino SPI interface (pins from 10 to 13 are used by SPI) could have damaged your board if you didn't use current limiting resistors.


text:
Referencing local libraries from higher dir levels
How can I include libraries not contained in any direct subdirectories of a sketch, using the Arduino IDE?
I want my project structure to look like this:
Project
└> MCUa
   └> MCUa.ino
└> MCUb
   └> MCUb.ino
└> Libraries
   └> TimerLib
      └> TimerLib.cpp
      └> TimerLib.h

So in my project two sketches MCUa and MCUb share a resource, namely the library TimerLib.
I've tried to include the libraries like this:
#include "../Libraries/TimerLib/TimerLib.h"

or this:
#include "./../Libraries/TimerLib/TimerLib.h"

But none of them will compile - this is the error message:
fatal error: ./../Libraries/TimerLib/TimerLib.h: No such file or directory
 #include "./../Libraries/TimerLib/TimerLib.h"
                                              ^
compilation terminated.
exit status 1
Error compiling.

If I put the library directly in of the directories and reference it like this:
#include "./Libraries/TimerLib/TimerLib.h"

Everything goes well.
Using an absolute path like in this answer is not a possibility in this case, as it should compile out of the box for others, without modifying any absolute paths.

Did you try #include <TimerLib.h>? Add to sketch and in source of TimerLib.

@MikaelPatel If I put the TimerLib in the "global" Arduino directory, yes, that works. But I don't think I understand your comment/suggestion? What should be added to the source of  TimerLib?

The problem with a relative path for an include is that it has to be relative to one of the predefined list of existing include directories. This includes:

Compiler include locations
The Arduino core files
The locations of other included libraries
The build folder for the sketch

What it does not include is the location of the sketch, so you cannot specify a location relative to the sketch itself.
Further, even if you could, the compiler wouldn't know what library it was supposed to be referencing so, while the header would be found, any source files associated with it would be ignored and linking would fail miserably.
Instead you will have to place the library in a standard library location, such as the libraries folder in your sketch book.

Ok, but why does #include "./Libraries/TimerLib/TimerLib.h" then work? That is relative to the sketch? I probably just don't understand completely how the compiler searches for libraries.

I suspect that it is being copied to the build folder along with the rest of the files in the sketch.


text:
How to interpret accelerometer output data?
I'm running my accelerometer through my Arduino mini and outputting my values using the following values
 // print the sensor values:
  Serial.print(analogRead(xpin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(ypin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(zpin));
  Serial.println();
  // delay before next reading:
  delay(100);

Here's an example.

The x,y,z values that are outputted are quite high even the arduino is not moving. I'm new to Arduino programming and would love some understanding on how to convert these x,y,z to an Acceleration value ie. Is the arduino moving or not?

Can you edit the original question and include the model of accelerometer and a link to the datasheet.

I've edited. @KennetRunner

It is possible that sensor is close to both values. For example, if x is at 9.9 sometimes it can be a bit more, so it will give you 10, while other times it will just give you 9. (this would be the same for y and z)

Even when the Arduino is not moving?

Quite high? Those are minuscule values. You have the raw ADC values there. They can range from 0 to 1023. 8 is just 0.78% of the maximum value. That's hardly "quite high" - that's almost non-existent.

Can you please specify the Model of Accelerometer? Each different model will send data differently and values will have to be interpreted differently.

Hi Mero55, it's an ADXL345.

The accelerometer will output a specific number of volts (or millivolts) per g.  You need to find that information in the datasheet for your accelerometer.
Then you need to take the readings you make through analogRead() and convert them to a voltage. Then that voltage can be used, combined with the value you found above, to determine the g reading.

As has been noted by @Majenko, you are reading voltages with your analogRead() as a ratio of the A/D reference voltage specified for the Arduino you are using rather than true accelerations. For example, your first pass readings of x=9, y=8, z=8 were really saying x = Vref * 9 / 1023 volts. The datasheet for your accelerometer sensor will specify a calibration factor to be applied in terms of Volts/g.
Therefore, if you wish to read in terms of actual acceleration g. then you will need to first convert the value read from the A/D to volts and then convert the voltage to g by applying the datasheet sensitivity factor.
You can brute force this conversion calculation if you wish by using variables of type float. If you wish to avoid floating point arithmetic and use fixed point calculations, you can consider defining the result as being multiplied by 10 or 100. (Example: a reading of 1.0g might be reported as 10 if using 10x reporting or it might be reported as 100 if using 100x reporting.
Additionally, if you suspect some jitter in your measurements, you can read multiple times to average and smooth the readings. You can then divide the total of the readings to get an average.
Example Code for Single Axis Using Integer Variables (Untested)
#define AXIS_PIN A0

void setup() {
  // Insert Setup Code Here

}

void loop()
{
  int reading;

  reading = 0;

  // Read the sensor axis value 4 times
  //  Use a short delay between reads if you might exceed
  //    the read frequency of the sensor.
  // Use millis() for non-blocking aspects if needed
  for (int readLoop = 0; readLoop < 4; readLoop++)
  {
    reading += analogRead(AXIS_PIN);
    delay(2);
  }

  // Map the reading to a voltage using a 100x multiplier
  //  The raw reading has a range of (0 to 1023) * 4
  //  The mapped reading has a range of (0 to 3300) * 4
  //    (assuming a 3.3v reference voltage)
  //    (Use 0 to 4 * 5000 if required by the choice of sensor and
  //      Arduino used.)
  reading = map(reading, 0, 4 * 1023, 0, 4 * 3300);

  // Find the average by now dividing by 4
  reading = reading >> 2;

  Serial.print(F("Average axis reading (x100) is: "));
  Serial.println(reading);

  // Read the axis once per second
  // Use millis() for non-blocking aspects, if needed
  delay(1000);
}

EDIT NOTE: I see you have now specified an Adafruit ADXL345 sensor. Be aware that this sensor references 3.3v (offset ratio-metric, ie +/- 1.65v) even though it runs off of a 5v power source. Depending on which Arduino you are using, you may have to adjust the map() function input above to account for the proper output. You can try something like map(reading, 0, 4 * 1023, -2 * 3300, 2 * 3300);.
ADDED EDIT: The above will output a converted voltage. If you would like to output directly in units of g (x100), then you can change the map() function to something like map(reading, 0, 4 * 1023, -2 * 300, 2 * 300) assuming the Adafruit ADXL345 (PRODUCT ID: 163) which reads to +/- 3g.


text:
Connect two ESP8266 using serial link
I am trying to build a gateway for ESP-NOW (https://github.com/HarringayMakerSpace/ESP-Now) and I would like to get help with connecting two esp8266 (nodemcu + esp01) with serial link (for use as gateway).

What I done so far:
ESP01 ... NODEMCU
-----------------
3V3   ...  3v3
GND   ...  GND
CH_PD ...  3v3
TX    ...  RX
RX    ...  TX

The problem is that with this setup NodeMCU (and I think ESP01 too) is not booting (probably because TX is connected?). What's the correct way to connect two ESP8266 as described in ESP-NOW project?
NodeMCU is running this code:
https://github.com/HarringayMakerSpace/ESP-Now/tree/master/EspNowFromSerialGateway
ESP-01 is running this code:
https://github.com/HarringayMakerSpace/ESP-Now/tree/master/EspNowToSerial

RX to TX. receive to transmit. and pull-up for io 0 of the esp-01

Ahoj Juraj, I tried this as well, but the main problem is not this. If I remove ESP-01, it boots correctly.

the code running on nodemcu seems to use softwareserial (on pins 14 and 12 - which are Dx and Dy on the NodeMCU - where x and y are seemingly arbitrary numbers), but you're connecting the hardware serial - I could be misreading the code though - I mean, how do you know it's not booting anyway?

This was the problem, problem solved. Thank you. If you post this as answer I can accept as solution.

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


text:
lcd has no contrast pin
i just bought this lcd. I connected all pins as discripted on this datasheet (Page 8). However i noticed that there is no pin to control the contrast. I also didin't get the display to run yet.
Might that be a problem?
edit: here is the code...
#define RST 3
#define CE 2
#define DC 4
#define DIN 6
#define CLK 5

void LcdWriteCmd(byte cmd)
{
digitalWrite(DC, HIGH); //DC pin is low for commands
digitalWrite(CE, HIGH);
shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
digitalWrite(CE, LOW);
}

void setup()
{
pinMode(RST, OUTPUT);
pinMode(CE, OUTPUT);
pinMode(DC, OUTPUT);
pinMode(DIN, OUTPUT);
pinMode(CLK, OUTPUT);
digitalWrite(RST, LOW);
digitalWrite(RST, HIGH);
LcdWriteCmd(0xAE); // LCD set display enabled
LcdWriteCmd(0x21); // LCD set power COntrol
LcdWriteCmd(0x14); // LCD bias mode 1:40
LcdWriteCmd(0xA2); // LCD basic commands
// LcdWriteCmd(0xA9); // LCD all segments on
}

void loop()
{
}

Is how you have interfaced it the same as in this document? http://www.buydisplay.com/download/interfacing/ERC12864-655_Interfacing.pdf - THAT is the document you should be reading for wiring it up. Also what code / library are you trying to use to get it working?

Yes that is probably the problem.

i did my wiring as described on that sheet. (serlial) I used no library yet. I thought i could just send a command to the display (all pixels on). I edited the question so you can see what the code looks like

What happens when you run the program?

I think your commands are a little wrong. Let's look at them:
LcdWriteCmd(0xAE); // LCD set display enabled

0xAE is 0b10101110. In the datasheet the matching command is 1010111# where # is display on (1) or off (0), so 0xAE is actually display disabled. Changing it to 0xAF instead, so bit 0 is 1, should enable the display.
LcdWriteCmd(0x21); // LCD set power COntrol

0x21 is 0b00100001. That command is 00100### where ### is the VLCD resistor ratio. That is being set to 2/8. ((# + 1) / 8).
LcdWriteCmd(0x14); // LCD bias mode 1:40

0x14 is 0b00010100, which is command 0001#### which sets the column address MSB. Quite why you're doing that I don't know, but that command has nothing to do with bias mode...
LcdWriteCmd(0xA2); // LCD basic commands

No, 0xA2 / 0xA3 sets the bias ratio set, which selects the bias from one of two groups of biases depending on the current duty. This is the default value.
So not only are you not configuring the screen correctly, but you aren't even then trying to put anything on the screen to see if it's working or not.
I suggest you work from the provided example code:

http://www.buydisplay.com/download/democode/ERC12864-655_DemoCode.txt

The "Initial" function sets the sequence of operations:
SET_ADC();
CLEAR_SHL();
CLEAR_BIAS();
Power_Control(0x07);
Regulor_Resistor_Select(0x06);
Set_Contrast_Control_Register(Contrast_level);
Initial_Dispay_Line(0x00);
DISPLAY_ON();

The main commands are defined at the top of the file:
#define DISPLAY_ON()           Write_Instruction(0xaf)   //  Display on
#define DISPLAY_OFF()          Write_Instruction(0xae)   //  Display off
#define SET_ADC()              Write_Instruction(0xa1)   //  Reverse disrect (SEG131-SEG0)
#define CLEAR_ADC()            Write_Instruction(0xa0)   //  Normal disrect (SEG0-SEG131)
#define REVERSE_DISPLAY_ON()   Write_Instruction(0xa7)   //  Reverse display : 0 illuminated
#define REVERSE_DISPLAY_OFF()  Write_Instruction(0xa6)   //  Normal display : 1 illuminated
#define ENTIRE_DISPLAY_ON()    Write_Instruction(0xa5)   //  Entire dislay   Force whole LCD point
#define ENTIRE_DISPLAY_OFF()   Write_Instruction(0xa4)   //  Normal display
#define SET_BIAS()             Write_Instruction(0xa3)   //  bias 1   1/7 bais
#define CLEAR_BIAS()           Write_Instruction(0xa2)   //  bias 0   1/9 bais
#define RESET()                Write_Instruction(0xe2)  //   system reset
#define SET_SHL()              Write_Instruction(0xc8)   // SHL 1,COM63-COM0
#define CLEAR_SHL()            Write_Instruction(0xc0)   // SHL 0,COM0-COM63

The more complex ones are simple enough - just ORing the provided parameter with the base command. For example Power_Control() just does:
Write_Instruction((0x28|vol));

I am sure you can find (and decipher) the rest of the commands to initialize the screen properly.


text:
How to use Serial2 on Raspberry Pi Pico
I want to use Serial1 and Serial2 in a sketch in Arduino IDE for a Raspberry pi pico.
My goal is to communicate from the pico with two other Arduino boards.
I use Arduino 1.8.9 and the official board for Raspberry Pi Pico:
"Arduino Mbed OS RP2040 Boards by Arduino version 2.1.0"
Serial2 does not seem to be configured. When I compile
    #include <Arduino.h>
    void setup() {
        Serial2.begin(9600);
    }

    void loop(){}

I get:
"undefined reference to '_UART2_'".
I found some documents (not rpi pico specific) that state you can define a second UART like this:
    #include "wiring_private.h"
    Uart mySerial (&sercom3, 1, 0, SERCOM_RX_PAD_1, UART_TX_PAD_0); // Create the new UART instance assigning it to pin 1 and 0

But that throws
" 'Uart' does not name a type; did you mean 'sqrt'?"
Does anyone have an example of how to use Serial1 and Serial2 (2 serial communications to two other boards) on a Raspberry Pi Pico using Arduino-IDE?
Thanks a lot!

I found the solution after reading https://github.com/arduino/ArduinoCore-mbed/issues/210#issuecomment-849502556.
Although the proposed code did not compile as it was shown there.
UART Serial2(8, 9);  // did not compile

What worked for me was:
UART Serial2(8, 9, 0, 0);

Full code:
#include <Arduino.h>

UART Serial2(8, 9, 0, 0);

void setup() {
  Serial2.begin(9600);
  // ...
  Serial2.write("hello world");
}

void loop {}

I'm not using the "Mbed" board, I'm using the "Raspberry Pi Boards(1.9.7)" --> "Raspberry Pi Pico" board, and found that:
Serial1 uses hardware UART0
Serial2 uses hardware UART1
Serial1.begin(SOME_BAUDRATE); // defaults to TX on GP0 and RX on GP1
Serial2.begin(SOME_BAUDRATE); // defaults to TX on GP8 and RX on GP9
To change the default UART pins to other option, as long as it comply with the Raspberry Pi Pico pinout (look for UARTx_TX / UARTx_RX next to the pins), see the following example:
#include <hardware/pio.h>

gpio_set_function(12, GPIO_FUNC_UART); // change the TX default for Serial1 (UART0)
                                       // to be GP12

gpio_set_function(13, GPIO_FUNC_UART); // change the RX default for Serial1 (UART0)
                                       // to be GP13

Completely different situation since you're using a different board.


text:
Receive data using ESP8266
I have connected ESP8266 to my Raspberry Pi's WiFi network and assigned a static IP.
My Arduino code
#include "SoftwareSerial.h"

String ssid = "Rpi";
String password = "raspberry";

SoftwareSerial esp(3, 2);// RX, TX

String server = "192.168.50.1"; //my Host

void setup() {
  esp.begin(115200);
  Serial.begin(115200);
  connectWifi();
  httpget();
  delay(1000);
}

void connectWifi() {
  String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);
  if (esp.find("OK")) {
    Serial.println("Connected!");
  }
  else {
    Serial.println("Cannot connect to wifi ! Connecting again...");
  }
  connectWifi();
}

/////////////////////////////GET METHOD///////////////////////////////
void httpget() {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",1234");//start a TCP connection.
  if ( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  /*
    String getRequest =
    "GET " + uri + " HTTP/1.0\r\n" +
    "Host: " + server + "\r\n" +
    "Accept: *" + "/" + "*\r\n" +
    "Content-Type: application/json\r\n" +
    "\r\n";
  */
  String sendCmd = "AT+CIPSEND=";
  esp.print(sendCmd);
  //esp.println(getRequest.length() );
  delay(500);
  if (esp.find(">")) {
    Serial.println("Sending..");
    //  esp.print(getRequest);
    if ( esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String response = esp.readString();
      }
      esp.println("AT+CIPCLOSE");
    }
  }
}

void loop() {
  httpget();
}

I get this message

Cannot connect to wifi ! Connecting again...

In my Raspberry Pi I am constantly sending a signal to this IP address.
import socket

TCP_IP = '192.168.50.1' #Local Host
TCP_PORT = 1234            #Listening Port
BUFFER_SIZE = 12

SERVER_IP = '192.168.50.18'  #Arduino IP
SERVER_PORT = 3007            #Server Port

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((TCP_IP,TCP_PORT))
#s.listen(1)

#(conn,addr) = s.accept()
#print 'Connection address: ',addr
while True:
    print 'Sending message'
    s.sendto('1',(SERVER_IP,SERVER_PORT))
    print 'Waiting for response'
    data,addr = s.recvfrom(BUFFER_SIZE)
    if not data: break
    print 'received data: ',data
    print 'data recieved from: ',addr
    conn.close()
s.close()

But I can not see it in my Serial Monitor. Do I need to create a separate program for getting from WiFi?

you didn't start a server on esp8266 so nothing listens on esp for signals from raspberry

did you change the wifi mode in esp? it is in AP mode at default

softwareserial at 115200 has errors

You are recursively calling connectWifi() and therefore your setup function results in an infinite loop.
You must not implement loops and for processes, which take some time, you should set and ask a flag.
Btw. why don't you use the official ESP WiFi library?

What is official ESP WiFi library?


text:
Using Arduino as ISP to burn sketch directly to ATmega328 without first installing a bootloader on the ATmega328
Is it possible to take a bare ATmega328 chip, and with an Arduino as ISP, burn a sketch directly to the chip (e.g. not needing a bootloader), or is the bootloader required to run Arduino sketches? I want to embed the ATmega328 into a different device, and do not want the overhead of the entire Arduino board.
I have looked at https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard and https://www.arduino.cc/en/Tutorial/ArduinoISP, and want to do the "minimal circuit" approach (as my application does not require 16MHz).
The tutorial described has steps to first burn a bootloader, then remove the chip from the Arduino, and then install the sketch. Ideally, I would like to skip the bootloader and removing the chip from my Arduino. Ideally, I would like to do it all from Arduino Studio (not AVRDUDE CLI).
I don't mind "dedicating" my Arduino to this (as I assume it's just burning the ArduinoISP sketch whenever I want to burn to a new ATMega328).
Thanks

It is possible to skip the Burn Bootloader step. When you do Upload Using Programmer the bootloader is overwritten and thus serves no purpose. However, there is another reason for the Burn Bootloader step, to set the correct fuses for your board selection. The fuse settings configure things on the ATmega328 such as clock speed and clock source. If the ATmega328 you are using doesn't happen to have the correct fuse settings for the board selection you're using in the IDE then things may not work or may not work correctly. For this reason it's best to always do the Burn Bootloader step the first time you use the ATmega328 and any time you change the board selection or other settings related to that board selection(such as custom Tools menu settings). Since you're not using an external clock source for your ATmega328 make sure that you don't select a board that is configured for an external clock as this will cause the chip to no longer work until you have connected an external clock.

Thanks for the detailed response. I assume if I get the clock speed wrong, I can't even burn the bootloader / anything to it? The chip I currently have has been programmed for a 14.3mhz (give or take?) external crystal, which I was not planning on using in the circuit. Will that be an issue?

@AndrewP: The clock rate only affects the delay and timing routines; ISP doesn't care about the exact speed provided certain minimums (detailed in the datasheet) are met.

The bootloader only enables serial programming of the device; it is perfectly possible to run Arduino programs without it provided that the code is compiled with the same hardware options (MCU model, clock speed, etc.) that the standalone device/board uses.


text:
No usb serial on Mac
I've been using my Arduino UNO without a hith for a few days now, but suddenly I can't program it anymore.
When I try to programm my Arduino on Mac, I get the following Error:
avrdude: stk500_recv(): programmer is not responding

The USB option under serial port has disappeard (It was there before). Has anyone an idea on how to fix this?
The last thing I did is use the serial port for some communication. A reboot hasn't improved anything.
I tried programming Linux, but it resulted in the exact same result.

Related: http://arduino.stackexchange.com/questions/804/arduino-nano-uploading-gives-error-avrdude-stk500-recv-programmer-is-not-re Does that solve your issue? What board are you using?

No is doesn't solve the problem. Besides that: I use an original Arduino Uno.

On Linux go to computer>var>lock and delete the  serial port lock files

It seemed to be a hardware problem on the board. Thanks for the effort.

You could try re-flashing the firmware for the usb-to-serial chip (atmega8u2) on the uno board.

If I try to upload with no device connected, I get a dialog with the message "port is blocked" and a message in Eclipse's console window that the port is not found.
So I'm guessing you've got a sync problem. UNO should reset automatically when avrdude connects. Try manually resetting it just before you click to start the download. If that works, then the automatic reset has failed.

If I try to upload with no device connected, I still get: "avrdude: stk500_recv(): programmer is not responding"


text:
Control 4 digital outputs with one switch
I want to control 4 digital outputs (d0, d1, d2, d3) with one switch. When the Arduino starts, they should all be in state LOW.
Now, after pressing the button once, d0 should get HIGH. Another push brings d0 to LOW and d1 to HIGH. So actually the 4 outputs shall behave like a bitmask. After every push the bitmask shall increment by one.
d0 LOW
d1 LOW
d2 LOW
d3 LOW

push
d0 HIGH
d1 LOW
d2 LOW
d3 LOW

push
d0 LOW
d1 HIGH
d2 LOW
d3 LOW

Is there an easy way to implement this, without typing every case in the code?
I am glad for any hints.
Cheers and thanks.

As usual with programming, there are many solutions, for example:

You can use a bitmask, put 4 variables in an array with binary values 1000, 0100, 0010 and 0001 and when the switch is pressed, you store the value into each LED pin by comparing the value.
However, a more simpler solution is just use a counter from 0 to 4, if the value is 1, the first LED should be one, then after a switch increase the value, and use modulo 5 (% 5) to go back to 0.

To check if a button is clicked, use a boolean, which check against the previous value. Also implement the debounce algorithm which can be found at the Arduino site.
Without debouncing it could look like this:
#include "stdlib.h"

int buttonPin    =   7;
int buttonState  = LOW;

int led1Pin      =   8;
int led2Pin      =   9;
int led3Pin      =  10;
int led4Pin      =  11;
int ledMode      =   0; // All off, 1-4 means LED 1-4 is on

void setup()
{
}

void loop()
{
   // Add debouncing yourself
   if ((buttonState == LOW) && (digitalRead(buttonPin) == HIGH))
   {
      buttonState = HIGH;
      ledMode = (ledMode + 1) % 5;
   }
   else if ((buttonState == HIGH) && (digitalRead(buttonPin) == LOW))
   {
      buttonState = LOW;
   }

   digitalWrite(led1Pin, ledMode == 1 ? HIGH : LOW);
   digitalWrite(led2Pin, ledMode == 2 ? HIGH : LOW);
   digitalWrite(led3Pin, ledMode == 3 ? HIGH : LOW);
   digitalWrite(led4Pin, ledMode == 4 ? HIGH : LOW);
}

If you put the LEDs on subsequent pins, you can use the following code which is more simpler and works for any number of LEDs:
#include "stdlib.h"

int buttonPin    =   7;
int buttonState  = LOW;

int nrOfLeds     =   4;
int startLed     =   8;
int ledMode      =   0; // All off, 1 means led on pin startLed, 2 means led on pin startLed + 1 etc.

void setup()
{
}

void loop()
{
   // Add debouncing yourself
   if ((buttonState == LOW) && (digitalRead(buttonPin) == HIGH))
   {
      buttonState = HIGH;
      ledMode = (ledMode + 1) % (nrOfLeds + 1);
   }
   else if ((buttonState == HIGH) && (digitalRead(buttonPin) == LOW))
   {
      buttonState = LOW;
   }

   for (int led = 0; led < nrOfLeds; ledPin++)
   {
       digitalWrite(startLed + led, ledMode == led + 1 ? HIGH : LOW);
   }
}

Thank you very much for your detailed answer!

If it helps you, upvote the answer, if it is the correct answer for you, also make it as accepted.


text:
Connecting the cathode of a diode to the output of a multiplexer
From the image, the diodes share the same anode which is driven by 'Do Something'. My question is: through using Arduino IDE, what code should I write that connects the output of the multiplexer (Z) to a specific diode's cathode (Y0 or Y1 or ... or Y7), which in turn is connected to 'Do Something' that drives the cathode probably? In this code, I want the ESP32 microcontroller to connect this cathode to 'Do Something' for say 3 seconds and then switch to the next diode's cathode with a delay of 0.1 seconds [where no diodes' cathodes are connected to Z]       (and so on: in a continuous loop).
Here some code I found online but not sure what needs to be added to get the proper functionality:
int outputs[4] = {4,0,2}; // pins for selecting LED
int inhibit_pin = 15; // pin for turning off all LEDs

void setup() {
  for(int i;i<3;i++){
    pinMode(outputs[i],OUTPUT); // output selection for LED control
  }
  pinMode(inhibit_pin,OUTPUT);
  digitalWrite(inhibit_pin,LOW); // raise high to disable all

}

void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){
    // turn on LEDs based on bit conversion
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    delay(100); // delay .1 sec
  }
}

I don't think that "digitalWrite(outputs,bitRead(j,i));" is actually needed and I am not quite sure of what it does.

bitRead(j,i) reads the i-th bit from a bitstring. e.g The number 6 has the binary representation 110. bitRead(6,2) reads a 1 as it starts from right bit0 = 0, bit1 = 1, bit2 = 1. In your program this code is written to the output pins which control the multiplexer to use Y6. That's all. The program should work as it is. BTW: You will only see an effect if the diodes in the schematic/picture are LEDs, and "Do Somethig" does something i.e provides a constant or fast pulsing voltage.

What is the MUX?

for say 3 seconds and then switch to the next diode's cathode with a delay of 0.1 seconds If you mean you want none of the eight outputs to be driven during the 0.1 second period, you should update your question to clarify.  As is, that is not something your code is doing.

what kind of diodes are you using? ... why do you even need them?

My idea is to use the microcontroller for only controlling the MUX (each time, one Y0 is connected to Z). The 'Do something' Block continuously provides appropriate signals for driving the anode of a diode and Z (cathode of a diode). The diagram only shows a small part of my project, and the 'Do Something' is a very complicated system. It works nicely when one diode is connected directly [without the MUX] to 'Do Something', but now I want 8 diodes, each time one diode gets connected to 'Do Something'.

Why not use 1 diode on Z, and remove the 8 diodes between pins Y0...Y7 of your MUX and  your Do Something block? That would only allow current to flow one way between Yx and Z, using one diode instead of 8.

I rolled-back your latest edit because you deleted the URL for the image but left the image tag in and also the content of your question makes reference to this image.  If you have good reason to get of the image, and it's not clear that you do, remove both the tag and URL and references to it.

Your "do something" common anode input should probably have a pullup to avoid a floating condition.

You should edit your question and put the image back. Without it your description is going to be very hard to follow.

The code you have posted should loop through the 8 possible MUX in/out pins (Y0...Y7) connecting one at a time to pin 3.
Assuming your Y0 through Y7 are each connected to a pin on your "do something" block, the mux should connect each of the 7 pins on your "do something" to Z.
One problem I see is that your code changes the pin select values on the MUX while the MUX is enabled. As you execute your for(int i=0;i<3;i++) loop and toggle the different select bits to S0...S2, the MUX will connect different Y0...Y7 pins to Z, until it settles on the final set of values for S0...S2. You should really set inhibit_pin to HIGH (disabling the mux before entering your for(int i=0;i<3;i++) loop, and then set it to LOW again at the end of the i loop and before the delay. (to re-enable the MUX at the now-completely-selected pin.)
Your description is a little hard to follow, but it sounds like that is what you want.
If you want each pin to be connected for 3 seconds, then not connected to any pin for .1 seconds before moving on to the next pin, you might rewrite your loop like this:
void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){

    // disable the mux while selecting a pin
    digitalWrite(inhibit_pin,HIGH);

    // select a MUX pin
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    // re-enable the mux now that we've selected a pin
    digitalWrite(inhibit_pin,LOW);

    delay(3000); // leave the pin active for 3 seconds.

    // disable the mux for .1 seconds
    digitalWrite(inhibit_pin,HIGH);
    delay(100);
  }
}

Thank you very much!! Out of curiosity, if I had two identical MUXs [same pins] and 16 diodes, then how would the code be changed to connect each of the 8 pins to Z of both MUXs at the same order/time [i.e. Y0 to Z of MUX1 and Y0 to Z of MUX2, then Y1 to Z of MUX1 and Y1 to Z of MUX2, and so on]? Excuse the wording of my question as I am trouble in putting my thoughts into words.

You could drive 2 MUXs with your Arduino, or better yet get a 16 channel MUX (altough with 1 16-channel MUX you could only select one channel at a time.) If you used 2 MUXs your tie their Z pins together, and use 3 different Arduino pins for the channel selector on each MUX. I'd write a channel-selecting function that took a MUX number as input (MUX 1 or MUX 2, say) and used that to look up the pin numbers to select and enable a channel for that MUX, and then my loop would call the function for each MUX in turn.

It looks like you need 4 unique pins for each MUX (3 channel select pins and an enable pin.) You could lower that to 3 unique pins and a shared enable pin if you wrote your code to disable both MUXs, do the channel selection, and then enable both at the same time.

I initially thought that since the two MUXs are to be operated in the same manner, then the code can be used as it is. But since I haven't used Arduino IDE much nor hardware programming in general, I wrote my initial comment to double check and as you said that I need a function to call each of the MUX. Yes, I agree that the two MUXs can share the enable signal, VCC, etc except for Y0-Y7 and Z.

if you are aware of any relevant web pages, please share them with me

If you always want MUX1 and MUX2 to connect their same pins at the same time, you could just split the Arduino outputs and drive both MUXes with the same 4 control pins.


text:
Varible Ramp up speed for motors controlled by joytstick
I trying to create a piece of code which will ramp up the motors speed to a changing value controlled by a joystick. For example joystick requests 120 speed to motors so instead of going 0 to 120 it goes 0, 10, 20 …. 120. But the maximum value will constantly change between 0-130 so it needs to ramp up each time.
This is a snippet of my code to run the motors in the forwards direction.
{
  motorControl = analogRead(joystick);
  motorControl = motorControl / 4;
  if(motorControl > 129)

{

    digitalWrite(pwm2, 0);
    digitalWrite(pwm3, 0);
    speedI = (motorControl - 130);
    speedFadeI =
    Serial.println(speedFadeI-130);
    analogWrite(pwm1, (speedFadeI - 130));
    analogWrite(pwm4, (speedFadeI - 130));

thank you for anyone who has a idea

do you have a question?

I assume from the 0, 10, 20 …. 120 series, that you want to have a linear ramp to the desired speed. This can be done really easily, if your requirements are not to high.
First we define the interval, in which we want to update the speed, and a constant acceleration, that you can choose. The current speed will be saved in a global variable.
#define INTERVAL        100
#define ACCELERATION    51
int current_speed = 0;

I chose an interval of 100ms and the acceleration value, so that it will ramp from 0 to 255 (full speed) in 5s (which results in 51 PWM values per second). Now, in the void loop() function, we use an if-statement with the millis() function to trigger an speed update at the regular interval. For this to work, we need a (here global) variable, that holds a timestamp. (If you don't know this technique, you can see it in the BlinkWithoutDelay example, that comes with the Arduino IDE, and there are many tutorials about this on the web)
Inside the if-statement, we write a second if-statement. It checks, if the current speed is above or below the set point, that comes from the joystick. If it's above, we will substract one speed step (calculated by acceration and interval and divided by 1000, because we used milliseconds and not seconds for the interval), if it's below we will add one speed step.
unsigned long timestamp = 0;

void loop(){
    int setpoint = analogRead(joystick)/4;
    if(millis() - timestamp > INTERVAL){
        if(current_speed > setpoint){
            current_speed -= ACCELERATION*INTERVAL/1000;
        } else {
            current_speed += ACCELERATION*INTERVAL/1000;
        }
        if(current_speed > 255) current_speed = 255;
        else if(current_speed < 0) current_speed = 0;
        analogWrite(pwm1, current_speed);
        timestamp += INTERVAL;
    }

I also added if-statements to cap the current speed between 0 and 255. Otherwise the value would overflow, when written to the corresponding 8-bit timer register by the analogWrite() function.
Of course, this method also has drawbacks. You will have to find a good value combination of ACCELERATION and INTERVAL, because when the current speed reaches the setpoint, it will oscillate around this value. The best way is to set the ACCELERATION, that you need, and choose a good interval based on that.
There are other ways to program this, but I like this way for being really simple.


text:
Using pointers with Arduino
I am learning about pointers.
I was wondering how the memory address is defined in programming. I get different outputs depending on the format I choose for memory address. So I was wondering if it is correct to assume that the format of the memory address is defined by the programmer. I get different results for memory address when I use Serial.print( (long) &ptr1, DEC); and Serial.print( (long) &ptr1, HEX);
 #include <stdio.h>
 int counter = 0;
   void setup() {
    Serial.begin(9600);
   int test1 = 10;
   float test2 = 3.14159;
   char test3[ ] = "This is a character array";
   int *ptr1;
   float *ptr2;
 char *ptr3;
  ptr1 = &test1;
Serial.print("The integer value is stored at ");
Serial.print( (long) &ptr1, DEC);

 Serial.print("The integer value is stored at ");
  Serial.print( (long) &ptr1, HEX);

  }
 void loop() {

    }

My output is:
The integer value is stored in  2296
The integer value is stored in  8f8

You realise you're printing the address if ptr1 here, not the test value (I think...) The formatting shouldn't make any difference - can you add example values that you get (when you print both values in the same program, re-compiling could potentially move these locations.

@Sean I have edited my question. It gives me 2296 when I put decimal format and 8f8 when I put Hex format

"Why do programmers always mix up Christmas and Halloween? Because Dec 25 is Oct 31" in your case "DEC 2296 is HEX 8f8".

You're printing the address of the pointer, not the contents of the pointer.
Say you have the memory map of:
100 20       test1 low byte
101 0        test1 high byte
102 100      ptr1 low byte
103 0        ptr1 high byte

test is located at address 100 and takes two bytes. ptr1 is located at 102 and takes two bytes. ptr1 contains the address of test (100) and test1 contains the value 20.
The different possible combinations of prints are:
Serial.println(test1);  => 20 (contents of test1)
Serial.println(&test1); => 100 (address of test1)
Serial.println(ptr1);   => 100 (contents of ptr1 = address of test1)
Serial.println(&ptr1);  => 102 (address of ptr1)
Serial.println(*ptr1);  => 20 (contents of address pointed to by ptr1).

(note: some of those will require a cast in order for the C++ to select the correct println() overload function.)

Serial.print would not work for &test, I had to put (long) before that. I get different results for Hex and Dec. I have edited my question.

I purposely omitted the casts that you would need to get the right println overloads so it didn't get too cluttered. That doesn't make any difference to what is happening though. You need to learn just what & and * mean.

so 2296 is the same as 8f8 with different format?

You're trying to play with pointers and you don't even know the difference between decimal and hexadecimal...?!?!

so 2296 is the same as 8f8 with different format - yes. Google 0x8f8 in decimal. You can get calculators that will do that for you. Probably is one built into your PC.

When you Google that Google even hands you a calculator right there in your browser.


text:
Is the ATMega328P powerful enough to deal with a lot of SPI data while reading a rotary encoder?
I need to:

Output data to a 128x64 screen with ug8lib (via SPI)
Keep track of the position of a high-precision rotary encoder (1024p/r)
Send about 2 bytes of data up to 120 times per second via an nrf24l01+ board (via SPI)
List item

Would the 3V Pro Trinket board, running an ATMega328P at 12Mhz, be powerful enough for this?
I was originally going to use a way more powerful STM32-based board for this project, but I'm having trouble making it work with my OLED screen, so am considering reusing an old Pro Trinket I've got lying around.

Presumably you'll handle the encoder with interrupts so consider pin choice carefully.  You've not stated the required update rate for the display or the allowed timing jitter for that or the radio.  240 bytes exceeds the nRF packet buffer so it will require a lot of interaction - do you require 240 bytes transferred or only 240 bytes attempted to be sent?  You may also end up tight on RAM.

Sorry, I wasn't very clear. I don't need to send 240bytes every second, but 2 bytes at a maximum of 120x per second. The display doesn't need to be updated too fast, but still about 20-40fps, and it doesn't need to be very precise. The radio however can't have much timing jitter at all.

You may need to just try it and see what difficulties you run into.  If you don't make your code to Arduino-ish you can likely re-use some of it for a different target.  Or try to get the STM32 working.  It's unclear if you've yet put much thought into the unreliability of the radio link.

does the screen have an integrated buffer? if not, then maybe use a second trinket to handle the screen display

You may be hitting a wall with SPI.  I have a 16x4 SPI board driven by an ATMege328P and it is quite slow updating.  However, I just purchased a TFT touchscreen 240x320 (https://amzn.to/2t27B5B) and I'm driving via ATMega328P and it is amazingly fast.  However, it has 8 separate data lines (parallel).  Check out the video I added to my amazon review and you'll see it can keep up with redraws.  Good luck.

The fastest SPI data transfer that I have done is 128,000 bytes in 1 second with an Arduino UNO at 16 MHz. That was transferring data points from an LTC1864 ADC to a SRAM chip for storage, with a simple data acquisition loop timed by hardware.  I think you can make your application work on a 328p if your code does not have too much time overhead.

If you are finding the SPI library too slow, you can also use AVR registers directly, i.e. SPDR, SPCR, SPSR


text:
How to output a true analog voltage at output pin
Regarding my program, it is a program that does some calculations and then outputs a voltage based on the result using analogWrite function. However my problem is that I had done my programming based on a misconception that analogWrite function via PWM does output an analog voltage, where in fact it only "simulates" the analog voltage instead.
Here are the relevant parts of my code :
int pwmOutput = 11;
int pwm = 0;

void compareNewOldVoltageYes(void)
{
  if(pv_Vnew > pv_Vold && pwm != 255)
  {
    ++pwm;           //increasing value
  }
  else if(pwm != 0)
  {
    --pwm;           //decreasing
  }
}

void compareNewOldVoltageNo(void)
{
  if(pv_Vnew > pv_Vold && pwm != 0)
  {
    --pwm;
  }
  else if(pwm != 255)
  {
    ++pwm;
  }
}

void loop()
{
   reading();
   PowerCalculation();

   if(pv_NewP > pv_OldP)
   {
      compareNewOldVoltageYes();
   }
   else
   {
      compareNewOldVoltageNo();
   }

   analogWrite(pwmOutput, pwm);           //analogWrite

   float displayPWMvolt = pwm * 0.0196;

   Serial.print("Output Voltage: ");
   Serial.print(displayPWMvolt);
   Serial.println(" V");

   pv_OldP = pv_NewP;

   Serial.print("Previous Power: ");
   Serial.print(pv_OldP);
   Serial.println(" W");

}

As for the circuitry, output pin 11 is being connected to a 1 ohm resistor and then to GND. (Where I measured the voltage) I am using Arduino Uno board.
UPDATE:
As said in the comments by @DatHa, pwm does not output voltage. Is there a way to output voltage as said, without changing the board?

P.S. Analog write uses PWM and it DOES NOT produce an analog voltage.

@DatHa does that mean it cannot be done this way? Is there another function to output analog voltage?

See @Russell answer on http://arduino.stackexchange.com/questions/10041/can-i-connect-a-pwm-pin-on-one-arduino-to-an-analog-input-on-another

@dpw I don't think that works as my program has to connect to an electronic load via its external programming port and control it using 0-5V.

PWM outputs a specific voltage, or I'm a pirate in the year of our Lord 1734. You can't go above an 8-bit value, and there's always some inaccuracy in reading it.

You basically have three options:

Switch to an Arduino Due which has a built-in DAC which outputs a real voltage.
Add an external DAC chip (such as the MCP4821/2) to create the voltage for you
Use a low-pass filter (R-C network) on a PWM pin.

Of the three options I usually use an MCP4822 since it gives the best results and doesn't cost as much as using a Due.

Thank you. Option 2 sounds really good, but due to time constrains, I went ahead with Option 3 and got the results I wanted.

or use an R-2R ladder as a "poor man's DAC"

@AndreHolzner I count an R-2R ladder the same as a DAC chip but with too many wires to make it practical on your average Arduino.

@Majenko I just wanted to add that there exist "digital potentiometers" or "digipots" that are pretty much R-2R ladders inside a DIP-8 chip. They are cheaper then DACs. (For example X9C103)

@FilipFranik Except they're not R-2R ladders. They're just a chain of resistors with a FET connected to each connection between resistors. There is only R. Many Rs all the same. Yes, if you write it up with the two ends of the potentiometer to VCC and GND you get kind of a DAC, but it suffers the same kind of impedance problems a real potentiometer does. It provides a pair of resistances, whereas a DAC provides a voltage.

At 5V, a 1 ohm resistor will try to sink 1A and far exceed the 40mA specs.  Please use at least a 5/0.040=125 ohm resistor to protect your pin.  And if you put the a capacitor between your resistor and ground, the RC circuit of the capacitor will smooth out the PWM into an analog voltage.
Please try the suggested @russell answer with a 47K resistor and 1uF capacitor, you will get an analog voltage at the junction to use with your electronic load.

As far as I know Arduinos have ADC (Analog to Digital Converters) but do not have any DAC (Digital to Analog Converters). So you can not output a set voltage from any pins based on a digital value.

The ARM based Arduinos usually have at least one DAC channel.

There is no direct way.
In addition to @Majenko
Alternative way: you can use H bridge like L293d to provide continuous level. Many diy inverter circuits are useing this technique.
http://www.instructables.com/id/How-to-Make-an-Inverter-Using-ARDUINO/?ALLSTEPS

NO.. There is no way to get an analog voltage from the Arduino. The best that you can do is to use Arduino as a Buck Voltage converter in linear or boost mode using a voltage regulator, inductor and the mosfet transistor.  You will also might need to use a Mega or Dulorme which provide a PWM frequency other that the standard 50o Hz.
Best luck

I wondered if this would give a more stable output.

You need to add an R in parallel with C1 to discharge C1.


text:
I2C communication, wrong response
With reference from http://www.gammon.com.au/i2c I tried the example there. However I am getting the wrong response and readings. At startup the Master will request for slave address. I should get a reading of "8" but I don't get it. Subsequently, A0 on the slave is connected to a miniature solar panel, that I have tested and it is working, however I keep getting a value -1 from it. No doubt I did modify a little bit to suit my inputs not sure if what I did affected the program.
This is the master code:
    #include <Wire.h>

const int slaveAddressA = 8;

enum {
  cmd_slaveAddress = 1,
  cmd_read_A0 = 2,
  cmd_read_A1 = 3
};

void sendCommand_toSlaveA (const byte cmd, const int responseSize)
{
  Wire.beginTransmission(slaveAddressA);
  Wire.write(cmd);
  Wire.endTransmission();

  Wire.requestFrom(slaveAddressA, responseSize);
}

void setup() {

  Wire.begin();
  Serial.begin(9600);

  sendCommand_toSlaveA(cmd_slaveAddress, 1);

  if(Wire.available())
    {
     Serial.print ("Slave address is: ");
     Serial.println (Wire.read (), DEC);
    }
  else
    {
     Serial.println ("No response to slave address request");
    }

}

void startupTest() {
  Wire.beginTransmission(slaveAddressA);

}

void loop() {

  int val;

  sendCommand_toSlaveA(cmd_read_A0, 2);
  val = Wire.read();
  val <<= 8;
  val |= Wire.read();
  Serial.print("Value of A0: ");
  Serial.println(val, DEC);

  delay(500);

}

This is the slave code:
#include <Wire.h>

const byte my_address = 8;

enum{
  cmd_address = 1,
  cmd_read_A0 = 2,
  cmd_read_A1 = 3
};

char command;

void setup() {

  command = 0;

  pinMode (A0, INPUT);
  digitalWrite (A0, LOW);  // disable pull-up
  pinMode (A1, INPUT);
  digitalWrite (A1, LOW);  // disable pull-up

  Serial.begin(9600);

  Wire.begin (my_address);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted
}

void loop(){
  //everything is done using interrupts
}

void receiveEvent(int howMany)
{
  command = Wire.read();
}

void sendSensor (const byte which)
{
  int val = analogRead (which);
  byte buf [2];

    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
}

void requestEvent ()
{
  switch (command)
  {
    case cmd_address: Wire.write(0x55); break;   // send slave address
    case cmd_read_A0: sendSensor(A0);   break;   // send A0 value
    case cmd_read_A1: sendSensor(A1);   break;   // send A1 value

   }

}

Also I'm wondering if I have to add a "Wire.begin(8);" at the slave program setup. ---------------------------I would like to know what did I do wrongly?
UPDATE: The 2 boards are now communicating with one another. However, requested address gives a '85' instead of an '8'. As for input A0, for example it should show '700' with a little bit of variant, but now it shows a repeated pattern of e.g '0 0 0 400 500 800 1040 1040 1040 800 500 400 0 0 0'

A possible problem is that you are doing an analogRead inside an ISR. ISRs are supposed to be fast, and an analogRead will take over 100 µs. Try doing the analogRead inside loop, and just send the latest reading in the sendSensor function. My (main) computer is currently doing an operating system upgrade, so I can't test this right now.

I'm wondering if I have to add a "Wire.begin(8);" at the slave program setup. - you did that, since my_address is 8.

Regarding my first comment, it looks like my code that you referenced does that as well (grin).

@NickGammon for this case I would like to know for void sendSensor (const byte which) { int val = analogRead (which); in the slave code, where is the which parameter passed?

Here: sendSensor(A0);

As Jot mentioned below, you are in fact sending 85 for the slave address: Wire.write(0x55). You should send: Wire.write(my_address); In my example that was not the I2C address (we know that after all) but an identifier - it was just an example anyway.

Subsequently, A0 on the slave is connected to a miniature solar panel, that I have tested and it is working - really? Can you show a schematic? What voltages is the solar panel delivering?

@NickGammon The solar panel delivers ~3V. However after you request for the schematic again, for some reason the ground wasn't connected properly and after amending it now the display values are showing correctly already. Thank you for your help!

When you send 'buf', how do you know that buf[0] is transmitted first and buf[1] is transmitted second ? Not long ago a bug in Wire library was fixed and it is now allowed to use multiple Wire.send() in the requestEvent() function. I suggest to send two bytes in sendSensor() in the Slave without using the 'buf'.
When you request the Slave addres, you send 0x55. That is not the Slave address. Do you receive 0x55 ?
It is not needed to remove pullup resistors from the analog input pins. It is also not needed to set the pinMode for those pins. You can use analogRead() without something else.
Did you connect the GNDs ? And did you connect SDA to SDA and also SCL to SCL. Which Arduino boards do you use ? Do you know that you can start the Arduino IDE twice, each connected to a board and each with its own serial monitor. That way you can work on both sketches at the same time.
As soon as the Slave is running with Wire.begin(8), the Master can run a i2c_scanner and it should find I2C address 8. That is the first test to verify that the I2C bus is working.

I have checked that the master and slave are indeed connected and working. I missed out the GND connection. The slave address i received is 85 instead.

@bytk - Are you saying it is working now? That the whole problem was a missing ground wire?

@NickGammon It is communicating with each other now, but it doesn't communicate correctly. As mentioned now the requested address gives a '85' instead of a '8' as for input A0, for example it should show '700' with a little bit of variant, but now it shows a repeated pattern of e.g '0 0 0 400 500 800 1040 1040 1040 800 500 400 0 0 0'

The slave address is not returned, but the value 0x55. That is decimal 85.
Reading analogRead() while the input is open, can result into anything.


text:
serial port on RPi
In the Arduino IDE on my RPi on the top there is a header that says, File, Edit, Tools and help.
Following a Magpi article it said to go to tools then serial port and change that depending on what board you use. The only problem is that it's not there, when I click tools I scroll down and there grayed out it says, serial port.
Why is this grayed out? And why can I not change it? Also, what port should be used for an Uno?

It's greyed out because it can't find any serial ports.
That could be because:

There aren't any detected (not got the right kernel modules loaded)
You don't have permission to access the serial ports (are you in the dialout group?)

Have you followed the Linux installation instructions? http://playground.arduino.cc/Linux/All

That would require RTFM :)
For the last many years (on various linux variants including rpi) a quick solution is:
sudo chmod ugo+rw /dev/ttyACM0

after plugging in the arduino.


text:
Expanding analog inputs to the Arduino
I need the Arduino to read about 100 analog inputs. Is this even doable? If not what is the maximum analog inputs I can read into the Arduino (The maximum non trivially would be to use the analog pins that the board already provides).
But can I expand those out? Thanks!!

You know that to scan 100 inputs you will take a quite long time, don't you? Time means something around 10-20 ms for all the acquisition, but anyway you'll get a low sample rate

Could you tell use what you need it for? 100 analog inputs seems excessive. Having e.g. 100 sensors would probably also lead to other issues like power. There might be an easier way of accomplishing what you want without 100 analog input.

Reviving an old thread and violating etiquette, but I am looking for solutions as well and would be interested in seeing Frank Mcculling's code (if he's still around).

Use a bank of 8-channel ADCs with SPI interface.  Sample times can be much faster than the internal ADC. http://ww1.microchip.com/downloads/en/DeviceDoc/21298e.pdf  with 2 MHz clock, and 24 clocks to read and reply, a conversion can be done in 12 uS.  100 inputs can be done in just a few ms total then if you have good loop code to cycle thru 8 inputs on 13 chips.

about reading multiple temperature sensors with just 1 arduino pin use the DS18B20. They work in paralell.

Expanding on part of Majenko's answer, you can use an analog multiplexer like the 74HC4051 to turn one analog port into 8.

Its cousin, the 74HC4067, will multiplex 16 ports. Now with 6 analog inputs on the Arduino Uno, you could have 6 x 16 inputs = 96. The A/B/C controls signals could be paralleled up.
This would let you handle 96 inputs with only 6 extra chips, and pretty simple code. I have code examples on my page about 74HC4051 multiplexer / demultiplexer.
For 8 inputs the code is:
// Example of using the 74HC4051 multiplexer/demultiplexer

// Author: Nick Gammon
// Date:   14 March 2013

const byte sensor = A0;  // where the multiplexer in/out port is connected

// the multiplexer address select lines (A/B/C)
const byte addressA = 6; // low-order bit
const byte addressB = 5;
const byte addressC = 4; // high-order bit

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Starting multiplexer test ...");
  pinMode (addressA, OUTPUT);
  pinMode (addressB, OUTPUT);
  pinMode (addressC, OUTPUT);
  }  // end of setup

int readSensor (const byte which)
  {
  // select correct MUX channel
  digitalWrite (addressA, (which & 1) ? HIGH : LOW);  // low-order bit
  digitalWrite (addressB, (which & 2) ? HIGH : LOW);
  digitalWrite (addressC, (which & 4) ? HIGH : LOW);  // high-order bit
  // now read the sensor
  return analogRead (sensor);
  }  // end of readSensor

void loop ()
  {
  // show all 8 sensor readings
  for (byte i = 0; i < 7; i++)
    {
    Serial.print ("Sensor ");
    Serial.print (i);
    Serial.print (" reads: ");
    Serial.println (readSensor (i));
    }
  delay (1000);
  }  // end of loop

There are two methods of doing what you want:

Add more ADC channels
Multiplex the existing ADC channels

SPI or I2C ADC chips are readily available in a range of resolutions, sampling speeds and number of channels.  They are fairly simple to add to any Arduino.
For instance the MCP3208 will give 8 channels of 12-bit resolution on SPI, which means 3 pins (MOSI/MISO/SCK) + 1 per chip (SS). So 1 chip would be 4 pins, 2 chips 5 pins, 3 chips 6 pins, etc.
Adding lots of chips to the SPI bus though can itself be troublesome with the increased capacitance of all those inputs meaning you have to reduce your communication speed somewhat or add extra buffering to drive the bus with more current.
I2C chips can be harder to have lots of them since there are only a limited number of addresses on an I2C bus - plus on many Arduinos the I2C is also two of the analog pins, which you may not want to sacrifice.
The second option involves using analog multiplexers (eg the 4051) to switch different sources in to the existing analog inputs.
A third option which you probably haven't considered is to have multiple arduinos (or other low-cost microcontrollers) each doing some of the sampling and then implementing some kind of communication method between them (or to a single master). This has the added advantage that it's then possible to sample multiple channels at once (one per microcontroller) speeding up your operation somewhat.

I have been exactly working with the same Issue. I need a program that reads 100 Thermistors...Why? well, some times you need it.
I kinda finished that already.
I tried the 74HC4051 multiplexer / demultiplexer. But, for some reason I didn't get the desired result.
First thing you will find...POWER, you will need an external power supply, in my case I just made a voltage divider and connected the thermistor to that power, then just use the Analog port for reading...
I use I2C protocol, 8 arduino Mega 7 slaves and One master. and since send send Integer, float, and blah, blah was kinda not helping I just made it for It can send the Analog reading over I2C and the master makes all the desired conversion.
If you still are interested, I can send you the source code for master and slaves. With this template you can connect up to 50 arduinos and the master will look for every arduino connected in the network and ask for data.
Regards