text:
What is the best way/module to talk to an Arduino from far away (WIFI)?
I am new to Arduino and IoT. I plan to build a product that I will connect to an app and they have to be able to communicate from a very far distance (kilometers).
Bluetooth is not a good option then (because the distance is too far). So would Wifi work? I read something about a module called esp8266 that might be what I am searching for.

esp8266 can communicate 100's of metres (I've seen claims of over 1km - but that would be with ideal conditions and directional antennas) ESP8266's big brother, the ESP32, has been apparently made to communicate over 10km - again, very ideal conditions and specific equipment required

Plus add on in esp32 you get Bluetooth but yet it's not having any arduino support for that.

Alright! A esp32 could be a good solution. I might need it for a bit longer distances though. But thanks a ton for your suggestion

I'd suggest looking into LORA.

Esp8266 range is about 400m. So if you have your mobile within 400m then you may be able to communicate. But for long distance communication I would not prefer but if you have any Internet connection available nearby esp then you may be able to transmit your messages via it. Well for long distance communication  I would prefer you to use any GSM shield in which you need to plug in a sim card and it can be used upto when you have coverage in that area.

Alright! Is is possible for iOS apps to communicate with GSM shields?

Arduino GSM Shield works the same as a mobile does. It uses the SIM Card to communicate. So as that suggests you can use it send Texts, Call anyone, and use the Data connection to connect to internet. Please refer the Arduino Page

Ah alright! I have a sm5100b-d at home that might be what I am searching for

I don't really now much but I think it might work I am not sure but it might work!

I don't really now much but I think it might work I am not sure but it might work!

The simplest option is to use GSM for the communication. Range isn't an issue, since point A isn't communicating with point B, instead point A and point B are both communicating via third party communication subsystem C which has a much greater coverage than anything you could build yourself.
I use GSM modules for communication with agricultural monitoring and control systems at remote locations. It works well, and you're pretty much guaranteed to have a signal.
For those times when GSM isn't a possibility (no signal, or the customer doesn't want the subscription cost) you really need line of sight between the two locations. Then you can use a highly directional antenna (e.g., parabolic dish or Yagi array) to extend any other suitable wireless communication signal over a long range (WiFi can reach tens of kilometres with parabolic dishes) and there are companies that specialise in that kind of equipment (such as this one that claims 8 mile range - of course you need two of them, one for each end of the link).  Of course, with some skill and determination it's possible to get incredibly long distances from WiFi. Not for your average user though...

appreciate your answer and help a ton!!

LoRa is apparently the most popular low-speed, low-power, wide-area network at the moment.
Many people use LoRa for direct point-to-point links around a kilometer.
Other people use LoRa for "last mile" wireless links as part of a LoRaWAN to some gateway hard-wired to the internet, much like a Wifi access point -- except trading off data rates in order to get longer wireless range than WiFi.
details:

"LoRa is de facto dominant" -- "LoRaWAN across the globe: LoRa Internet of Things networks overview"
LoRa range tests using the RFM95 Anarduino LoRa Modules, similar to the , LoRa IoT Development Kit (using a "LoRa Bee"), RFM95W LoRa Module for Arduino, RFM95W Breakout Board for LoRa, RFM95 LoRa mikroBUS Module, etc.
"LoRa range experiments Urban test" using the Microchip RN2483 module; I can't quite see which breakout board he's using -- I'm guessing it's one of the Sodaq LoRabee RN2483, the RN2483 LoRa Technology PICtail, the Azzy RN2483 breakout board, the Azzy LoRaWAN RN2483/RN2903 Breakout board , etc.
The Vinduino measures wind and soil moisture using an Arduino and reports back those measurements with a Globalsat LM-210 LoRa module
"LoRaWAN ... Range: 2-5km (urban environment), 15km (suburban environment)" --
"11 Internet of Things (IoT) Protocols You Need to Know About"
LoRaWAN Part 1: How to Get 15 km Wireless and 10-Year Battery Life for IoT
"low power wide area (LPWA) technologies have become popular. In various LPWA technologies, narrowband (NB)-IoT and long range (LoRa) are two leading technologies." -- "A survey on LPWA technology: LoRa and NB-IoT"
"The LoRa shield: an Open Source Arduino’s long-range communication module" apparently uses the Open-Electronics LoRa shield for Arduino - Mounted
"Building your own private LoRa network" mentions several different LoRa shields
The LoRa Alliance
arduino-lmic: the IBM LMIC (LoraMAC-in-C) library, slightly modified to run in the Arduino environment
"LoRa and Long Range Wireless IoT"
"The low data-rate (down to few bytes per second) and LoRa modulation lead to ... more than 22km (13.6 miles) in LOS links and up to 2km (1.2miles) in NLOS links in urban environment (going through buildings)." -- "Extreme Range Links: LoRa 868 / 900MHz SX1272 LoRa module for Arduino Waspmote and Raspberry Pi" tested a SX1272 LoRa module on a Multiprotocol Radio Shield on an Arduino Uno and links to a few other LoRa modules / LoRaWAN kits.


text:
Two Timer Interrupts, One Incorrect?
I'm trying to replicate a waveform exactly using external and timing interrupts. I've got an external that's setup as a 0ms reference, TIMER1 which is used to determine on time, and TIMER2, which sets the low period. Unfortunately, I can't get the pin low for 2ms. TIMER2 must have something wrong with it, but I can't find it. Instead of banging my head against the wall, I thought I'd ask you guys. Anyone know the answer?
//3 is interrupt for Timing
//4 through 11 are Time dependent receivers
//3-11 Pins 12-19

//Current Serial Byte(Letter or Number)
char incomingByte = 0;
//Previous Byte in the Serial Chain
char previousByte = 0;

//Iterator for Interrupt Values
volatile unsigned int maincount = 0;

//Time of High Period or Timer Duration
volatile unsigned int timerhigh;

//Output Pin for Timer Waveform
volatile unsigned int waveout;

//Time for Timer Delay in milliseconds, default tim
volatile unsigned int groundtime = 0;

//Receiver Pins in an Array, except for 3, which serves as 0 source reference
int pins[9] =
{
  3,4,5,6,7,8,9,10,11
};

void rising()
{
  // set up Timer 1
  TCCR1A = 0;  // normal mode
  TCCR1B = bit(WGM12) | bit(CS11);  // CTC, scale to clock / 8
  OCR1A = timerhigh;          // time before timer fires
  TIMSK1 = bit (OCIE1A);            // interrupt on Compare A Match
}

//Sets Pin Low, then sets up another timer interrupt for the jump back to high
ISR(TIMER1_COMPA_vect)
{
 //Brings Pin Low for Keypress
 //Serial.println("We're in Timer 1");
 pinMode(waveout,OUTPUT);
 digitalWrite(waveout, LOW);

 //Stop Timer 1
 TCCR1B = 0;                      // stop timer
 TIMSK1 = 0;                      // cancel timer interrupt

 //Disables Interrupts Before Messing
 cli();
 // set up Timer 2
 TCCR2A = 0;  // normal mode
 TCCR2B = 0;
 //  TCCR2A = bit(WGM21) | bit(CS21);  // CTC, scale to clock / 8
 TCCR2A = (1 << WGM21); //Enables CTC for timer
 TCCR2B = (1 << CS21); //Sets 8 bit prescaler
 OCR2A = groundtime;          // time before timer fires
 TIMSK2 = (1 << OCIE2A);

 //Cancel Rising Interrupt on D3
 EIFR = bit (INTF1);
 //Reenables interrupts
 sei();
}

//Timer Interrupt for Low Period
ISR(TIMER2_COMPA_vect)
{
//Serial.println("WE'RE IN TIMER2");
//Brings Output pin high
digitalWrite(waveout, HIGH);

//Stop Timer 2
TCCR2B = 0;                      // stop timer
TIMSK2 = 0;                      // cancel timer interrupt

//Cancel Rising Interrupt on D3
 EIFR = bit (INTF1);
}

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

//Sets all the pins for output use
for(int i=0;i<8;i++)
{
  pinMode(pins[i], INPUT);
}

//Sets Reference Pin as Input
pinMode(3,INPUT);

//Begins Serial
Serial.begin(115200);

//Cancels Timer 1
TCCR1A = 0;  // normal mode
TCCR1B = 0;  // stop timer
TIMSK1 = 0;   // cancel timer interrupt

//Cancels Timer 2
 TCCR2A = 0;
 TCCR2B = 0;                      // stop timer
 TIMSK2 = 0;                      // cancel timer interrupt
detachInterrupt(1);

}

void loop() {

  //Time of Ground Drop(2 mS), Universal for all letters and offsets
  groundtime = 40000;     // spark time (4000 * 500 nS) = 2 mS

  // because of prescaler of 8, each unit is 500 nS (0.5 µS)

     if(Serial.available()> 0);
    {
   //Reads Serial Value and assigns to incomingByte
   incomingByte = Serial.read();
   attachInterrupt(1,rising,RISING);
    }
  //  noInterrupts ();  // atomic change of the time amount

   //In this area, we'll set the output pin to be used by the timing interrupt,
   //and the time delay off the default waveform present on pin 4

   //We can use switch case arrangement, don't know if that's the optimal setup though
 switch(incomingByte)
 {
   default:
   //Do Nothing
   break;

   //Cases FOR ALL THE LETTERS
   case 'a':
   break;
   case 'b':
   break;
   case 'c':
   break;
   case 'd':
   break;
   case 'e':
   break;
   case 'f':
   break;
   case 'g':
   break;
   case 'h':
   break;
   case 'i':
   break;
   case 'j':
   break;
   case 'k':
   break;
   case 'l':
   break;
   case 'm':
   break;
   case 'n':
   break;
   case 'o':
   break;
   case 'p':
   break;
   case 'q':
   break;
   case 'r':
   //Output pin 17 Frequency Pin 10
   //microseconds
   timerhigh=8000;
   waveout=9;
   break;
   case 's':
   break;
   case 't':
   break;
   case 'u':
   break;
   case 'v':
   break;
   case 'w':
   break;
   case 'x':
   break;
   case 'y':
   break;
   case 'z':
   break;

   //Cases FOR ALL THE NUMBERS
   case '0':
   break;
   case '1':
   break;
   case '2':
   break;
   case '3':
   break;
   case '4':
   break;
   case '5':
   break;
   case '6':
   break;
   case '7':
   break;
   case '8':
   break;
   case '9':
   break;

   //Cases FOR ALL THE PUNCTUATION
   case '.':
   break;
   case ',':
   break;
   case '!':
   break;
   case '"':
   break;
   case '#':
   break;
   case '$':
   break;
   case '%':
   break;
 }

//Enables Rising Interrupt for 0ms detection
//attachInterrupt(1,rising,RISING);

//Reenables interrupts after offset time change
//interrupts ();
}

Which MCU? What clock frequency?

Turns out the problem was that timer 0 and 2 on the arduino uno are 8 bit. Set a different prescaler and I'm golden
// set up Timer 2
    TCCR2A = 0;  // normal mode
    TCCR2B = 0;
    //  TCCR2A = bit(WGM21) | bit(CS21);  // CTC, scale to clock / 8
    TCCR2A = (1 << WGM21); //Enables CTC for timer

    TCCR2B |= (1 << CS21);
    TCCR2B |= (1 << CS22); //Sets 256 bit prescaler
    TCCR2B |= (0 << CS20);
    OCR2A = groundtime;    // time before rising edge
    TIMSK2 = (1 << OCIE2A);
    //Cancel Rising Interrupt on D3
    EIFR = bit (INTF1);
    //Reinables interrupts

source: Stack Exchange

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

sort: votes


text:
How can I connect to an Arduino using WiFi?
I'm working on building a solar powered, Arduino based weather station. The weather station consists of a temperature sensor and a photoresistor, and I plan to add an anemometer in the future. I would like to connect the weather station to my wireless network so that I can retrieve the sensor data from my computer without having to run wires (I live in a rental).
What are the different options for connecting the Arduino to WiFi? I've looked at ethernet shields, WiFi shields, and something called Xbee, but I don't understand what each of them are for.
I also have a wireless home router that I could use. Is it possible to connect my Arduino Uno to the router via the routers ethernet or USB port and then receive data from and send commands to the Arduino wirelessly over my home network? If so, how would this be accomplished?
I currently have a bare Arduino Uno.

Do you have an Ethernet shield?

You need to clarify your question: what does "communicate with it" mean? Upload sketches? Send commands to a sketch? Get data from a sketch?

I've attempted to add detail and context to the question. I do not have any shields currently.

I don't think any revision of the official Uno has an ethernet port. I guess you must have an Arduino Ethernet (which is similar), or perhaps an unofficial clone of some kind?

I've edited the question to specify the ethernet port on the wireless router. So the question is: [Arduino + ? + (Wireless Router OR ?) = Arduino sending data over my wireless network].

Also have a look at adafruit cc3000 wifi module. If you need to log data on internet server, wifi/ethernet is recommended, if you just need the data on your pc, a cheaper option would be using motinos from low power lab.

You have a few options for connecting your Arduino to the network/Internet.
Ethernet
Something like the Arduino Ethernet Shield allows you to plug in an Ethernet cable from the wall or router into your Arduino. Obviously, the main limitation is that your device is now tethered by the cable. For outdoor use, I wouldn't do this.
WiFi
The Arduino WiFi Shield allows you to connect to your home WiFi network. This is just like the Ethernet except its now wireless.
The ESP8266 is a cheaper alternative that, with the default firmware, has the same functionality as the WiFi Shield. Be careful that you power it with 3.3V and not 5V as the rest of the Arduino. It also uses 3.3V logic levels so don't connect the Arduino's TX pin directly to the ESP's RX pin; use a voltage divider.
RF
If you have a lot of sensors or other devices that need to communicate with each other, the best option is usually an RF module. You have many options here, XBee being one of them. Check out the Sparkfun XBee Buying Guide to look at all the options available. And that's just XBee. There are many other wireless options available, at all sorts of prices.
The thing with RF is that none of these will connect to the Internet. You will have all your devices communicate with each other or a base station, which will then be connected to the network by either a WiFi or Ethernet module.
Wireless Router Serial
Depending on what kind of wireless router you use, you can have the Arduino communicate directly with it and use that as your connection to a network.

Arduino - Cheap wifi connectivity
Converting your Ethernet Shield to a wireless shield

As for "RF" communication, you can also use the popular nRF24L01+ modules. There are some good libraries out there for this. The issue with the RF link is that you need to have another Arduino or Raspberry Pi etc. running as the "receiver" which then is connected to your computer where you want to store/view/analyze the data.
For Wifi there are now also CC3000 shields available  http://www.adafruit.com/products/1534

While researching the options you provided I came across the Yun. Would that be a more straightforward option? Thanks.

Maybe. never used it myself. The shields aren't hard to interface with and may be cheaper.

Marry OpenWrt and your Arduino
Get a small OpenWrt-capable router like "TP-Link TL-WR703N", flash it with the current stable version of OpenWrt and connect your Arduino to the router's USB port.
This solution ist half or less of the cost of WiFi-shields and has far more power.
...and cheaper as a YÙN.
Smart home automation webserver on OpenWRT router WR703N interfaced to Arduino, compared to Raspberry Pi and Ubuntu may be a starting point to read about this and your favorite search engine will find many more links about marrying WR703N and Arduinos...
(!) Please see https://arduino.stackexchange.com/a/1754/653 too....

ESP8266 is a cheap 5$ wifi module with UART, SPI connectivity. This can be integrated with Arduino seamlessly either through the stock firmware using AT commands, or by writing custom firmware using the SDK provided and GIPO available. For more reference http://www.esp8266.com/

I've been working with xbee on the arduino and raspberry pi for a few months now. Whilst it does have it's issues and quirks, it is a great tool in the communication chain. It's not perfect but given the mesh side of it, for me it reaches further than my wifi and can even be more reliable (my raspberry pi with wifi occasionally drops out, however the connected xbee continues to function in the background.
Specifically in my case it allows for a serial connection between my devices (being several arduinos, a raspberry pi (coordinator) and my mac (used primarily for monitoring but also occasionally injecting serial data)). In this case it's perfect. It doesn't allow internet access or access beyond the xbee framework, but that suits me perfectly since implementation is as simple as Serial.print and Serial.read with no Ethernet overhead.

I use Spark Core which is a very easy to use Arduino programming platform. This platform was built on the primus that WiFi should be easy to use and cheap. Can even program the Spark Core from anywhere, any time.

How does it compare to XBee in terms of: price (including Arduino connecting stuff such as a shield), distance range, programming (on Arduino)?

You could try a Arduino Yun, it is like a Uno but it has a WiFi directly on the board.
There is a part in the "Guide to the Arduino Yún" called "Configuring the onboard WiFi", that describes how to configure the WiFi.

Hi, could you edit your answer with some more information. OP already knows about the Yun so your answer would be more useful if, for example, it guided people to how to use the WiFi chip on it.

What you want is pretty easy to do, and the code exists already.  But the way I invision it, you won't connect the sensor Arduino to your wifi.  Instead, you'll use another Arduino as your gateway like this:
Sensor Arduino:  Located outside, connected to temperature sensor, wind speed, rain gauge?
Gateway Arduino: Located inside, w/ Wiznet 5001 ethernet shield
The Sensor Arduino and Gateway Arduino talks to each other using a VERY easy to use wireless transceiver, nRF24L01+.  The wireless modules are $3 each, and the library for use is very mature.  All the sensor data is easily communicated to the Gateway using this library.
The Gateway Arduino w/ the ethernet acts as a webserver, enabling any computer in your local network to open up a page and view current conditions.  Look at this page for the Arduino code:
http://arduino.cc/en/Tutorial/WebServer
You want to also save historical temperature/wind speed information right?  This is the best part! The Gateway Arduino can push data to a service like Xively, a free web-based data collection service that also gives you a nifty way to visualize/graph your data.  There is a little hiccup with using the Wiznet along with the nRF24L01 module.  The wireless module and ethernet shield both use the same bus to communicate, so take a look at this blog to see how you can use both at the same time:
http://www.heald.ca/content/arduino-ethernet-nrf24l01-and-pachubecosmxively
Xively also lets you make that data public or private, so you can chose to contribute your weather station data to the community.
Some other notes:
I like nRF24L01+ modules because they're dirt cheap.  Xbee modules cost more than the Arduinos themselves.  You can keep adding nRF24L01+ modules around the house once you establish a gateway.  The same cost problem exists with wifi shield - expensive.

If you want a cheaper alternative to add WiFi capabilities to Arduino look at ESP WiFi shield.
It works great with WiFiEsp library.
Programming model is exactly the same as Arduino WiFi Shield

Check ESP8266 wifi module , it's a cheap module and can be controlled using any microcontroller by AT commands , also it's Soc so you can use it standalone .

Using the ESP8266 sield is error prone, requires an update that needs to be flashed, some soldering required, and it's not appropriate for a production environment. Also, there are issues with the power supply because you need to have a separate 3.3V power supply.  It's 2016 (!) and there are a bunch more options available now.
"The UNO WiFi board is the Arduino UNO with integrated WiFi." http://www.arduino.org/products/boards/arduino-uno-wifi
and
"The Star Otto is the first Arduino board featuring the STM32F469 processor with WiFi." http://www.arduino.org/products/boards/arduino-star-otto (Actually, as of October, it's still not available, "Coming Soon").
Please note these two boards are from the OTHER Arduino organization.

After several trials & errors in my IoT project, I would recommend working on ESP32 over ESP8266(and also Arduino Uno & Nano), except if you know very well the scope of your project.
Advantages of ESP32 over ESP8266:

Bigger RAM, ESP8266: 32KB instruction & 80 KB user data, ESP32: 520 KB

I'm working on an IoT project and trying to authenticate the device on GCP using a certificate. The root certificate of GCP is already about 120 KB, so it does not fit into ESP8266. There are alternatives but that complicates things.

ESP32 has bluetooth & ESP8266 not

Well at some point of your IoT project you might want bluetooth to connect your device with your phone ...

Some versions of ESP32 has integrated ports for the camera (search ESP32 CAM)

With ESP8266 you can surely use a camera but that will involve more coding & wiring and potentially worse performance.
And at last, I tried to wire a wifi chip with Arduino Uno & Nano but I encountered some bugs and problems with the AT commands. Thus now I'm quite happy with ESP32 because everything is integrated.

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

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


text:
Rotary encoder on Uno and interrupts issue
This question is regarding a project using an Arduino Uno.
I have one of these quadrature rotary encoders.
I'm using a slightly modified version of the code from the article, Quadrature Encoder too Fast for Arduino (with Solution), which uses a library called digitalwritefast.
My version of the code on pastebin - I modified to use different pins for the Uno and a single encoder:
#include <digitalWriteFast.h>  // library for high performance reads and writes by jrraines

#define c_LeftEncoderInterrupt 0
#define c_LeftEncoderPinA 2
#define c_LeftEncoderPinB 3

volatile bool _LeftEncoderBSet;
volatile long _LeftEncoderTicks = 0;

void setup()
{
  Serial.begin(115200);
  pinMode(c_LeftEncoderPinA, INPUT);
  digitalWrite(c_LeftEncoderPinA, LOW);
  pinMode(c_LeftEncoderPinB, INPUT);
  digitalWrite(c_LeftEncoderPinB, LOW);
  attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING);
}

// Interrupt service routines for the left motor's quadrature encoder
void HandleLeftMotorInterruptA()
{
  _LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB);   // read the input pin
  _LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1;
}

void loop()
{
  Serial.print(_LeftEncoderTicks);
  Serial.print("\n");
  delay(20);
}

I am attaching output A of the encoder to pin 2 and output B to pin 3.
This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying c_LeftEncoderPinB accordingly).
I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).

The code you started from was never meant for bi-directional rotary encoders. I'd suggest looking for a proper rotary encoder library (that also handles de-bouncing). That might safe you some headaches.

What happens if you use digitalRead instead of digitalReadFast2?

Please do not use pastebin on SE, it is not recommended, in case the link dies (there is a post about this on Meta somewhere). It is far better, and easier for us, if you just post the code directly into your question/answer.

OK embarrassingly it turns out my wiring was wrong! I was going astray as it was working in both directions as described, even when only one of the outputs was connected, as long output B was connected to an interrupt. Once the wiring was sorted everything worked perfectly, in both directions, using just one of the interrupt ports.

When turning one way, A is asserted, then B is asserted, then A is deasserted then B is deasserted. You can detect this because A is asserted first, even if you can't tell when B has changed. But if you turn the opposite way then you fail to detect the initial assertion of B, and the code fails.
What you may be able to do is use PinChangeInt to capture the pin change interrupt rather than an external interrupt. This should allow you to use almost any I/O pins on the Uno for the encoder.

Hi Igancio. Could you clarify - what is it exactly that causes the detection failure on pins other than pin 3? I was assuming that it being an interrupt pin didn't make any difference since we're not actually setting an interrupt on this pin?

The code needs the interrupt in order to work. No interrupt, no work.

:( I don't understand. The interrupt is working on pin 2. I'm reading from pin 3 after the interrupt, not setting an interrupt on it directly. In the original code, the author is using pins 19 (A) and 25 (B) on an arduino mega. Pin 25 on the Mega is not an interrupt pin either

My first thought is that something else is off because there is no reason that shouldn't work.  It will of course only count 1/4 of the ticks since that's how it was designed to work for very fast motors.  I can't comment yet but to Gerben above, I think it is meant to be bidirectional as indicated by the ternary operator.  My guess is the problem is with the digitalReadFast library and I would be interested to know if this works when using digitalRead() instead.
My second thought is that this is usually not the best way to do things.  Firstly, you would need a really fast motor for the read fast function to matter.  Secondly, you're sacrificing resolution by only using one interrupt instead of two.  The more generally accepted method is to attach both pins of the encoder to an interrupt.  Alternatively, you could use pin change interrupts which allow any pin to be used as an interrupt.  However, there are only 3 interrupt service routines on the Uno, one for each port of pins.  Whenever one pin on that port triggers, the ISR triggers and you need to keep track of the pin states in order to do anything with it.  Here's a good example of the first and info on the second method.

authors: Ελπινίκη Μαρούλη

authors: Никита Чаузов


text:
Does porting code to different MCU clock frequency affect serial baud rate?
Tried to upload my Arduino Uno sketch that writes to serial UART at 9600 baud rate onto my ATtiny2313 running at 1MHz. Not getting the signal on the ATtiny, does this have to do with my clock frequency of the MCUs being 16 vs 1MHz?

You'd need to set F_CPU to 1. However the only way to do this is to create a new board inside the hardware folder. Once created it will fix delay, millis and serial.

Yes, it does. As can be seen in the "USART" section of the datasheet the baud rate is generated directly from both fosc (aka FCPU) and the value contained in UBRR. The tables at the end of the section gives the appropriate value for UBRR for a given CPU frequency, desired bit rate, and state of the USART clock doubler.

Thank you, where can i find more info on how to get my 16mhz Arduino uno sketch to properly work on Attiny. I guess i must change the FCPU and UBRR?

Also would it port better if i used a ATMEGA8 instead of the ATTINY2313.
Please let me know if there is any great beginner bookss that will catch me up on becoming an avr expert :)


text:
Smaller version of the Mega
I'm currently working on a Arduino Mega (GPS + IMU + SD card logging + BT). I need the Mega for extra memory and serial port.
I would like to transition to something with a smaller form factor now. I need help with suggestions for a smaller form factor board/version of Mega.
Any suggestions?
I can't really find anything.
The only small size yet meeting requirements (in terms of memory) option seems to be a Microduino -
but I'm not whether all the libraries (SDfat etc.) will work on this.

It should be possible to make something smaller with an ATmega2560, but realistically most of that market is claimed by little ARM cortex boards which are yet more capable - Teensy for example.

@O.K. Microduino appears to be a company, not a single product. What board did you go with? Also, you link appears to be broken.

@Cerin we eventually used a Teensy 3.2... btw this post was 2+ years old, so Microduino may have changed the product links

@O.K. The Teensy does indeed look exactly like what you described. I was looking for something like that myself. Thanks.

The ATmega1284P provides 128kB of flash, 16kB of SRAM, 4kB of EEPROM, and 2 USARTs in a 40/44/49-pin package. Mighty 1284P provides Arduino support for the '1284P.
There aren't too many actual boards that feature it, but it can be used very easily on a breadboard or custom PCB with a programmer.

thanks Ignacio. I think I will go for the Microduino (link in my ques), which as mentioned by Nathan uses the ATmega1284 you mentioned.

Look for "Mega2560-CORE" on ebay.
Some information:
http://www.inhaos.com/product_info.php?products_id=88

The link uses the same chip that Ignacio recommended.  The libraries will need some minor edits, but many of the standard ones do have a 1284P fork.  It is mostly just redoing pin assignments, or adding the 1284P to the board definitions.  I am working on a similar project and have gotten the 1284P to work with SDfat, a bunch of standard GPS libraries, and TinyGPS++ .

Thanks Nathan, good to know someone has tried using 1284 with the existing libs. I want to avoid any major/complex work in porting libs; your comment is helpful here. Also, if you don't mind, can you share exactly which 1284 board you are using?

I am using a breadboard version documented here: https://maniacbug.wordpress.com/2011/11/27/arduino-on-atmega1284p-4/  The included zip file has some already adapted libraries but adapting the others wasn't too hard.  Basically you just have to search 1284P and library for the major ones.

I like Jack Christensen's Might Mini design so much I sell it assembled on eBay, username hexinverter. That 2K of RAM in Nanos and the like is just painful. Anyone interested in making their own can find the design and BOM here: https://github.com/JChristensen/mini1284 and a boards.txt for 1.0.5/6 here: https://github.com/JChristensen/mighty-1284p ... all derived from and mentioned in the ManiacBug post and discussed at arduino.cc forums.


text:
Adafruit Feather M0 WiFi - ATSAMD21 + ATWINC1500 Firmware updater
I have a Adafruit Feather M0 WiFi - ATSAMD21 + ATWINC1500 that indicates the firmware installed is too old for the Wifi101 library (Version 0.16.1).  I have been trying to do a firmware update but when I run the Wifi101 Firmware updater, the GUI indicates that there are no compatible boards connecter.  The board I have selected is the Adafruit Feather M0.  I tried selecting the MKR1000 and the GUI seemed to think that was okay, but after starting the FW update fails.    Which board should I be selecting to get the Firmware Update running?
Per the comment below, I should have mentioned that I did follow the instructions at https://learn.adafruit.com/adafruit-feather-m0-wifi-atwinc1500/updating-firmware.  One of the pictures showed the board as Adafruit Feather M0, which is what I do have selected, however the WiFi101 Firmware Updater GUI says the board is unsupported.

https://learn.adafruit.com/adafruit-feather-m0-wifi-atwinc1500/updating-firmware

did you notice "If you are using a Feather M0 or WINC1500 breakout, don't forget to update the pins as necessary with setPins()!"?

In the picture above, partially obscured by the board selection dialog, the WiFI.setPins(8,7,4,2); line can partially be seen.  I believe the message above 'No supported board connected', seems more to do with the Adafruit Feather M0 being selected than the pin configuration.

try it with older version of the fw updater, before they added update for the NINA fw and board selection

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


text:
Is there a Arduino UI library that provides dialog box and button functionality at a minimum?
I have been looking at the Arduino TFT Library and it supports all the bits and pieces for making a simple display, but I am looking for something a little higher level that has primitive dialog box and button capability, and presumably, the ability to layer the display so I can push and pop display elements.  Is there a higher level GUI library for Arduino TFT displays?

a quick search found this ...https://youtu.be/UEKrithNr1g

Take a look at this library. Will this do all that you want?
https://github.com/AndreiDegtiarev/AWind
I have not tried it yet but I would like to.
Edit:
I just remembered this https://github.com/ImpulseAdventure/GUIslice
https://github.com/ImpulseAdventure/GUIslice/wiki
A lightweight GUI framework for embedded displays
The library supports creation of multiple pages of buttons, text, images, checkboxes, sliders and other graphics primitives. New UI / widget types can be created easily.
It works with many existing TFT libraries. There also is a drag & drop builder application.  https://github.com/ImpulseAdventure/GUIslice-Builder


text:
The program keeps skipping over the running 1 and 2 states even though the prereqs are met
The serial prints are for troubleshooting. All outputs are LEDs for testing purposes. The running 1 and 2 states are sometimes skipped over, but not always. I think this is from the light sensor being bad and jumping up and down, but using a higher value does nothing. I also tested the light sensor in the example program and got 1s and 2s so that really shouldn't be the problem. When it does work and the second light sensor is covered (the one that measures sugar level) it continuously cycles through and never returns to ready state. If more detail is needed please let me know
//Digital Inputs
int measureSwitch = 13; //switch that sets 2 tsp and 1 tsp

//Digital Outputs
int motor = 12;
int buzzer = 11;
int readyLed = 10;
int running1Led = 9;
int running2Led = 8;
int doneLed = 7;
int sugarLevelLed = 6;

//Analog Inputs
int cupSensor = 20; //the light sensor should read 0 when the cup is resting on it
int lightSensor = 100; // the sugar should cover up thelight sensor so the light can pass thru, making it zero

//different run times

int running1Time = 100; //1 tsp tentative times
int running2Time = 250; //2 tsp tentative times
int buzzerTimer = 200; // how long the buzzer will go off for

void setup() {
  Serial.begin(9600);
  pinMode(measureSwitch, INPUT);
  pinMode(motor, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(readyLed, OUTPUT);
  pinMode(running1Led, OUTPUT);
  pinMode(running2Led, OUTPUT);
  pinMode(doneLed, OUTPUT);
  pinMode(sugarLevelLed, OUTPUT);
}

//Ready State

void readyState(){
  digitalWrite(readyLed, HIGH);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

//Running 1 State

void running1State(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, HIGH);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, HIGH);
}

//Running 2 State
void running2State(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, HIGH);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, HIGH);
}

//Done State
void doneState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, HIGH);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, HIGH);
  digitalWrite(motor, LOW);
}

//Waiting State
void waitingState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, HIGH);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

//Sugar Level State
void sugarLevelState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, HIGH);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

void loop() {
  while(analogRead(A0) > lightSensor){ //when there is no cup placed on the
sensor, be in ready state
    readyState();
    Serial.println("READY STATE");
  }

//when the cup is on the sensor and the switch is set to 1 tsp
    for(int time1 = 0; ((time1 < running1Time) &&
                        (analogRead(A0) < cupSensor) &&
                        (digitalRead(measureSwitch) == HIGH)) ; time1++){
    //run the running 1 state for 4 seconds
      running1State();
      delay(1);

      Serial.println("RUNNING STATE 1");
      Serial.println(time1);

  }

    //when the cup is on the sensor and the switch is set to 2 tsp

    for(int time2 = 0; ((time2 < running2Time) && (analogRead(A0) < cupSensor)

&& (digitalRead(measureSwitch) == LOW)); time2++){

//run the running 2 state for 8 seconds

      running2State();
      delay(1);
      Serial.println("RUNNING STATE 2");
      Serial.println(time2);
      Serial.println(analogRead(A0));

  }

  for(int buzzerTime = 0; buzzerTime < buzzerTimer; buzzerTime++){

    doneState();
    Serial.println("DONE STATE");
    Serial.println(buzzerTime);
    delay(1);
  }

  while(analogRead(A0) < cupSensor){
    waitingState();
    Serial.println("WAITING STATE");
  }

  while(analogRead(A1) > lightSensor){
    sugarLevelState();
    Serial.println("SUGAR LEVEL STATE");
  }
}

Try pulling the output of the light sensor to ground via a 10k resistor, that should calm the values.
Note that you are going to need to completely change the value of the variable lightSensor. This is because it will now be outputting different values due to the extra resistor to ground.

simulate this circuit – Schematic created using CircuitLab

and probably the bottom connection of LDR1 (as shown in the diagram) should be labeled +5v if the Arduino is a Uno etc.

I wasn't used to the design software


text:
Contoller for a stepper motor
I am currently implementing the following setup:
Arduino Mega 2650 -- DRV8834 -- Stepper motor
Everything works fine, however since it can provide a higher torque I want to run the stepper in half step mode. Each step is triggered by a single pulse coming from the Arduino to the driver. If one uses the Digital Pins for this purpose as done by AccelStepper, the maximum frequency is around 1000 pps (points per second). This is a third of what I want to achieve. The second option would be to use the PWM of the Arduino which naturally runs at 16 MHz (way to high). There is a way to downgrade this frequency, however the steps are only discrete and not accurate enough for a nice speed control.
Therefore I want to do the following
Arduino Mega 2650 -- Controller -- DRV8834 -- Stepper motor
whereby the Controller is creating a PWM with a frequency (100 to 3000 Hz) depending on some signal coming from the Arduino (I2C, voltage level or something else). I was now searching two days for a component and have no clue what I could use.
How can I create a PWM from 100 to 3000Hz with an arduino?

Edit 1: I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM
void loop(){
digitalWrite(pinSTEP, HIGH);
delayMicroseconds(T/2);
digitalWrite(pinSTEP, LOW);
delayMicroseconds(T/2);
}

where T = 1 / f is not feasible since I have to read out a sensor in the loop which destroys the motor timing.

Edit 2: There is a method to change the register of the timers. One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM. However with only seven discrete steps this leads to the following freuquencies:
prescalar = 1 ---> PWM frequency is 31000 Hz
prescalar = 2 ---> PWM frequency is 4000 Hz
prescalar = 3 ---> PWM frequency is 490 Hz (default value)
prescalar = 4 ---> PWM frequency is 120 Hz
prescalar = 5 ---> PWM frequency is 30 Hz
prescalar = 6 ---> PWM frequency is <20 Hz

which is not sufficient for my application.
For more about this method:

http://usethearduino.blogspot.ch/2008/11/changing-pwm-frequency-on-arduino.html
http://forum.arduino.cc/index.php?topic=72092.0

Sometimes a solution is so easy that it hurts ;) Based on the input of this wonderful community I found my solution. Code:
#include <TimerThree.h>
// TimerThree PWM Pins 2, 3, 5

#define pinPWM       2
#define pinM0        22
#define pinM1        24
#define pinSleepnot  28
#define pinDir       30

void setup(void){

  // Define output pins
  pinMode(pinM0, OUTPUT);
  digitalWrite(pinM0, HIGH);
  pinMode(pinM1, OUTPUT);
  digitalWrite(pinM1, LOW);
  pinMode(pinSleepnot, OUTPUT);
  digitalWrite(pinSleepnot, HIGH);
  pinMode(pinDir, OUTPUT);

  // Initialize serial communication
  Serial.begin(9600);

}

void loop(void){

  for (float frequency = 500; frequency < 3000; frequency = frequency + 1) {
    float T = 1 / frequency * 1000000;
    Serial.print("Frequency: ");
    Serial.println(frequency);
    Timer3.initialize(T);
    Timer3.pwm(pinPWM, 100);
    delay(5);
  }
}

The premise of your question is based on misunderstanding, you can toggle digital pins a lot faster than 1 KHz.

@AngeloQ: which voltage to frequency converter would you have in mind? I had a look at the other comments and i think it is not working with that. (see my edits in the post)

How can I create a PWM from 100 to 3000Hz with an arduino?

Your question is really "How can I create a PWM from 100 to 3000Hz with an Atmega2560"?
The Atmega has various timers which can be configured in many ways. You can alter the prescaler (ratio of processor clocks to timer ticks) and the amount it counts up to. Certainly you can change the frequency and duty cycle.
I have a page about timers which may help you.

I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM ... is not feasible

Yes, don't do "bit banging" when you have 5 hardware timers.

One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM.

Adapt the prescaler and the timer configuration. Between them you have very fine control.

Thank you very much sir! Sometimes a solution is so easy that it hurts if you find it ;)

the maximum frequency is around 1000 pps

Arduino pin operations takes about 100 ticks. Or 400 ticks for four pins. No more than another 100 ticks for processing and logic ops. So I would expect 500 ticks or 30k on a 16mhz Arduino.
Much faster if you use direct pin ops.
So maybe the code you used isn't well written or your Arduino is doing lots of other things?
edit:

I found my solution. Code:

there is no reason for you to repeatedly initialize the module. this thing is simple, and others have laid out the thought process for you. write a set of routines that spin the motor - spin it left, spin it right. and then call those routines in a timer isr. nothing fancy here.

Please see my edits in the post. I think this method is not working for me. Do you have anything else in mind?


text:
Driving conveyor belts using Arduino Unos
We are planning to drive conveyor belts with Arduino Unos using stepper motors. We are planning to use easy drivers, so that we control at least 3 motors with one Uno. Currently we are still at an initial stage, we are designing and planning the setup of conveyor belts. But what I wanted to ask was, regarding the coding.
How would I code so that say the belt moves forward for x seconds, and then after time it moves backwards for y seconds. Any basic idea on the code would be great thank you. I could do the basic code, but I just need help with timers part.

Steppers may not really be the best motor technology for that, but they are conceptually simple.  Time based control is extremely simple, but often poorly suited to the real world. However, if you wanted to do it, and are using stepper motors, a possible way would be to figure out your steps per unit time, and issue that many steps.  In reality, stepper systems with mass will need acceleration and deceleration, so you'd have to work that in too - maybe instead of time, you could work in terms of a desired total number of steps.  Don't forget operator safety!

The clocks of the Unos have only ~ 0.5% accuracy. This may be an issue if you need several of them working in unison.

In regards to time control use the mills() function.  You start by creating an:
unsigned long lastTime = millis();

Then later in the program create another variable:
unsigned long currentTime = millis();

Next Compare the two:
unsigned long elapsedTime = currentTime - lastTime;

For the most part I normally just shorten the last two lines into one:
unsigned long elapsedTime = millis() - lastTime;

Stepper motors are not needed if you are just doing timed control, but the advantage of stepper motors are you can move them with pin point accuracy based on the number of steps per rotation.  If there are 60 steps per rotation then 360 degrees per rotation/ 60 steps per rotation and you get that each step is 6 degrees.  So in order to turn the motor 6 degrees you would turn it 6 steps.  This also allows you to keep track of angular velocity.
When I control motors I normally create an array of the different parts of the cycle then loop through the array.

yeah we are going for stepper motors because in some cases we need the conveyor to oscillate back and forth, so we would need to play with time ofcourse and also accuracy of steps also, that it needs to oscillate x steps forward for y seconds then reverse x' steps backwords for y' seconds. So I think stepper motors would be a good choice here. We will not be using an external sensor to detech the change motor speed or steps. It will all be done in coding only. Also with stepper motors we can utilize full 360 degree angle, which would be required, unlike servo motors which only go upto 180.

Did my answer answer your question? If so please mark it as the answer.  If not, how can I improve it to help you best?

@Joel..yes I was replying to you. we are still in process of developing the basic automation idea. The electronics part of driving motors etc comes later on. So I will surely refer to you..once we start electronics part. I hope you read my comment, you reckon stepper motors would be a good choice??? Thanks

Steppers motors will work well with a conveyor.  In order to get accurate position data you will need to convert steps to distance moved which is centered around your gearing.  Make sure to check there torque specs, depending on the conveyor size you will need larger stepper motors which require larger hardware to control them.

@joel...yeah ok, let us see how it goes, I will contact you once the prototype is ready. I reckon I posted a bit early, but anyways stepper motors then it shall be...mind you for prototyping we will be using arduinos unos just to check the feasibility and the results..for the original setup we will probably use PLC..


text:
Right PIN to activate a wireless relay with ESP8266 ESP-01
I'm trying to program an ESP8266 ESP-01 module to let it connect to my personal wifi network and activate a wireless relay that I've bought.
No problems with Wifi connection so I've omitted the code about it, my problem is to find what is the right PIN to set to LOW/HIGH to control my relay.
Setting relayPin to 1 as shown in this code works and with it I can see the embedded LED turning on and off.
const int relayPin = 1;

void setup() {
    pinMode(relayPin, OUTPUT);
}

void loop() {
    Serial.println("Close Relay for 100 ms and then Open");
    digitalWrite(relayPin, LOW);
    delay(100);
    digitalWrite(relayPin, HIGH);
    delay(200);
}

Surfing the web I've found the following diagram about the ESP8266 ESP-01 module:

I've tried to set relayPin to 0 or to 2 but the relay doesn't activate/deactivate.
So, what is the right PIN number to set in my relayPin constant to control the GPIO0 port?
The relay works succesfully if I give him +3.3V on GPIO0 with an external power.
Thanks in advance

why don't you just write test code that tries all the pins in sequence?

@jsotola tried with https://pastebin.com/pNsZY1ZX but nothing happens :(

check the traces on the relay PCB

@Juraj how can I do that?

I'm in the same boat as Roberto and wondering if this issue was resolved and what was the solution. Also interested in the firmware that was used in the ESP.

most GPIO pins on the ESP8266 "boot" up in INPUT mode
You'll need to
const int relayPin = 0; // or 2

void setup()
{
    pinMode(relayPin, OUTPUT);
}

The reason GPIO1 works is because GPIO1 is serial TxD - so, it's set to output

Thanks for your comment! It was already written in my code but I've forgotten to write it, now I've edited the 1st post ;) Thanks

Looking at better pictures of the PCB on ALIExpress it looks like GPIO0 is used to switch the relay.
What that pin maps to, though, depends on what board you have selected in the IDE.

Thanks for your answer Majenko! In Arduino IDE I've set "Generic ESP8266 Module", but where can I find the PIN mapping? :)

"PIN mapping"? GPIO0 is pin 0 ... GPIO1 is pin 1 ... up to GPIO16 is pin 16 ... it's not hard :p

@JaromandaX In this case it looks like yes, it's a 1:1 mapping between the GPIO number and the Arduino pin number (which is default). However, since digitalWrite() is a weak alias to __digitalWrite() it's perfectly possible that a board definition overrides that function with its own to implement a different numbering scheme.

Pin 1 is gpio 1 always on every 8266. Some boards may have d0 d1 etc.  But that is completely irrelevant to an esp01

Ok thanks, I've tried to set relayPin to 0 but nothing happens on the relay :( I've also tried with this sketch but nothing happens: https://pastebin.com/pNsZY1ZX What is missing?

I had this exact same problem. Solution was to put 5 volts on the relay.
There is a regulator on the wireless relay that gives 3v to the ESP-01 and not 5v. But 5v is required for the relay to work.

1 solution I did is to use rx [GPIO 3] to drive relay. For this,

Need to short the GPIO 0 and GPIO 3(Rx) pin on the relay board.
While inserting the ESP-01, either bend the GPIO 0 or completely remove it from ESP-01 board. Be careful, on removing you wil find difficult to program the ESP-01 module again because GPIO 0 should go low at boot time to enable program mode. And this is the reason why GPIO 0 is HIGH on boot.

If you want, you can try this product
Smart Switch. Android Based ESP01 Relay Module

You can use any pin of the esp-01
You may want to tell the TX and Rx pins though to behave like regular I/O with the pinMode/Function_3 command as described here:
https://arduinodiy.wordpress.com/2018/06/14/simple-wifi-relay-board-or-diy-sonoff-sv-sonoff-4-channel-2/

the question is about a pcb with relay already wired to a pin


text:
Bluetooth a pushbutton from one arduino to another to turn on a LED
For a major project at school i need to get a bluetooth module to be able to communicate between two  HC-05 modules as a master and slave. They need to be able to press a pushbutton on the slave and it lights up a LED on the master.
I have been able to get the two hc-05's to connect to each other but i cant find a code and wiring that will work for what i need to do.
any help will be appreciated. Thanks

When you already have two arduinos and two hc-05 connected to each other, what wireup and code is missing?

The HC-05s are serial bluetooth modules. If you have connected the two HC-05 you already have send them AT commands via your serial interface. What is your problem with sending the needed information over the serial interface?

please post the code that you have so far .... we can then give you some hints  .... please do not expect any ready made solutions, since this is a school assignment

Do not post code as pictures. There is a function in the question editor to properly format code you inserted as text. Please use it

So, you have done the hard part and now need the easy bit :)
Firstly you need a button (failing that touching two wire together will just about do).  There are loads of quick tutorials on the web, here is one https://www.arduino.cc/en/Tutorial/Button.  They will end up with you having a pin that goes high or low when the button is pressed, you can either poll/loop to detect the press or go posh and use interrupts (leave that for later).  When the pin detects the press you need to send some data via your HC05 link to the master, something like 'ON' or 1, who cares so long as the master understands it.  And when it disconnects you need to send a off or 0 message (Remember the number 1 and the character '1' are not the same thing, so make sure you know what you are sending).
When the master receives the command it will execute a bit of code that will send a pin high (lets say pin 7).  Connected to pin 7 will be the +ve side of a LED, the -ve leg of the led will be connected to a resistor of 200-250 ohms and the other end of the resistor will be connected to ground.  Then when pin7 goes high it will light the resistor.

simulate this circuit – Schematic created using CircuitLab
As always you probably will need to break it down to test it, have a little app that toggles pin 7 high for 2 seconds and low for two seconds, etc (just like blink).
There is a phenomenon called 'bouncing' which is where the useless human finger presses a switch and doesn't instantly create a perfect connection and perfect disconnection.  This might make the slave send 101010101010101 when you just expect 1, you can either debounce using software or hardware, but only worry about that if you have a good quality switch :)


text:
Sending a character 'A' through blinking led

How do i code to send a character 'A' to the arduino through a blinking led?
   i am doing a project about data transmission. i really need help&some guide.
   Material used are arduino uno r3,white led and a resistor.

MY OUPUT IN SERIAL MONITOR
Insert letter:
01000001 65  - Character A
00001010 10  - when i send/enter
CODE
 int LEDTrans = 13;
int timeWaitOn = 1000; //milisec (1 sec)
int timeWaitOff = 1000; // milisec (1 sec)
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);

 Serial.print("Insert letter:");
 Serial.println(" ");
}

void loop() {

digitalWrite(LEDTrans,HIGH); //turn the led on
delay(timeWaitOn); //delay in millisec (1 sec)
digitalWrite(LEDTrans,LOW); //turn the led off
delay(timeWaitOff); //wait a sec

   /*  check if data has been sent from the computer: */
  if (Serial.available()) {

     byteRead = Serial.read();
    // will print the binary representation of 'byteRead' as 8 characters of '1's and '0's, MSB first.
for ( uint8_t bitMask = 128; bitMask != 0; bitMask = bitMask >> 1 ) {

      if ( byteRead & bitMask ) {

    Serial.write('1');
  } else {
    Serial.write('0');
  }
}

Serial.write("    ");
Serial.println(byteRead);    //send back the actual ASCII code
}

}

you forgot to ask a question

There is no code intended to send something over a LED. Try googling something like Arduino light data transmission and similar terms. There are libraries for that

Possible duplicate of transmit a sequence of bit using arduino uno

Huh, I'm confused. You asked this exact  question here https://arduino.stackexchange.com/questions/52352/transmit-a-sequence-of-bit-using-arduino-uno/52363#52363 and the given answer is also the exact functional equivalent, except that the data is coming from the serial monitor..

i'm learning a lot from this website. im a beginner and i want to learn a lot of things. your explanation and help was really helpful :) im really grateful for that. thank you so much.

I want you to state, very clearly, what you want the code to do. For example: When I send "A" I expect a pause of 1 second with the LED off, then the LED to be on for 1 second, then the LED to be off for 5 seconds, then on for one second, and then off for one second (giving a total of 8 seconds to send the letter "A"). If that is not what you want please state what you do want.

Now get it. I saw the LED on and off as you describe above. Therefore it takes only 8 seconds to send letter 'A'. Thank youu veryyy much

Instead of printing '0' or '1' set the LED pin off or on, like this:
const int LEDTrans = 13;
const int timeWaitOn = 1000;  // millisec (1 sec)
const int timeWaitOff = 1000; // millisec (1 sec)

void setup() {
  // Turn the Serial Protocol ON
  Serial.begin(115200);
  Serial.println("Send letter:");
  pinMode (LEDTrans, OUTPUT);
}

void loop() {
  /*  check if data has been sent from the computer: */
  if (Serial.available()) {
    byte byteRead = Serial.read();
    // will print the binary representation of 'byteRead' as 8 characters of '1's and '0's, MSB first.
    for ( uint8_t bitMask = 128; bitMask != 0; bitMask >>= 1 ) {
      if ( byteRead & bitMask ) {
        digitalWrite(LEDTrans, HIGH); //turn the led on
        delay(timeWaitOn); //delay in millisec (1 sec)
        digitalWrite(LEDTrans, LOW); //turn the led off
      } else {
        delay(timeWaitOff); //wait a sec
      } // end of if
    } // end of for loop
  } // end of if something available
} // end of loop

how do i count the flashes? is it based on the binary 01000001?

Here's the problem ... according to what your question seems to ask for, you are wanting an LED to flash for a 1 and be off for a zero. So the results (which my code provides) would look like this:

So, you get two flashes, the first one second after it starts, then there is a gap of 5 seconds, and then another flash. That would be 01000001.
However, how do you know when to start counting flashes? It might be:

That would be 00000001.
Or even:

That would be 10000010.
You can see, can't you, that you can't make any meaningful deduction at the receiving end about what the character is?

So what asynchronous serial (normal serial on an Arduino) does is have a Start Bit which signals when to start counting, like this:

Normally the serial port is high (continuous 1s) and then when a 0 arrives that means "start counting". So, you wait 1½ bits of time and then sample at the known baud rate. In your example, where you want 1 second per bit, the baud rate would be 1 (one bit per second). Thus, you sample every one second. Normally baud rates are somewhat faster than that, like 9600 or 115200 samples per second.
Also there is a Stop Bit which is always a 1. This guarantees that there will be at least a single 1 at the end of each byte, so that we can tell when the next start bit arrives.

There are other ways of doing this, for example a short pulse might represent a zero, and a longer pulse represent a one. In that case, any pulse at all could represent the start of a byte, and then you just measure how many short pulses, and how many long pulses, you get (for some definition of "short" and "long").

thank you soo much the blinking happened. but i am a bit confused. I count the on and off for the led to see the character of 'A' in binary that is 01000001. but it didn't happened.

Really? I changed the baud rate to 115200, I hope you noticed. If I send "A" then I get the LED flashing after 1 second and after 7 seconds, which is right: 01000001. You expect two flashes, one a second in, and one seven seconds in. The rest of the time the LED is off (that is a zero).

Oh. I noticed that,but i tried to change to 9600.Maybe that's why. Do i really must use the baud rate 115200 to achieve 01000001 ?What type of library should I import in this coding?Where can i get the library?This arduino acts as a transmitter to send the character 'A' and the receiver is an application. Do you have any suggestion how can i synchronize both of them?Can i have your email. i have a lot to ask.

The baud rate is only for you to send a character to the sketch from the serial monitor. The rate at which the LED blinks is set in your code, currently one bit per second. There is no library you need. Why do you think you want one? If you have more questions please post them here.

I thought I need one. I went through other projects they import libraries. But I currently don't understand what you mean by >>    flashing after 1 second and after 7 seconds, which is right: 01000001. You expect two flashes, one a second in, and one seven seconds in. The rest of the time the LED is off (that is a zero).

I'm curious to know what you are expecting to happen. Please state how often you expect the LED to blink and at what intervals. Surely 01000001 represents two blinks? (There are two "1"s there). What else could it represent?

I am sorry that I made you confused. How do i count the flashing of the led that you mention before?for 1 how many flash&seconds that it represents?and for 0 how many seconds does the led went off? i want to transmit the 'A' in binary for 10 seconds. If the led is on,does it represent 1?i am a bit confused there.When the led is off it represents 0?

how do i count the flashes? is it based on the binary 01000001?how do i count the flashes? is it based on the binary 01000001?the pins that i connect the jumper to the led should be pin 13 and tx is it right?i want to transmit 'A'.

Nick, I tried to count the blinking of the LED on the arduino board. it shows flashing after 1 seconds and after 7 seconds. but when i attached a white LED using the jumpers,the flahsing is different. i count the flashing, when the LED starts to went off as 0, then it when on as 1. the white led blinks 0 1 0 1 0(5 to 6 sec) 1 0 1.  Or i should count on the second blinking that shows 010000010 ?

the pins that i connect the jumper to the led should be pin 13 and tx is it right - No, pin 13 and Ground, with a current-limiting resistor between the LED and ground, for example 330 ohms.

how do i count the flashes? - what do you mean by that? When you see a flash you count it? You also make a note of the time between the flashes. I am completely unclear, after reading these questions, about what you are expecting the code to do, and if you can't state that then neither I, nor anyone else (including you) can make it do that thing, whatever it is.

Now i understand. I am expecting the arduino to be a transmitter that transmits character 'A' through pin 13 on the arduino.  You helped me a lot Nick. Thank you very very much.


text:
Controlling HDMI Switch via RS232/UART
Problem:
I have an HDMI switch that is controllable via RS232

Scenario 1:

Setup: PC connected to HDMI switch using USB -> serial adapter
Test: Opening PuTTY on COM port and sending command "sw i01" from my PC
Results: HDMI switch input changes to port 1 [Good]

Scenario 2:

Setup: Arduino UART port connected to TTL->RS232 adapter connected to serial->USB adapter connected to PC with PuTTY program open on COM port
Test: Sending command "sw i01" from Arduino to PC using code below
Results: "sw i01" prints repeatedly on the Putty terminal [Good]

Scenario 3:

Setup: Arduino UART port connected to TTL->RS232 adapter connected to HDMI switch serial port
Test: Sending "sw i01" from Arduino repeatedly to HDMI switch using code below
Results: HDMI port does not switch from port2 to port1 [Bad]

Hardware:

Intel Galileo Gen 2
SparkFunRS232/TTL Shifter connected to Galileo UART
HDMI switch is IOGear GHSW8141

Code:
[Note: Galileo Gen 2 requires Serial1 for UART communication]
void setup() {
    Serial1.begin(19200);
}

void loop() {
    Serial1.print("sw i01");
    Serial1.write(13);    // CR
    Serial1.write(10);    // LF
    delay(1000);
}

Question:
It seems like Scenario 1 and 2 confirm that the Arduino->HDMI switch communication should work, but it doesn't. Am I missing something regarding physical connectivity? Does manually typing "sw i01" in PuTTY send different commands than I have in the Arduino code?

How have you connected this?

I can't tell how you have it physically connected. So I can't tell if it's wrong.
It should work indeed. But you'll need the exact right settings and probably an (correct me if I'm wrong) uart<->RS232 converter.

@MikaelPatel I edited the description above to include how I connected everything for each scenario. Let me know if I need to be more clear on anything. Thanks!

@Paul I edited the description above to include how I connected everything for each scenario. Let me know if I need to be more clear on anything. Thanks!

You might want to check if inverting the Rx and Tx lines does something. But judging from the tests you've done, it shouldn't make a difference. Worst case, you could try an ossiloscope and compare the actual raw electrical output of the working and non-working examples. Are you sure you need an CR + LF? Maybe your putty settings only send an LF (and does work for that reason)

I found it is was related to the physical connection!
In Scenario 3, I originally had the Sparkfun TTL/RS232 adapter that had a female DB9 connector wired to the HDMI switch female DB9 connector using a male/male serial cable. The serial cable I bought was a straight through cable.
I swapped it out with a null modem cable and it worked right away.
Looking at the wiring diagram, I thought swapping the Tx/Rx pins on the Sparkfun adapter would have achieved the same result as the null modem cable, but apparently not.
If anybody can point out why the null modem cable made the difference, that would be something good to know for the future.

Your HDMI switcher, and your USB to RS-232 converter speak RS-232.  The Arduino speaks TTL UART.
While the concept behind them, and the overall format of the data, is the same there are major differences:

RS-232 uses a ±10V NRZ signalling method, TTL UART uses a 0-5V signalling method
RS-232 uses inverse logic compared to TTL UART

That means that you need to convert the Arduino's TTL UART to ±10V NRZ with inverse logic in order to communicate with the IOGear.
Fortunately that's a simple enough task using a special interface chip. These are readily available and can be bought for tiny amounts as a breakout board or even a full shield if you like (such as this one from Sparkfun).  The chip is known as a MAX232 in its most common form, though other manufacturers may use different letters.
If you pop on eBay (or your favourite budget seller site) and search for "Arduino MAX232 DB9" (the DB9 is the type of plug on the board - the 9-pin D connector) you will get lots of hits to choose from.

Majenko, did you read the “SparkFun RS232/TTL Shifter connected to Galileo UART” part of the question?

Nope. Missed that.

@jwpat7 and Majenko, I edited the description above to include how I connected everything for each scenario. Let me know if I need to be more clear on anything. Thanks!


text:
How to combine Leonardo with Ultrasonic sensor?
I am working on an Arduino project that replaces the computer mouse. I want to do this in combination with an ultrasonic sensor. I found some nice examples on youtube, but they didn't post the code. And an example on this website. But I don't get it completely. I don't have much Arduino skills, but do have some. How can you attach for example echoPinScroll to a board?
I hope someone can give me advice on how to use this ultrasonic to control my mouse!
#include <Mouse.h>

int echoPinCursor=2;
int trigPinCursor=3;

int echoPinBtn=4;
int trigPinBtn=5;
int echoPinScroll=6;
int trigPinScroll=7;
int x;
int y;
long duracionCursor, distanciaCursor;
void setup() {
 Serial.begin(9600);
 pinMode(trigPinCursor, OUTPUT);
 pinMode(echoPinCursor, INPUT);
 pinMode(trigPinBtn, OUTPUT);
 pinMode(echoPinBtn, INPUT);
 pinMode(trigPinScroll, OUTPUT);
 pinMode(echoPinScroll, INPUT);

}

void loop() {

//mover el cursor
int direccionx=moverx();
int direcciony=movery();

Mouse.move(direccionx, direcciony,0);
delay(2);

}

int moverx(){
distanciaCursor=obtener_distanciaCursor();
if (distanciaCursor >= 1  || distanciaCursor <= 11){
   x--;
 }
if (distanciaCursor >= 12 || distanciaCursor <= 24){
   x++;
  }
 return x;
}

int movery(){
distanciaCursor=obtener_distanciaCursor();
if (distanciaCursor >= 25 || distanciaCursor <= 37){
   y--;
   }
if (distanciaCursor >= 38 || distanciaCursor <= 50){
   y++;
  }
return y;
}

long obtener_distanciaCursor(void)
{
digitalWrite(trigPinCursor, LOW);
delayMicroseconds(2);

digitalWrite(trigPinCursor, HIGH);
delayMicroseconds(10);

digitalWrite(trigPinCursor, LOW);
duracionCursor = pulseIn(echoPinCursor, HIGH);

distanciaCursor = duracionCursor/58.2;
return(distanciaCursor);

}

Was this the example, as it is the only link with echoPinScroll that I can find: I want to move the mouse pointer with an Arduino and ultrasonic sensor

What is your hardware setup?
From your code, it looks like you're not using the pins trigPinBtn, echoPinBtn, trigPinScroll, echoPinScroll. Weird. I can't figure out:

which ultrasound module you're using
what do you expect, eg which movement(s) in front of which ultrasound sensor shall generate which mouse action(s)

I would recommand having an iterative approach:

Play with your ultrasound sensor(s), eg understand properly how to wire them to the arduino, how to interface them (software/lib), what kind of values you can get from them, etc... This will depend on the HW module you have chosen (if any yet).
Read the documentation that comes with the mouse lib of the Leonardo and play with it independently/with existing, working examples.

That is divide and conquer: understand each bit before trying to assemble them.
THEN, and only then, you will have a better understanding of the different part of your project. You will then be able to formulate an overview of your project goals, and how you can do it. That is, start documenting your project before it is done: doing so will force help you to have a clear idea of what it is that you're trying to achieve... and thus how to achieve it.
But yeah, the overall project might look something like this:
// Ultrasound distance sensor #1, hooked to the arduino with xxx and yyy; generates movement along the x axis
// Ultrasound distance sensor #2, hooked to the arduino with zzz and ttt ; generates movement along the y axis
// Something for the wheel? The buttons?

//global values & objects
setup()
//initialize hardware& libs

loop()
//get raw ultrasound distances
//translate these into x and y movements
//do something about buttons & wheel?
//update mouse values


text:
Is programming the ATTiny85 possible in 1.5?
I upgraded to Arduino 1.5.7 in hopes of using the command line interface for a larger project. However, the old package I was using to program the ATTiny85 chip with the Sparkfun Tiny AVR Programmer no longer works. I'm getting the following error:
Third-party platform.txt does not define compiler.path. Please report this to the third-party hardware maintainer.
processing.app.debug.RunnerException
    at processing.app.debug.Compiler.getCommandCompilerCPP(Compiler.java:597)
    at processing.app.debug.Compiler.compileFiles(Compiler.java:275)
    at processing.app.debug.Compiler.compileSketch(Compiler.java:642)
    at processing.app.debug.Compiler.compile(Compiler.java:125)
    at processing.app.Sketch.build(Sketch.java:1589)
    at processing.app.Sketch.exportApplet(Sketch.java:1611)
    at processing.app.Sketch.exportApplet(Sketch.java:1597)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2397)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at processing.app.helpers.StringReplacer.replaceFromMapping(StringReplacer.java:97)
    at processing.app.helpers.StringReplacer.replaceFromMapping(StringReplacer.java:89)
    at processing.app.helpers.StringReplacer.formatAndSplit(StringReplacer.java:37)
    at processing.app.debug.Compiler.getCommandCompilerCPP(Compiler.java:595)
    ... 8 more

Does a package exist that will allow me to program the chip in 1.5.7?

You can download a version of arduino-tiny for IDE 1.5.x from here.

Where do I extract it? It contains tiny/avr/.... Do I extract /tiny to /hardware/... or do I extract the avr subfolder?

Never mind, this doesn't work in 1.6.


text:
I need 70 or more input pins for the Arduino -how to do this?
I have some SN74HC165N, CD4021B chips. How many (minimally) such ICs would I need to get 70 inputs to an Arduino Uno? What is the exact circuit diagram and the code? Im not sure how the wring cascades into each of the chips to make it grow to over 70 inputs, or what the code is for the 70 input circuit. I do understand how to use one of those ICs though. My second easier question is -is there an development board with 70 or more inputs?
CD4021B,SN74HC165N are the chips, you know the ones, that has a parallel input pins that are listened to by latch pin, and the clock pins such outputs the parallel data into the serial data-so I am interested with solution with this pin because I know how it works.
It is for sure 70 pins that are required -not any less-I am sure of that. Because the inputs cannot be further simplified to less than 70. The reason the inputs are 70 is because the algorithm used has 70 free variables in it. Hence by definition it uses 70 or more variables. The input for each of the 70 inputs can be a digital high or a digital low but this is not known before hand. So it cant be simplified because it like saying you can simplfy the information from 70 or more sensors at runtime, and each sensor has an unpredictable value. Anyway this explanation is moving away from the point of my question. I just want to know the circuit that does 70 inputs or more using the mentioned IC-I can live with that answer even if its not the most efficient.

"is there an development board with 70 or more inputs?" Possibly. The ATmegaXX0 has enough GPIOs, but the Mega doesn't expose all of them.

Are your inputs digital-logic-level signals, or switch contacts, or what?  It makes a difference, eg matrix techniques and multiplexers are relevant in some cases but not others.  What response times are needed?  Polling, or interrupts?  Is this a one-off project, or will you make multiple copies?  (Please edit question and add that info)

Two of these could do the trick; http://anarduino.com/gpio-expander/

The best way I know to do it is by using the MCP23017, which gives you 16 extra GPIOs via I²C communication. They can be configured for both input and/or output. I've done it myself and it worked like a charm. It has 3 pins for dynamic addressing (3 bits), which allows you to use up to 8 (0..7) MCP23017 for a total of 128 extra GPIOs.
This is the chip datasheet:
(http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf)
There's a lot of examples about its use on the internet. Just google for "MCP23017 arduino" and you'll find them. For example:
http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/

Personally I prefer the MCP23S17 - the SPI version. Faster communication, and as many groups of 128 GPIOs as you have spare IO pins for CS.

That's another good option. At the time I chose the I²C version because I was working with the ESP8266 (ESP-12) and I didn't have the driver for SPI comm, only for I²C. For Arduino you can easily use the SPI version indeed.

Just with that number of chips you want to watch your pin capacitance - you may want to boost the signal strength with some IO drivers.

@Vinicius I'm thinking about your answer which I never considered before. Can I get the MCP23S17 to work with Arduino Uno I2C bus? Using I2C bus do I use wire library to set up what input and out port? and to write values? to get it to work

There are libraries available to do all the work for you. Google for them.

You probably mean MCP23017?

I have some 74HC595 chips. How many (minimally) 74HC595 would I need to get 70 inputs to an Arduino Uno?

None. Those chips are for output, not input.

I do understand how to use one 74HC595 though.

Evidently not, since you don't even know what they do.

My second easier question is -is there an development board with 70 or more inputs?

Yes, there are. None made by Arduino though, but there are plenty of other options. Myself I work with microcontrollers with hundreds of IO pins.
However, I think you need to re-think what you are trying to achieve. There are many options for reducing the number of inputs you need to use depending on what it is you are doing. Maybe if you told us a little more about what you want to do, not how you think you want to do it, we can help you a little more.

It sounds like youve got "fire in your belly" about the 74HC595 typo

@Rosemary he means no harm ;) It may be interpreted as so, but at the point of writing he didn't know it was a typo. He was pointing out it was unlikely that one knows how to use output IC's for input signals, nothing personal I believe.

Agreed, it's not personal. I'm snarky to all people equally ;)


text:
transmit a sequence of bit using arduino uno
How do i code to transmit a sequence of bit using arduino uno?My project is about a transmitter and a receiver.Arduino as the transmitter and an application as the receiver.Light sensor will detect the bits sent.How do i send a sequence of bit for example 00101010.What kind of function should i use? i am a beginner for arduino. thank you.

Transmit how? Using morse-code with the led?

Optical transmission is quite a broad field. What are your requirements regarding speed, error-correction? How do you want to receive and decode the data? You might be better of using an IR library or a different medium (WiFi, Bluetooth, ..)

transmit using morse-code but transmit binary. That will sent 1's and 0's that is 8 bit. the arduino uno act as a transmitter and an application will be receiver and accept the sequence of bit.

transmit using morse-code but transmit binary say again. If you have "A" would you like this transmitted as "short-long" or "01000001" (ASCII value).

Serial.print("hello"); is transmit binary (ASCII). So your sketch is already doing that.

woahh i just knew a lot of this. i just want to send a simple binary value. a sequence of 8 bit character continuously. which library or example should i refer to learn and code. thank you so much.

what i mean was. i want to send a binary transmitter. a simple one. not using morse-code

people usually use manchester coding. but my receiver is a light sensor from android

send it where? At what rate?

38400rate. send it through an led

read the Serial TX LED or create SoftwareSerial with TX on pin 13

you are already sending a sequence of bits through an LED. 1 second ON followed by 1 second OFF, repeating indefinitely .... please update your question with what you really want to ask

Also asked here: https://arduino.stackexchange.com/questions/52837/sending-a-character-a-through-blinking-led

Bit-wise sending of a chunk of data is really just:

go through each byte of the data
for each byte (= 8-bits), put each bit on the LED and wait

This also has some substantial drawbacks:

no error detection or correction. If you get interference on your light sensor / camera due to the environment, you will read wrong data. For this you would need to code the data with some coding scheme or append a checksum
outputting on the built-in LED on the Arduino Uno / Nano is a bad idea sine it's directly next to the power, RX and TX LED
outputting in the visible spectrum is asking for interference. That's why we have InfraRed transmissions.
receiver and transmitter might out of sync; that means that the receiver does not sample the output of the transmitter at the correct time -- you should use a preamble, oversampling and averaging at the receiver to overcome this

That said, you might be better off using other proven methods such as IR, 2.4GHz transceivers, et cetera, from my point of view. Other microcontrollers (example) have even built-in peripherals to do IR transmission according to some protocol.
On the Arduino Uno/Nano you could also use the IRemote library to send and receive data using a cheap IR LED and a IR receiver, many of which are included in starter kits (and are also otherwise cheap).
The code below simply takes a stream of bytes and outputs them bit-wise on the LED. Nothing else done. Also, digitalWrite is slow and should be replaced by a faster variant.
#include <Arduino.h>

/* LED to output from */
const int LEDTrans = 13;
/* Length of a symbol */
const int timeWait = 500;

const char dataToSend[] = "Hello World";

/* Transmits data bitwise */
void transmitData(const char* data, size_t length) {
    //go through each byte of the data
    for(size_t i = 0; i < length; i++) {
        uint8_t currentByte = (uint8_t) data[i];

        //Go through each of the 8 bits in the byte
        //Goes from LSB to MSB (right-to-left)
        for(int j = 0; j < 8; j++) {
            //uses Arduino.h macro "bitRead"
            bool currentBit = bitRead(currentByte, j);

            //Set the LED on/off
            digitalWrite(LEDTrans, currentBit);
            //Wait for the symbol time
            delay(timeWait);
        }
    }
}

void setup() {
    pinMode(LEDTrans, OUTPUT);
}

void loop() {
    transmitData(dataToSend, strlen(dataToSend));
    //turn LED OFF again
    digitalWrite(LEDTrans, 0);
    delay(2000);
}

transmit using morse-code but transmit binary say again. If you have "A" would you like this transmitted as "short-long" or "01000001" (ASCII value)..... i'm sorry i didn't notice your question Maximilian. i want to transmit in the form of 01000001.

can i have your email?i need to ask a lot..


text:
Binary addressing and coding to control a 96 input mux matrix
I’m trying to wrap my head around using binary addresses in a mux. Failing miserably.
For the circuit I have six 16 channel analog multiplexers CD74HC4067 as slaves to an eight channel multiplexor CD54HC4051 master.
They are bringing in 96 sensor readings (IR receiver diodes through Op Amps) into an array
that, in turn,  is used to constantly update lotsa LEDs through a series of shift registers (TLC5940) using the Arduino TLC5940 Library.
I’ve included the possible wiring scheme that the code is trying to control.
It probably needs work too.
Question: I’ve seen, and SEMI-understand matrixes that address 32 inputs
(4 x 8 bits) but not quite understanding how I can address the six mux chips
with 96 inputs. Or if I can even do it this way. Example from this forum: How to code for cascading multiplexers?
Is it possible with this matrix of 96 inputs, and how? Am I barking up the wrong tree?
Code so far:
    #include <Tlc5940.h> //Arduino TLC5940 Library controls the individual LEDs - "Pixels"

int ledCount = 96; //change  LED "PIXEL" count in matrix...also number of IR sensor inputs

int thresh = 10; //value for usable distance reading from IR

// main structures to hold LED Pixel array on/off state, IR reciever readings
byte dsply_state[ledCount];    //pixel on-off grid, need for tlc5940
uint_16  recv_state[ledCount];           // IR Readings - FROM mux set-up

// Master IR -mux sensor pins for Arduino Pro MINI
#define  M_S0 2
#define  M_S1 4
#define  M_S2 5
// Slave IR mux sensor pins
#define  S_S0 6
#define  S_S1 7
#define  S_S2 8
#define  S_S3 12

//  ANALOG PIN :
#define  InputFromMux A0

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

    //tlc5940 Arduino library
    Tlc.init(0);

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

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(S_S3, OUTPUT);
    pinMode(InputFromMux, INPUT);

}

void loop() {
    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER and SLAVES.

  for (int i = 0; i < ledCount; i++) {

    digitalWrite(M_S2, i & 0b1000000);
    digitalWrite(M_S1, i & 0b0100000);
    digitalWrite(M_S0, i & 0b0010000);
    digitalWrite(S_S3, i & 0b0001000);
    digitalWrite(S_S2, i & 0b0000100);
    digitalWrite(S_S1, i & 0b0000010);
    digitalWrite(S_S0, i & 0b0000001);

    delay(2);

    //edited as per @Gerben. thanks so much

    //get an individual sensor reading from IR receiver/opAmp mux, store it in a variable
     int IRstate = analogRead(InputFromMux);

    //populate receiving array with a reading
     recv_state[i] = IRstate;

    //populate display array for tlc5940 to push out
     dsply_state[i] = recv_state[i];

} //end for(i...) loop

      //run through display state array to check if the stored reading is greater than a threshold number
      //if yes, then turn on the "pixel". If not, set it to zero
      //

       for (int x = 0; x < ledCount; x++)
          if (dsply_state[x] >= thresh ) {

               Tlc.set(dsply_state[x], 4000);

             //or if reading from mux is zero
          } else if (dsply_state[x] < thresh) {

              Tlc.set(dsply_state[x], 0);
              }

            //tlc5940 Arduino library - update() clocks the chips
            // move update(); outside the for(x...) loop for speed?
        Tlc.update();
        delay(10);

      } //end For(x..) Loop

}//endMainLoop

The 48 in the for loop should be 96. It should be digitalWrite(M_S2, i & 0b1000000) not 0b110000. You do an anologRead, but never do anything with the read value (IRstate).

Thank you @Gerben. This is exactly the part that confuses me. How to correctly write the masks(?) that make the chips cycle through each input. If I digitalWrite M-S2 as i & 0b1000000, won't that be the same as M_S1? Or does it change enough as you've added six zero's instead of five - M_S1, i & 0b100000? As per IRstate, I thought I was pushing each reading into recv_state array in the for loop. Or should the variable be inside the loop? Or is there a better way to get each reading into an array?

You correctly spotted the extra 0. Your mask needs to be 7 bits long. 3 bits to represent a 0-7 for the first mux, 4 bits to represent 0-15 for the second stage muxes. Maybe for readability, you could add a 0 on the left of all mask.

The line of your code is IRstate = recv_state[x];. Maybe you meant recv_state[x] = IRstate; instead. The value of right part is what you assign to the left part. I think what you need is to remove the for( x ...) loop and add recv_state[i] = IRstate; and dsply_state[x] = recv_state[x];

Thanks @gerben, I'll edit the masks. Re:IRstate.....So that works without a for loop? int IRstate = analogRead(InputFromMux); recv_state[i] = IRstate; disply_state[x] = recv_state[i]; That three lines takes the individual readings, pushes all 96 readings into recv-state array and then maps recv-state[] onto a new display_state[] array? Is it the main loop then, doing the pushing?

You already have a for-loop. No need for the other.

Thank you @gerben. I see I missed the first for(i...) loop, so I understand how I was repeating. However, I'm not understanding how dsply_state[x] is iterating? dsply_state[x] = recv_state[i]; Isn't it just overwriting x rather than mapping 96 individual values into the dsply_state array? Should I just make it dsply_state[i] = recv_state[i];? Would that be the right way to map dsply_state array to recv_state array?

Yeah, sorry. I forgot to replace the x with a i. That would make the values in the dsply_state array the same as the recv_state array. PS. I'm only counting 5 } while there are 6 {s.

This helped so much. I've tried to edit the code as you suggested. It makes so much more sense now. Thank you @gerben

You will have a problem if you don't change the schematic. You have A0 unused on the 4051 chip, which means that your bit patterns are going to be out. You should really use A0 to A5 leaving A6 and A7 free. Otherwise the code will have to change to allow for that. Probably two loops would be easier in that case if you already have the board and can't change it.

You could also use the digitalWriteFast library which will somewhat speed up all those digitalWrites in the loop.

I take back that comment about digitalWriteFast. That requires both arguments (pin number and value) to be constants. The value isn't a constant.

OK. First, how the multiplexer works. I have a page about multiplexers in which there is this example of the 74HC4051:

Depending on the "binary" input to A/B/C (shown as S0/S1/S2 on your schematic) there is a low resistance path between one of the 8 inputs and the single output. The CD74HC4067 works in a similar way, except it switches 16 inputs.
So, if you set up the binary number 2 (010) in A/B/C then the third input is selected (number 02 because it is zero-relative).
In your schematic you have 6 x CD74HC4067 which therefore can have 16 x 6 inputs (96 inputs in total). The outputs of those 6 are fed into the 54HC4051 (2 aren't used) so therefore the 54HC4051 can select which of the 6 16-input chips it is interested in right now, by setting up a number between 0 and 5 on the 8-input multiplexer.
The four binary inputs to the 6 x CD74HC4067 are all tied together as you can see on the schematic.
Thus your method would be:

Loop from 0 to 5 on the master multiplexer (the 54HC4051). This selects which of the 6 16-input multiplexers you are interested in right now.
For each of those, loop through 0 to 15 on S0/S1/S2/S3 so that the currently-selected CD74HC4067 routes its input through to its output.
Read the resulting value

Those two loops will give you 96 inputs, which is what you are trying to read.
This technique takes 7 output pins to output the binary numbers (3 bits plus 4 bits). It also needs one input pin to read the result.

Judging by the schematic it uses SPI (serial data) to control the 6 x TLC5940 shift registers which lets it turn LEDs on and off with only two control pins (SCK and MOSI named SCLK and SOUT on your schematic).
The chips are daisy-chained together so all of those TLC5940s are controlled by those two pins.
This fairly minimalist design has therefore left some spare pins on the Arduino Pro.

Mostly having a hard time visualizing the code, especially how to write correctly the 7 binary digital write commands. Is it possible for you to correct what I've written above, so I might be able to see the pattern?

I know you changed the question by the time I saw this, but the code below illustrates what I mean by the two loops:
const int MUX_CHIPS = 6;
const int LEDS_PER_CHIP = 16;
const int TOTAL_IR_INPUTS = MUX_CHIPS * LEDS_PER_CHIP;
// Master IR -mux sensor pins for Arduino Pro MINI
const byte  M_S0 = 2;
const byte  M_S1 = 4;
const byte  M_S2 = 5;
// Slave IR mux sensor pins
const byte  S_S0 = 6;
const byte  S_S1 = 7;
const byte  S_S2 = 8;
const byte  S_S3 = 12;
//  ANALOG PIN :
const byte INPUT_FROM_MUX = A0;

int  recv_state[TOTAL_IR_INPUTS];           // IR Readings - FROM mux set-up

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

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

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(S_S3, OUTPUT);
    pinMode(INPUT_FROM_MUX, INPUT);

    // set ADC prescaler of 32
    ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
    ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
} // end of setup

void loop() {

  unsigned long start = micros ();

  // read from IR diodes

  int whichLED = 0;
  for (byte master = 0; master < MUX_CHIPS; master++)
    {
    // select appropriate slave on the master MUX
    digitalWrite(M_S2, (master & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master & 0b001) ? HIGH : LOW);

    // take each slave reading
    for (byte slave = 0; slave < LEDS_PER_CHIP; slave++)
      {
      digitalWrite(S_S3, (slave & 0b1000) ? HIGH : LOW);
      digitalWrite(S_S2, (slave & 0b0100) ? HIGH : LOW);
      digitalWrite(S_S1, (slave & 0b0010) ? HIGH : LOW);
      digitalWrite(S_S0, (slave & 0b0001) ? HIGH : LOW);

      // store this reading
      recv_state [whichLED++] = analogRead (INPUT_FROM_MUX);

      } // end of for each slave
    } // end of for each master

  // display results here ...

} // of loop

The exact code above took 5148 µs (around 5 ms) to execute the loop once on my Uno. If we remove the speedup of the ADC (analogRead) it takes 13252 µs (13 ms).
To allow for your exact wiring you need to ignore the low-order bit on the master MUX because you are not using input A0_13 in which case you need to add 2 to the master value in the outer loop:
    // select appropriate slave on the master MUX
    byte master_plus_2 = master + 2;  // allow for not using input A0
    digitalWrite(M_S2, (master_plus_2 & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master_plus_2 & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master_plus_2 & 0b001) ? HIGH : LOW);

Thank you @nickGammon. Appreciate the mux explanation. Very helpful. Mostly having a hard time visualizing the code, especially how to write correctly the 7 binary digital write commands. Is it possible for you to correct what I've written above, so I might be able to see the pattern? And yes, keeping this art installation very simple for now, at least until I can understand better

Look like you already have worked it out. You may want to change the ADC clock rate (see here). A prescaler of 32 will make the analogReads take only 26 µs rather than 104 µs which will improve responsiveness when you are reading 96 of them.

I updated my answer anyway to include the code I suggested (an inner loop and an outer loop). That will make it easier to change if you leave A0 disconnected on the master MUX.

This is sooo far out of my league :-) Regardless, thank you very much for the lessons @nickGammon. The explanations + code are so helpful. I will try both codes, the simpler and this double loop/pre-scaler after I solder up the circuit. I can still change the 4051 to use A0 - A5 as suggested and try to get that pre-scaler in there for speed. Especially considering that the 96 values, in turn, need to be pushed out through the TLC5940's as well


text:
Arduino code intermittent
Have an alarm for "tea time", "lunch time" and "tea time". Works well at times but occasionally it gets stuck on the alarm not resetting, other times it does not trigger the alarm.
please help I am new to Arduino and all of this.
here is the code:
#include <LiquidCrystal_I2C.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

ThreeWire myWire(4,5,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);
LiquidCrystal_I2C lcd(0x3f,16,2);
int Relay = 7;

void setup ()
{
    //RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
    //Rtc.SetDateTime(compiled);
    Serial.begin(9600);
    lcd.init();
    lcd.backlight();
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("  ClearChoice");
    lcd.setCursor(0,1);
    lcd.print(" Installations");
    delay(5000);
    lcd.clear();
    pinMode(7, OUTPUT);
    pinMode(8, INPUT);
    digitalWrite(Relay, LOW);
}
void Alarm()
{
    digitalWrite(Relay, HIGH);

    delay(3000);

    digitalWrite(Relay, LOW);
}

void AlarmActive()
{
    RtcDateTime now = Rtc.GetDateTime();
    int MySec = now.Second();
    int MyMin=now.Minute();
    int MyHour=now.Hour();
    int MyDay=now.DayOfWeek();

    if(MyHour==10 && MyMin==00 && MySec==00 && MyDay<=5)
    {
        Alarm();
    }
    if(MyHour==10 && MyMin==15 && MySec==00 && MyDay<=5)
    {
        Alarm();
    }
    if(MyHour==12 && MyMin==00 && MySec==00 && MyDay<=5)
    {
        Alarm();
    }
    if(MyHour==12 && MyMin==30 && MySec==00 && MyDay<=5)
    {
        Alarm();
    }
    if(MyHour==15 && MyMin==00 && MySec==00 && MyDay<=5)
    {
        Alarm();
    }
    if(MyHour==15 && MyMin==15 && MySec==00 && MyDay<=5)
    {
        Alarm();
    }
}

void Clock()
{
    RtcDateTime now = Rtc.GetDateTime();
    int dayOfWeek = now.DayOfWeek();
    String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    lcd.setCursor(0,0);
    char buffer[3];
    lcd.print("Date: ");
    lcd.print(now.Day());
    lcd.print("/");
    lcd.print(now.Month());
    lcd.print("/");
    lcd.print(now.Year());
    lcd.setCursor(0,1);
    lcd.print("Time: ");
    sprintf(buffer, "%02d", now.Hour());
    lcd.print(buffer);
    lcd.print(":");
    sprintf(buffer, "%02d", now.Minute());
    lcd.print(buffer);
    lcd.print(":");
    sprintf(buffer, "%02d", now.Second());
    lcd.print(buffer);
    lcd.setCursor(0,1);

    Serial.print("Time: ");
    Serial.print(now.Hour());
    Serial.print(":");
    Serial.print(now.Minute());
    Serial.print(":");
    Serial.print(now.Second());
    Serial.println();
    Serial.print("Date: ");
    Serial.print(now.Day());
    Serial.print("/");
    Serial.print(now.Month());
    Serial.print("/");
    Serial.print(now.Year());
    Serial.println();
    lcd.print("Time: ");
    Serial.println(days[dayOfWeek]);
    Serial.println();
    AlarmActive();

    delay(1000);
}

void loop ()
{
   Clock();
}

Please try delaying only for like half a second instead of a full second in Clock(). Currently you are probably occasionally missing the relevant second of an alarm.

Thank you. Will give it a try.

Also, Alarm() has a 3-second delay. This can contribute to the issue you are seeing, as @chrisl mentioned. Check out an example called "blink without delay". That should give me some idea about how NOT to use delay.

Thank you.
Fahad

What do you see on the serial monitor when the program fails to work as expected?

@Fahad: You changed the code while reformatting it. Maybe you should explain to the OP that the empty else statements have no effect at all and can be removed.

forget the seconds ... trigger the alarm on day, hour, minute ... insert a 60 second delay at end of alarm() so that it triggers only once every alarm time


text:
Teensy and MS5803 sensor
I'm trying to use the MS5803 pressure sensor with a Teensy 3.2. Compiling the Sparkfun, or other, libraries, however, results in no output.
Can you provide guidance on how to modify the libraries to work with the Teensy (t3_i2c)?

Why not ask on the Teensy forum? In any case links to the sensor, the libraries, and providing your code would make your question more meaningful.