I would double check the pin numbers for the attiny. They look like port bit numbers but that might just work by chance.

const int transmit_pin = PB0;
const int sensor_pin = PB4;

A quick double check with the attiny/pins_arduino.h give:

// ATMEL ATTINY45 / ARDUINO
//
//                 +-\/-+
// Ain0 (D5) PB5  1|    |8  Vcc
// Ain3 (D3) PB3  2|    |7  PB2 (D2) Ain1
// Ain2 (D4) PB4  3|    |6  PB1 (D1) pwm1
//           GND  4|    |5  PB0 (D0) pwm0
//                 +----+

As you have found they should be defined as:

const int transmit_pin = 0; // Physical pin 5
const int sensor_pin = 4;   // and pin 3

This type of issue could be avoided by using strong data typing and object oriented design. Please see for instance Cosa ATtinyX5.hh and GPIO.hh.

Cheers!

Here is something that does basically the same as the sender. Cosa supports attiny and Arduino boards "out-of-the-box".


How to prevent breaking my Arduino by mistake?

Not best practices, but an alternative approach:

Consider the Ruggeduino instead of a standard Arduino. At a price ($39.95) comparable with the equivalent Arduino, the Ruggeduino offers:

Resettable fuse on each GPIO pin, i.e. all GPIO pins are protected from short-circuit to ground or other pins
All GPIO pins withstand 24 Volts
Reverse voltage protection (-30 V) on Vin
Microcontroller overcurrent protection
3.3V and 5V outputs on the board are over-current and short-circuit protected

Besides the above points specific to the question, the boards are designed to survive harsh environments and various mistakes. Also, the clock is more precise than on the Arduino.


Arduino with wifi shield and 5AA batteries current draw

As a general answer, yes. AA alkaline should be more around 2500~3000 mAh depending on quality. 5x AA in series would result in 7.5 Volts and 2500 mAh.

But that's only for almost fully charged batteries. AA batteries can range from 1.6V to 0.8V "dead for most purposes". As they drain, the voltage drops.

What may be happening is that you are powering the Arduino through its power jack, which goes through a diode, causing a 0.7V drop. Then it goes to the linear regulator which has a very high drop out voltage. Or even via the VIN pin, bypassing the diode. But as the battery drains, the voltage drops below the regulator ' s limit.

The Arduino microcontroller can easily work below 5V. The shield might not.


Recursive list of files on SD card with indexing

dirFile.open("/", ...) opens the root directory which always exist, even if there are no files.

You can check if there are files by checking openNext. If the first call returns false, there are no files or folders.

Some unrelated remarks:

Name variables you use, with more than 1 character (so e.g. numberOfFiles instead of n)
Do not increase a variable inside a Serial.print statement .. if you remove the 'test/debug' code, your sketch behaves differently.

Update:

I now see your question about the array. 300 is probably what you assume is the maximum number of files. Note that if 300 is passed, the sketch will crash.

What you can do to prevent this:

Easy solution: stop storing files after 300. In this case, make 300 a constant.
Solid solution: do not use a predetermined length array. However, this means some disadvantages:

You have to create a list structure and dynamically change the code.
This is slower (probably not an issue since SD card communication is much slower)
It can result in memory gaps, resulting in hard to solve memory problems later if the code is extended and more memory is needed.

I suggest you add some code, to stop storing at 300.


Can I use the setup() function inside the loop() function

It could be possible, since it is going simply to call the same function BUT it is really a very bad design*.

Usually the main purpose for a microcontroller is just sitting there and run a procedure or main function repeatedly until the end of the world. And during one loop just to check if some conditions are met.

You should never stop or influence your loop() function and never mess up the default design of the arduino.

In you case (but it depends on your code and your application), you just want to run the loop() once all sensors have been already started (in the setup() function).

In your run, you check periodically the sensor and start a timer (better if interrupted). If an amount of time has expired and the sensor should be turned off, then the timer will call another function, which has the only target to switch sensors off.

The loop() runs again and again and if the original condition is met, then you can start your sensors again.

To save up time and code typing, I suggest you write only ONE function for switching on the sensors and call this function in setup() and in your loop(), something like this:

void startSensors();
void stopSensors();

void setup() {
  startSensors();  // I start all sensors here
}

void loop() {
  if( condition?!?! )
     {
       ...
       stopSensors();
       ...
     } else {
       ...
       startSensors();  // I call the same function here
       ...
     }
}

*: for istance you define in your setup() the connection through serial port. This means that your object "serial port" is going to be recreated each time you call setup() whit undefeined behavior in case it is outputting datas or has same data in the FIFO Buffer. Simply...setup() has that name because needs to setup things once. Everything that must be done more than once, then must be called from run() too.


Receiver xbee receiving data even if the Transmitter is not sending?

The reason that it is printing characters with no input is that the readBytesUntil function has a timeout. If no new characters are received for a certain amount of time, "Serail.setTimeout()" seconds, it will just continue with the code. the default timeout is 1 second.

The reason you are not receiving what you transmit (or at least a reason) is that the RX code does not read from an xbee, but reads from regular "serial".

I recommend you try something simple first to test the xbee's configuration, like having TX run this:

void loop(){
    xbee.println("Hello");
    delay(1000);
}

and RX run something to echo serial like this:

 void loop(){
     if(xbee.available()){
         Serial.print((char)xbee.read());
     }
}

And make sure you set up an xbee object an the receiving side first.


How to read a 25 kHZ PWM signal from PC fan header?

Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
  Can the ATmega328p handle this frequency range?

No, and No; 1/25000 = .000040 or 40 microseconds (μS) and the documentation for pulseIn() says:

  Works on pulses from 10 microseconds to 3 minutes in length

However the PWM frequency is the maximum on time, at 50% you will have a square wave that is HIGH for 20 μS and low for 20 μS. pulseIn will not work if the PWM duty cycle goes below 25%

What you want to do is put an 'accumulator' (an RC filter) between the PWM output and an analog input pin, and read the voltage off of that.

However since you want to

  ... control a DC motor's speed using the PWM output from my motherboard header

and the fanspeed header is already designed to do this, you just use the PWM signal to drive a transistor that drives the motor, the motor itself will act as an accumulator here; no micro controller needed!

  ... so that I can use a motor driver to control my motor's speed.

you will need to generate an extremely similar, almost certainly identical, PWM signal to drive your motor controller/driver

  A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

Trust your documentation or test it if you don't trust the docs!


Should I control each of the four robot wheel separately or wire two from each side together?

it looks like you have two channels on each controller, so you have some options here. but first I'm going to talk a bit about your motors. If you have a spec sheet for them you can gather most of this info through that, but it doesn't hurt to do some experimentation. A motor will draw max current when it is stalled (is trying to drive but it can't), and you can determine this "stall current" with a multimeter or from the spec sheet. when you're driving the robot, this can occur when you drive up to a wall and try to push through the wall (hint, no robot this size will damage a well built wall) but likely the driver will reach a wall and stop driving (unless she can't see the robot while driving, idk). the lowest current it will draw (aside from zero when it can't...) is it's "free speed" current, this is when it's spinning as fast as it can with no load on it. while you're driving the robot you can expect the current to be between these numbers, if you want to get super fancy (and you want to equip your robot to do this) you could log the instantaneous current every 10ms or however often (this can be useful if you want to diagnose faults, but again its a small robot)... so if you have two motors in parallel (which you want to do because in series one will drive harder than the other), then the current drawn by each will add, so you can double it for two motors.

anyways, here's a few options for the motor configuration:

if two of your motors in parallel draw less than continuous 1.2 amps, you could use a single controller for one robot, controlling left wheels on channel 0 and right on channel 1.

if your motors draw more than that in parallel, you will have to use two channels per side, however you could Y the PWM lines between the motor controller and the arduino

if you are using something like omni wheels and want control over every single wheel, obviously you will want one channel per wheel...


Distance Sensor. Calculating running median and Average

There are two main problems with your program. The first is noted in
Gerben's comment: you (attempt to) increment index (with a bad
syntax), while you should be incrementing i instead. The second
problem is these lines:

for (i = 0; i <= 8; i++) {
    int_array[i] = 0;
}

Fix the index vs. i confusion, remove the lines above, and your
program should work.

Explanation: The first point should be obvious, I hope. I am
discussing here the second issue. At the end of the loop above, the
index i has the value 9. Later, in loop(), and assuming you fixed
the first issue, the program does

i++;
if (i == 9) {
    i = 0;
}

and i has the value 10. From there i will continue incrementing, and
you are always writing outside of the array.

The root of the problem is that you used the same variable i for two
different purposes. There are several solutions to this:

use different variable names for different purposes
use local variables whenever applicable (here: in setup())
be defensive in your tests: instead of if (i == 9) write
if (i >= 9), but note that this alleviates but does not completely
solve the problem
remove the initialization of the array altogether.

I suggest removing the initialization because the array is a global
variable and, per the C++ standard, if not explicitly initialized it is
implicitly initialized to zero, so your initialization is redundant.


You could use an opto-coupler:

An opto-isolator (also called an optocoupler, photocoupler, or optical
isolator) is an electronic component that transfers electrical signals
between two isolated circuits by using light. Opto-isolators
prevent high voltages from affecting the system receiving the
signal. Commercially available opto-isolators withstand
input-to-output voltages up to 10 kV and voltage transients with
speeds up to 25 kV/μs.
A common type of opto-isolator consists of an LED and a
phototransistor in the same opaque package. Other types of
source-sensor combinations include LED-photodiode, LED-LASCR, and
lamp-photoresistor pairs. Usually opto-isolators transfer digital
(on-off) signals, but some techniques allow them to be used with
analog signals.

Here is an example schematic and packaging:

If you have a heavy load (although this does not seem to be your case) then they can also be used in conjunction with relays - here is an eight channel opto-coupler relay module board:


Thank you all...
I found solution for my problem.
The circuit and the sketch isn't any problem. But I saw this and I think problem is because of LC Studio's SD card. In previous circuit I connect 5v pin of SD card to 5v pin on arduino. But now I disconnect that and connect 3v3 pin on card to 3v3 on arduino.
Now it's work very nice. And I don't know "why?" . Any idea?


Controlling multiple 24V solenoids with Arduino

No, it won't:

The diode D1 is backwards.
The opto-coupler is wired completely wrong.

You don't actually need the opto-coupler as long as the threshold voltage of the MOSFET is low enough for the Arduino to switch.  However if you do want (or need) to use it you should wire it like this:

simulate this circuit – Schematic created using CircuitLab

R1 is a pull-down that keeps the MOSFET off when not being turned on (just like with a button). The value doesn't matter much.  R2 is a resistor just like you use for any LED with an Arduino.  D1 must be connected reverse biased or it will just short out your solenoid. The opto-coupler must be connected with the transistor the right way around or it will not work (or melt, or create a black hole...)

To ditch the opto-coupler you can just treat it like any other load on the Arduino (as long as the MOSFET's threshold voltage VGS is below 4V):

simulate this circuit


Thanks @Arjan for reminding me. I would love to contribute to the community. So this is my final coding and its worked for me :

const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
  digitalWrite(yellowLed,HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
  if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}
}
}


Arduino pin 13 as PWM output, not possible?

Arduino pin 13 is SCK/BP5 on the ATmega8 MPU, there's no hardware PWM capability on that pin, so any PWM would be software driven.


Question about configuration EEPROM or Flash

Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).

Perfectly viable - although an SPI Flash chip would be more appropriate.

  Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).

It is the bootloader that can write to flash. I don't thing the main program can write to flash, or it would wipe itself out. You may need a special bootloader with your own protocol and upload program to go with it.

  Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.

Perfectly viable, but tricky to say the least.

  Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

Yes, 512 bytes of SRAM, since that is the size of one block on an SD card. But an UNO has 2048 bytes of SRAM - more than enough for SD card support.

The SD card would be my route of choice. It's the easiest from a user's perspective (slip the card into their computer and copy the files), and pretty simple and straight forward to connect and program the Arduino for.

  To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

If you know where in the file the byte are then you can seek() straight to them. Takes almost no time. 20ms is an eternity for a microcontroller.


So i recently bought an arduino along with lcd module and 2 extra atmega328p-pu ,yesterday it was working just fine then i disconnect everything and reconnect it and this happen, what could possibly go wrong ?

I hope you understand how difficult it is for anyone to help with this type of question.

My quick answer is "follow the schematics and reconnect the wires correctly" and "double check all wires".

From the picture it looks like you need to adjust the LCD contrast and reduce the back-light. Please see typical schematics for this.

Another rule-of-thumb is to use wire colors in a meaningful way. For instance, black for GND, red for VCC, yellow for data, blue for control, green for clock, etc.

Cheers!


SPI communications with an Yost Labs IMU

You almost certainly shouldn't raise CSN after each byte, only after the entire packet.
Although the data sheet is not explicit the chip select is usually used to frame an entire command. As it is at the moment it keeps starting a new transaction.
I like the comment in the data sheet that "...the 3-Space Sensor will not work properly in outer space or on planets with no magnetic field".


You need to determine what the network address is of the LAN you have connected the arduino to. A router can often give you this information. Alternatively you can connect a computer to the same network and look at the computers network settings (this varies depending on what OS you use). Then you have determine what IP address is available on that network. You will enter this in the ip variable in your example.

The internet is not required for your application, however you do need the arduino to be connected to a LAN and another device (probably a standard computer) to invoke the arduinos server behaviour.

To test that it works, you can open an internet browser on the second device and type in the IP address that you have configured for the arduino into the address bar.


Can I use atmega328P without capacitors?

Those specific capacitors form part of the resonant clock oscillator circuit. If you are using a quartz crystal then they are required. You can't do without them.

If you use a 16MHz ceramic resonator, however, they don't need the capacitors (they're built into the resonator).

Also, if you have your ATMega328P on a breadboard the capacitance of the board itself is sometimes enough to "get it working", though as soon as you transfer your circuit to a permanent PCB it will suddenly stop working for no apparent reason.


The accepted way to initialize an array in C follows this example:

const char ID [] = {111, 11, 11, 11};

You can read more about it here.

You later use an array name ("ID") with no index ("ID[0]").  The C compiler assumes the programmer who uses an array name with no index is interested in the memory address of the first element of the array.  But you wanted the value in that memory location.  So you should use the array name with the appropriate index.  Guessing, it would appear you intended to use "ID[i]" in the above code fragment.


Edited to suggest driving the outputs low.
To use a multiplexed grid of switches like that you'll need to write code that sets all the columns to open, sets all the input rows to INPUT_PULLUP, drives one column at a time low and scans the rows for low output to figure out which buttons are pressed. (You could reverse the rows and columns, or add external pull down resistors and pull the rows/columns high rather than grounding them, but you get the idea. You'll need to write code to scan the grid of buttons in nested for loops.)


You could check from where you have bought it. Maybe they have datasheet.
I found one similar, but before you must check if everything is the same and then do testing with power. LuckyLight


How to create a wired ESP8266 range extender?

There's a project that calls itself a "wifi repeater" at

https://github.com/martin-ger/esp_wifi_repeater

It includes support for an ENC28J60 ethernet adapter connected via SPI.

It has some serious limitations.

First, it's really a NAT (Network Address Translation) router, not a Wifi extender, though it can effectively extend wifi. However, devices being extended will not be able to communicate with devices on the original network via broadcast or multicast. This will break some applications and many IoT devices.

Also, devices on the original network will not be able to originate connections to devices on the extended network.

But if you just have some devices that only need to talk to the Internet and are a little too far for your router, this should work for them.

Also, the ESP8266 can only get about 5Mbps through it (I'm actually surprised it's that high). You probably won't be able to reliably stream video - definitely not 4K video. It's not a good choice for connecting a television and probably won't work well with security cameras.

Finally, as @Juraj mentioned, it's not an Arduino project. You'll need to install the NON-OS SDK and toolchain to build it. It does include a pre-built image and instructions on how to flash it.

I haven't used it and can't promise that it will work well, but it's the closest thing I'm aware of to what you're looking for.


I have only worked with the SIMCOM series of GSM modules like the SIM900 and the SIM808. Here is a sample of the kind of code you should be looking at using.
It will send one "AT" to the GSM module and then it will spit out the result in the serial monitor.

void setup()
{
  Serial.begin(115200);
  int bytesSent = Serial.write(“AT\r\n”); //send "AT" and send the end of line characters to signify end of the command
 }

 void loop()
{
   if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();
    }
}


How do I use an AtTiny85 (or other AtTiny) with Arduino?

1. The Tiny

The ATtiny differs a little from the Arduino, don't expect it to be "fully compatible". It's a microcontroller which is just a part of an Arduino and not a full Arduino itself.

It's more of a device for "advanced users" and gives some more flexibility (at cost of usability). You can easily add this microcontroller on a breadboard, since putting a full Arduino on a breadboard makes little sense.

1.1 USB?

Since the ATtiny is a microcontroller (like the ATmega on an Arduino) and not a development board (as an Arduino), it does not have an USB connector.
The ATtiny series also does not have hardwareUART (Rx/Tx). The

You'll have to take care for a steady power-supply to your Microcontroller and the programming will be a little more tricky (details further below).
It is however possible to use SoftwareSerial and a customized bootloader. My ATtiny85 runs software serial with 115200 fine, though I have found a post which states that the internal oscillator should be tuned for a reliable connection.

1.2 RAM/program memory

The ATtiny has less RAM and program memory. This essentially means your program can't be as 'big' as on a normal Arduino. It also means that you can't use as much variables. A program for the tiny should be "small" or very efficient.

1.3 "Speed"

My ATtiny came with 1Mhz internal clock set, but if you change the fuse bits you can make it run at 8Mhz. An standard Arduino has a 16Mhz clock on the board. So your code would run 16x slower on default and 2x slower on "max". You could use an external clock for the ATtiny, but that eats up 2 pins.
The cool thing is, when you set it to 1Mhz it can run on about 2.7V (check datasheet first).

Arduino                   16Mhz
ATtiny (standard)         1Mhz
ATtiny (set fuses)        8Mhz
ATtiny (external crystal) up to 20Mhz

Higher Mhz is faster. Keep in mind that 1Mhz is roughly 1000000 instructions per second, which is still blazingly fast and good enough for most occasions, especially on such a tiny device.

2. Programming the Tiny

Most of the ATtiny's don't come with a customized (software serial) Arduino bootloader. This essentially means that you have to burn a custom bootloader by yourself or use another type of programmer. You should really watch the video from Ben Heck. He explains that Arduino boards have an USB converter on board and have custom code that is able to "bootload" your Arduino. But that ICSP/ISP programmers are used to upload programs without a bootloader/uart connection.

2.1 The programmer

You've got a load of options, check the "Programmer" item in the "tools" tab in your Arduino IDE. I'm using an USBasp which can be bought on ebay for as little as 3€. You should get one that has a selectable voltage (3.3V and 5V).

(If your ATtiny85 already has the bootloader, which is unlikely, you can use the software rx/tx pins for uploading)

2.2 Preparation

Check your microcontroller if it really is a ATtiny85 my E-bay reseller actually had one ATtiny45 included, which lead to an "error" when trying to upload.

The Arduino IDE does not know the "ATtiny board" so you can't select it easily. You'll have to let the IDE know that the ATtiny can also be programmed.

I found a very nice tutorial that describes how to do this.

  Open the preferences dialog in the Arduino software. Find the
  “Additional Boards Manager URLs” field near the bottom of the dialog.
  Paste the following URL into the field (use a comma to separate it from any URLs you’ve already added):
  https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json
  Click the OK button to save your updated preferences.
  Open the boards manager in the “Tools > Board” menu.
  Scroll to the bottom of the list; you should see an entry for “ATtiny”.
  Click on the ATtiny entry. An install button should appear.
  Click the install button. The word “installed” should now appear next to the title of the ATtiny entry.
  Close the boards manager. You should now see an entry for ATtiny in the “Tools > Board” menu.

2.3 Changing the internal clock

Some interesting post I found told me that you can change the internal clock/oscillator to 8Mhz by selecting 8Mhz (internal) as the clock and pressing the "Burn bootloader" button. This won't flash a bootloader (since that makes little sense on a Tiny85) but does change the fuse-bits.

2.4 Code

You'll not get away with the standard blink tutorial. It uses digital pin 13 (the tiny only has 8 pins).

Mind that you might have to upload using Ctrl+Shift+U (or sketch->Upload with programmer).

I used the diagram below to check the pins (from highlowtech.org)

3. Hardware

Your "schematic" isn't complete, I don't see a way to program or power the microcontroller. And you might want to take some precautions.

I personally think a well-drawn schematic looks better as a "breadboard view".

The 10Kohm pull-up resistor on the reset pin is not 100% neccesary according to the datasheet. But the Uno has one in it's reference design (which I use as a reference).

There are two capacitors, one "big" capacitor as a reservoir. If one device suddenly pulls a lot of current, this capacitor will handle that. The smaller decoupling capacitor will damp the noise of other IC's or switching supplies. It may work withouth these, but your circuit will be more reliable with them.
Mind that the decoupling capacitor should be (physically) close to the IC.

You can power the board through the programming header, but mind that you'll need a smooth voltage between (most likely) 3.3V and 5V. If you want to power it with a bigger voltage (9V battery) then you'll need a voltage regulator.


PCF8583 with Arduino delay of one second?

Check your schematic vs the datasheet and make sure that it makes sense.
Check to make sure that your input is right. You can print it back right away, or set the etc to a known good time and see if it keeps time.
Check the library to make sure that it is good.


Using Capacitive Sensing Library with a 74HC4067 multiplexer

This is way late, but for anyone who runs across this, here was my solution. The two main thing is explicitly using analog input pins (which could be quantized to digital values in the software, and making sure you have resitors on each channel being sensed. Also, ground the EN pin on the multiplexer

#include <CapacitiveSensor.h>

#define muxS0Pin 9  // I used these rather than 4-7
#define muxS1Pin 10
#define muxS2Pin 11
#define muxS3Pin 12

#define muxSignalPin A0      // explicitly set ro analog
#define capSenseSendPin A2   //

#define sampleRate 10
#define n_inputs 16

int touch[n_inputs] = {};

CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

int readMux(int channel) {
  int controlPin[] = {muxS0Pin, muxS1Pin, muxS2Pin, muxS3Pin};

  int muxChannel[16][4] = {
    {0, 0, 0, 0}, //channel 0
    {1, 0, 0, 0}, //channel 1
    {0, 1, 0, 0}, //channel 2
    {1, 1, 0, 0}, //channel 3
    {0, 0, 1, 0}, //channel 4
    {1, 0, 1, 0}, //channel 5
    {0, 1, 1, 0}, //channel 6
    {1, 1, 1, 0}, //channel 7
    {0, 0, 0, 1}, //channel 8
    {1, 0, 0, 1}, //channel 9
    {0, 1, 0, 1}, //channel 10
    {1, 1, 0, 1}, //channel 11
    {0, 0, 1, 1}, //channel 12
    {1, 0, 1, 1}, //channel 13
    {0, 1, 1, 1}, //channel 14
    {1, 1, 1, 1} //channel 15
  };

  //loop through the 4 contol pins
  for (int k = 0; k < 4; k ++) {
    digitalWrite(controlPin[k], muxChannel[channel][k]);
  }
  //read the value at the SIG pin
  return capSense.capacitiveSensor( sampleRate );
}

void setup() {
  // Very important to set control pins to output mode
  pinMode(muxS0Pin, OUTPUT);
  pinMode(muxS1Pin, OUTPUT);
  pinMode(muxS2Pin, OUTPUT);
  pinMode(muxS3Pin, OUTPUT);

  digitalWrite(muxS0Pin, LOW);
  digitalWrite(muxS1Pin, LOW);
  digitalWrite(muxS2Pin, LOW);
  digitalWrite(muxS3Pin, LOW);
  Serial.begin( 9600 );
}

void loop() {
  byte touchIndex = 0;
  for ( byte channel = 0; channel < n_inputs; ++channel ) {
    Serial.print( readMux(channel));
    Serial.print("\t");
  }
  Serial.println();
}


Joy stick Implementation on PID controlled balancing robot

I'm not 100% sure what your expect problem is … I assume you can read left and right on the joystick (very similar to up and down).

To make a left movement, you have to either stop the left wheel and rotate the right wheel forward (so you make a left turn), or if you want an even faster movement, move the left wheel backwards and the right wheel forward.

For a right movement, do the opposite.

(actually having a different speed for the left and right wheel already causes a turning movement).


SPI is supposed to be used for things in close proximity to each other. See Wikipedia - Serial Peripheral Interface Bus.

  The Serial Peripheral Interface (SPI) bus is a synchronous serial communication interface specification used for short distance communication, primarily in embedded systems.

(My emphasis).

At that distance, and at standard SPI speeds you are probably losing signal integrity. The default SPI speed is system clock divided by 4 (that is, 4 MHz). It's not surprising some bits go missing after 40 feet.

See my page about SPI - you can use SPI to transfer to a 595 register (as described here).

(I'm assuming you are talking about a 74HC595 shift register)

I suggest running at a somewhat lower speed - insert delays after toggling the clock pin (each way). Or use the SPI hardware at (say) SPI_CLOCK_DIV128.

  The shift register is very close to some 110V wires. Maybe interference

You might also want to look at a balanced line driver (eg. RS485) - I have a page describing that.

  The 5V power supply isn't powerful enough to power the relay board and the shift register?

The register won't take much power. I trust the relays are solid-state ones and not coils that you are directly driving from the 595 chip?

Also see How do you use SPI on an Arduino?


softwareserial between arduino uno and esp8266

Make sure that:

RX pin on the Arduino UNO is connected to the TX pin on the ESP8266.
TX pin on the Arduino UNO is connected to the RX pin on the ESP8266.
Baud rate should be set to the same value from both the Arduino and ESP8266.

I don't know about your arduino but looking at this schematic, your RX and TX should be swapped.


Arduino communicating back and forth with PHP server

I would suggest your best bet would be to pass messages back and forth via JSON, via Get/Post http request.

So to send data, you send a POST request (to the PHP server) with your data in JSON in the content.  To get instructions, you send a GET request to the PHP server and get a contents field with JSON in it.


You could try to use a force sensitive sensor to detect when grass blades touch it.


How to send a message to my phone that my Arduino system is on when turning on my Arduino

You can send an SMS using the Arduino GSM library. Here is a bare bones sketch that sends one pre-set SMS when it starts up, based on this tutorial:
#include <GSM.h>

#define PINNUMBER "1234"
#define REMOTENUMBER "07123456789"
#define TXTMESSAGE "System started!"

GSM gsmAccess;
GSM_SMS sms;

void setup() {
  boolean notConnected = true;

  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      delay(1000);
    }
  }

  sms.beginSMS(REMOTENUM);
  sms.print(TXTMESSAGE);
  sms.endSMS();
}

void loop() {
}

If you can't or don't want to use the GSM library, it should also be possible to send an SMS by using the SoftwareSerial library to control your GSM shield using AT codes. Here's a tutorial on this approach, which is lighter weight but might be more fiddly to get working, especially if you need a PIN for your SIM card.


How to program the Robotdyn Mega 2560 PRO MINI?

Connect the Arduino to the FTDI in the following way:

FTDI - Arduino
VCC - VCC
GND - GND
RX - TXD
TX - RXD
DTR - 100nf capacitor - RST
CTS is not connected

Use the following settings in the Arduino IDE

Board: Arduino/Genuino Mega or Mega 2560
Processor: ATMega2560 (Mega 2560)

The image shows the Arduino with colored connectors and with 4 extra rows of connectors. These are not part of the original Arduino. I added them to make it easy to connect lots of I2C devices for testing.


Connect to more than one Arduino with Adobe AIR

This seems to be possible with as3Glue as per the docs:

as3Glue is an ActionScript 3 library that enables communication between Flash/Flex/AIR applications and Arduino boards. It can together with one or several Arduino boards be used to monitor sensors (such as rotary encoders and motion detectors), control actuators (such as LEDs and motors) and interface other electronics (such as RFID readers) from Flash, Flex and AIR applications.

as3Glue can be used with as3-arduino-connector as mentioned in the docs:

Using with as3Glue
Download either the SWC or Source Code from the Downloads section of this project for a patched version of as3Glue. This patched version has the exact same interfaces as v20, with a notable exception of the constructor. When you instantiate a new "Arduino" object, replace the IP address and port with the COM port and baud rate. For example :
public var myArduino:Arduino = new Arduino("COM10", 57600);


Unlike other more "normal" build systems, the Arduino IDE doesn't compile the files in the project directory.

Instead it loads all the files with certain extensions into the IDE, each in its own tab. When you press the compile button it then writes the contents of each of those tabs to files in a temporary build folder and then compiles there.

Because of that only files with certain extensions ever get placed in the build folder. Those include:

.pde and .ino for sketch files
.c and .cpp for C and C++ source
.h for headers
.S for assembly source.

There may be a few others as well but those are the main ones. Things like text files aren't considered source files and thus aren't ever seen by the IDE.


ISR(USART__RXC_vect)
{
  char ReceivedByte;
  ReceivedByte = UDR0;
// Fetch the received byte value into the variable "ByteReceived"
}

USART__RXC_vect is not the name of the interrupt vector, USART_RX_vect is.

If you don't get the name right there is no compiler warning, however the interrupt routine is not called.

UCSR0A |= (1 << RXCIE0);

That line is wrong. RXCIE0 is in UCSR0B not UCSR0A. If you set the bit in the correct register you will get an interrupt.


Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port

One of the option is using Proteus simulator with Arduino library. You can build the program via Arduino IDE, then export the compiled binary (.hex file). Proteus also provided virtual terminal feature (not Virtual COM).


How can I attach I2C sensors on the small board of Intel Edison?

If you're using the mini-breakout board (https://www.sparkfun.com/products/13025), then you can get the I2C connections from the board (connections available through holes under the Edison; you can see them from the backside; see: https://cdn.sparkfun.com//assets/parts/1/0/0/1/1/13025-02.jpg). You can solder headers on or can solder wires directly to the required pins. You can find the pin mapping here: http://iotdk.intel.com/docs/master/mraa/edison.html


You could use a GPIO expander (MCP23017 or similar) which could give you 14 extra pins (16-2 for I2C bus), but this is putting extra load on the microprocessor.  (you haven't said which one by the way).

Or another option might be to revisit you design and see if you can split it out to multiple processors.  This is effectively the same as a GPIO Expander, just using an Uno or ESP8266 as the expander.


My guess: Fully Qualified Board Name

I.e., a descriptor that uniquely identifies a board and its configuration.


Sending A String from a Website to Arduino

On the yun, this functionality is built-in via the bridge. Here's an example.

Via the shield, you now end up writing your own webserver and responding appropriately.

I'm guessing it makes more sense to use the client (the web browser) to make the calls than the backend php, but in either case, once the webserver is up and going on the arduino, you're just using it like any other server.


Apparently the name RECV_PIN is used somewhere else, presumably in IRRemote.h -- although not in any version of it I can find.  Anyway, just change the name of RECV_PIN to something which doesn't conflict.

For example:

int MY_RECV_PIN = 11;
IRrecv irrecv(MY_RECV_PIN);


Integrating Java program with arduino mega is it possible?

There is a project called uJ by Dmitry Grinberg that enables you to do that, somehow. It has been tested on AVR devices too, not your particular one however. Knowing AVRs, that shouldn't be a stopper at all.

That said, I don't think it's a very good idea. The overhead of the JVM may only let you handle some 'slow' signals, unless you heavily rely on peripherals and wit to do stuff. Though in your particular application, that shouldn't be that much of an issue.

Instead of having the trouble of running a JVM and such, you may just as well rewrite the code in C/C++ or whatever, even for increased efficiency. There may also be some Java to C transpilers, I haven't looked, wary of the dragons.

However, if you eventually decide against that and instead choose to talk to the microcontroller over serial or something else, there is the dreadful excellent RxTx library for Java that works pretty fine after all, or the Firmata library.


How to get a specific value from an unknown number of JSON representations?

Directly from the ArduinoJson Assistant:
// Stream& input;

StaticJsonDocument<384> doc;
deserializeJson(doc, input);

for (JsonObject elem : doc.as<JsonArray>()) {
  const char* ID = elem["ID"]; // "12345", "13244", "00345"
  const char* name = elem["name"]; // "John Smith", "Jason Statham", "Paul Anderson"
  const char* Address = elem["Address"]; // "Street 1", "Street 2", "Street 3"
}

See also:

How to use ArduinoJson with HTTPClient?
How to deserialize a very large document?


How to control an 12V 2A Car lamp using relay or MOSFET in Arduino

You can use a RFP30N06LE mosfet. It can support up to 60V 30A

Here is a wiring schema


I would expect only one data line output from the receiver.

Looks like the manufacturer might have just connected the 2 data pins together. You could try using either pin to confirm that the two data output pins are simply connected together.


Sending values from Matlab to arduino using serial communication

You send a string of ASCII characters representing a number in human readable format.

You then read one of those characters that represents a single digit and then try and use it as if it were a number.

Instead you need to read the whole string of numbers (which means having some way of knowing where the end of the numbers are in the stream of characters that arrive) and then interpret it back into a number again.


Can I power my Arduino Uno with a 9V / 990mAh battery?

While this answer addresses the specific question it should also prove useful as a link to resources relating to current reduction in other microcontroller projects.

Short:

The "C" rate for a cell is a current in mA numerically equal to the capacity in mAh
eg 1000 mA for a 1000 mAh cell.

In the absence of a specific data sheet a LiIon or LiPo cell is probably safe for maximum charge and discharge rates of C/2 and C.
ie 500 mA max charge rate for a 1000 mAh cell and
1000 mAh max discharge rate for a 1000 mAh cell.

In many cases double those rates will be safe.
Charge rates are seldom higher than C but discharge rates of substantially higher than 2C MAY be safe - see data sheet!.

In your example case, the operating time will be approximately mAh/average_current. Consult the data sheet for your microcontroller and/or measure current drain.

A typical "bare" Arduino with processor, USB IC, LEDs and "glue" components probably draws typically 50 mA and maybe up to 100 mA. Adding external loads can increase this - depending entirely on the load.

At say 100 mA average drain you'd get approximately 900/100= 9 hours operation. Running just the processor and on board components / peripherals you'd probabaly get twice times as long. By targeting low current methods (see refs ate end) you could get MUCH longer.

Most LiIon batteries are rated to charge at up to the "C" rate - ie 990 mA for a 990 mAh battery and to safely discharge at several times as much. Some manufacturers rate their batteries for lower maximum charge rates and this also can vary with the intended cell application. A "high energy" cell is liable to have lower charge and discharge rates than a "high power" cell. This relates to means of construction and to be safe the manufacturer's data sheet should be consulted.

The battery "capacity" rises somewhat as rates decrease below 'C' and fall significantly for rates above C.

Here is an excellent example data sheet for selected Sanyo LiIon cells . These are only examples but give a reasonable idea of what can be expected from a reasonable quality product.

Arduino per pin current limitations

Typical current draw](http://gadgetmakersblog.com/arduino-power-consumption/)

Excellent - Methods of reducing Arduino power consumption  & Related & more

Stack exchange discussion - How much current do you require in Arduino and embedded systems projects?


How can write a single data into spiffs?

For this kind of situation it's best to treat your data as records in a database. To change one part of a record you read the entire record, change the value, then write that record back.

int record = 4; // which record you want to change

struct book b; // Temporary storage for editing the data

// Go to the record and read it in
filename.seek(record * sizeof(struct book));
filename.read( (const uint8_t*)&b, sizeof(struct book));

// Change the data
strcpy(b.title, "Winnie The Pooh");

// Go to the record again and write it out
filename.seek(record * sizeof(struct book));
filename.write( (const uint8_t*)&b, sizeof(struct book));


Serial: What is different between Gammon's RS485 (blocking) and RS485 "non blocking" libraries?

Reference page: http://www.gammon.com.au/forum/?id=11428

The blocking library is intended where you want to wait for incoming data, and are prepared to do nothing else while it arrives. There is also a timeout parameter which lets the code proceed if nothing happens for a specified number of milliseconds.

The non-blocking library is intended for where you need to do other things (like control motors, or read switches) at the same time you are receiving data. For that situation you call an update function periodically which assembles the incoming packet, byte-by-byte if necessary.

When the data is fully received the update returns true, and you can process the packet.

  If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?

As I stated above in neither case do you receive and print "at the same time", however the non-blocking one does not simply wait until all the data has arrived.

Example code from the linked page:

void loop ()
  {
  if (myChannel.update ())  // returns true when packet fully received
    {
    Serial.write (myChannel.getData (), myChannel.getLength ());
    Serial.println ();
    }

  // do other things while waiting

  }  // end of loop

  If in example for non-blocking libraries is the same wiring as in the example of blocking library, where is (in non-blocking example) definition of RX(=2) and TX(=3) pins?

The hardware is the same.

  there is limitation for use - only pins which supports change interrupts.

Of course. If the underlying protocol is SoftwareSerial then the usual limitations apply (that is for the Rx pin).


How can I get my (Arduino) Pro Micro schematic to allow me to program it through GPIO instead of USB

Welcome to arduino.stackexchange.
You can program your ATmega32U4 on at least two ways:
1. Use Arduino's bootloader and D+/D- pins. This way you won't need an external programmer. Try search for phase "programming ATmega32U4 with bootloader".
2. Use ISP (In-System-Programming) method. In this case you can use your avr programmer. To do so you also need access to PINs named Reset, MISO, MOSI, SCLK. See this link or this one

As always, the important read is ATMega32U4 datasheet.


ATmega32U4 (Leonardo/Pro Micro) bootloader, 8K rather than 4K?

The bootloader needs a USB stack to work. It is possible to run the main sketch without a bootloader. So yes, I suppose you must have two of them. Looking at the assembler output for a blank sketch, it appears that you get the USB code in it by default. As I said, they have to assume you may not have the bootloader around, so they can't just execute the stack from the bootloader.


I just tried it (using my own method), and I got it working with very good sensitivity (should be fine for two people) using a TIP102 Darlington transistor and some resistors. Here is what I did:

R1, the 1M pulldown resistor on the first pin of the Darlington is necessary to keep the light off when nobody is touching the wires. Without this, the light will turn on and off frantically.

R2, the 1k resistor keeps the Arduino from draining too much current (since that would be bad for the pin) in the case that your A0 is in OUTPUT mode and set to LOW.

R3 keeps the LED (or in my case, an AC relay connected to an actual light) from draining too much current from the Arduino. Note: The LED leads may be backward (reverse polarity) in the provided diagram.

Here is the code:

// I release this code under the standard MIT licence;
// (in addition to whatever StackExchange implies);

const short triggerThreshold = 10;// Lower is more sensitive;

void setup() {
  pinMode(A0, INPUT);
  pinMode(A5, OUTPUT);
  digitalWrite(A5, LOW);
  delay(1);
}

void loop() {
  short value = analogRead(A0);
  digitalWrite(A5, (value > triggerThreshold) ? HIGH : LOW);
  delayMicroseconds(10000);// 10ms;
}

Note the triggerThreshold setting in the code. If you want more sensitivity, try changing the 10 to a 5. I just tried it, and it becomes extremely sensitive, yet it still appears to reliably stay off when I don't touch it. Naturally if you use large plates for touching, electrostatic in the air could set it off, so you may need to change this number to be higher to make it less sensitive, depending on your setup.


To keep the two loops more symmetrical, let the first loop go from 0 until 254: [0 .. 255) and the second loop from 255 to 1: [255 .. 0), so both iterations have 255 values each.

Also, it is quite common in programming to include the start element, and not include the end element (as in the values above: [start_element .. end_element).

Also, for the simple formula (255 - i), I would leave out the formula. And to make things more clear define constants for the min/max values (0,255) and the delay.

Than you get:

const int A = 3;
const int B = 5;

const int MIN_INTENSITY = 0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
}

void loop()
{
  for(int i = MIN_INTENSITY; i < MAX_INTENSITY ; i++)
  {
    analogWrite(A, i);
    analogWrite(B, MAX_INTENSITY - i);
    delay(DELAY_TIME);
  }

  for(int i = MAX_INTENSITY ; i > MIN_INTENSITY; i--)
  {
    analogWrite(B, MAX_INTENSITY - i);
    analogWrite(A, i);
    delay(DELAY_TIME);
  }
}

By making a function and use arguments for the variable values, and create some better names for constants and variables you get this:

const int LED_1_PIN     =   3;
const int LED_2_PIN     =   5;

const int MIN_INTENSITY =   0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup()
{
  pinMode(LED_1_PIN, OUTPUT);
  pinMode(LED_2_PIN, OUTPUT);
}

void loop()
{
  fade(MIN_INTENSITY, MAX_INTENSITY,  1);
  fade(MAX_INTENSITY, MIN_INTENSITY, -1);
}

void fade(int startIntensity, int endIntensity, int stepValue)
{
  for(int intensity = startIntensity; intensity < endIntensity; intensity += stepValue)
  {
    analogWrite(LED_1_PIN, intensity);
    analogWrite(LED_2_PIN, MAX_INTENSITY - intensity);
    delay(DELAY_TIME);
  }
}


Arduino nano digital pins not working with external power source

I think you may need to back up and start over again.

Rather than changing the power supply, you need to fix the problem that made you think you needed to change power supplies.

Following a link in a comment on the question you linked  to leads to this thread on the Arduino forums.

The suggestion there is that a particular pin on the FTDI chip on the Nano isn't connected as it should be.

To be exact, the Test pin (pin 26 on the FT232RL chip) needs to be grounded to fix the original problem you were having with communications with the Nano.

The description there fits your description.  The Nano can't talk to the PC if the Nano is connected to the PC at power on.  The same thing happens with the circuit referenced in that Arduino forum thread, but they are using another embedded system instead of a PC.

If you fix that, then you won't need to use an external 5V supply.

To back up the conclusion from the Arduino forum, here's an excerpt from page 8 (pin descriptions) of the FT232RL datasheet:

  26 TEST   Input  Puts the device into IC test mode. Must be tied to GND
  for normal operation, otherwise the device will appear to fail

You need to connect pins 25 (ground) and pin 26 (Test.)

Excerpt from the Nano schematic:

Pins 25 (ground) and 26 (Test) are right next to one another, so easy to fix.

You need to put a blob of solder on the red marked spot in this picture:


How to find if AC Appliance is on or off using ACS712 current Sensor

The code looks like it would produce rather larger values than you are seeing, if it gets correct inputs from the sensor.  For that reason, you probably should carefully check your wiring.  Also, with a DVM, measure the sensor output voltage with the light on and with it off, to verify sensor operation.  If you measure ok sensor voltages but don't get good readings, your analog input pin may have a problem; you could try other analog input pins.

Note, when debugging an issue like this, it does not make sense to run a few numbers through five levels of processing before printing anything out.  You should at least add serial prints in getVPP(), and just before returning the result, print out result, maxValue, and minValue.

Note, fix the erroneous comment “//root 2 is 0.707”; the square root of 2 is about 1.414213562, while 1/√2 = (√2)/2 is about 0.707106781.


How to connect Arduino Nano with ESP8266 and BMP180?

Connections:

[...]

Rx to Rx
Tx to Tx

That's not gonna fix your problem with initializing the BMP180, but you have to cross the lines, Rx to Tx and Tx to Rx, if you want to get anything on the serial terminal... Besides, your Nano is 5V, your ESP 3.3V. Connecting directly the Nano's Rx/Tx lines at 5V to the ESP's Rx/Tx 3.3V lines might not be very safe.

As for the BMP180, is it rated for 3.3V, or only 5V? If it is 5V only, it might not work on the ESP. Hence the init fail.


How to program an nRFL01 RF module that is connected to a pc via a USB to UART/TTL adapter?

In short: whatever software you use on the remote end (rf24.h for example) you have to re-write on the PC using whatever language you can interface to the FT2232 with. That means having intimate knowledge of:

The USB to SPI adapter you choose (NOT USB TO UART!)
The low-level control and interfacing of the nRF24L01+ chip
The exact protocol used by your chosen Arduino library.

That's a lot of understanding which (by the level of your questions) is most likely way outside your area of ability.

If you equate time to money then the cost of doing what you want to do is far higher than just using a small Arduino to act as an intelligent interface between your PC and your chosen wireless system. You can discount points 2 and 3 above since they have already been done for you by the Arduino libraries and tutorials. Point 1 becomes considerably easier since you are then just talking to an Arduino using a protocol which you yourself have come up with.

So do yourself (and us) a favour and come to your senses and just plug the nRF24L01+ into an Arduino then plug the Arduino into your PC and program the Arduino to do the RF communications according to commands and instructions you send to your sketch from the PC.


Figured it out - stupid mistake as expected. The power and ground lines on my bread board don't go all the way across. They break right in the middle, as the lines show. I moved my ground connection to the left a few slots and it worked. Thanks for working through it with me jfpoilpret!


Transmitting Electrodes Signal to Breadboard Wireless

No. Certainly not. You are thinking completely backwards.  It is necessary for the electrodes to go directly into that circuit since that circuit amplifies the tiny signals from the electrodes to make them readable.

You should instead think about shrinking your design to the stage where it becomes possible to make the Arduino be wireless and send the data somewhere else.


USB and Arduino: Power Arduino, charge LiPo, and transfer data at the same time

I'd recommend using the Arduino Leonardo as a reference for your circuit. Its pretty much the same as an Arduino UNO but has a built in USB interface so you don't need the USB-Serial converter.

I'd also recommend running the chip at 3.3V. That way you can use a linear regulator to regulate the 3.7V battery voltage down. Otherwise you'd need a boost converter to bump the voltage up to 5V which needs more parts.

If you follow those recommendations then all you will need is a LiPo charging IC to handle the charging. You'll need to add an ISCP header to flash the initial Leonardo bootloader, but after that you can use USB and the Arduino IDE to program it.

I did exactly this for a school project a while back. You can find the schematics here: https://github.com/seanwatson/ece4416-project/blob/master/hardware/rev2/sw-4416-project-v2-sch.pdf


Add the flag -hupcl to your stty command.  That will disable the assertion of DTR which is resetting the board.

 hupcl (-hupcl)
             Stop asserting modem control (do not stop asserting modem
             control) on last close.

The first time it is run there will be a reset, since setting that flag entails opening the port, which causes a reset.  So you need to add a delay long enough to get past the bootloader - minimum 2 seconds, best make it 3.

You can do that with the sleep command: sleep 3

Note that you now won't be able to upload a new sketch since you have disabled the auto-reset feature that allows you to enter the bootloader, so before uploading a new sketch you need to turn the reset back on with

stty -F $tty hupcl

If you don't disable the reset then every operation in your script that opens and then closes the serial port will trigger a reset of the board.  So in summary try this:

#!/bin/bash
tty=/dev/ttyUSB0
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts -hupcl
sleep 3
echo temp >$tty
read reply <$tty
echo "$reply"
stty -F $tty hupcl


Where are the implementations of the SdFat BlockDriver methods?

The typedef in BlockDriver.h is only for pointer type, not for instance of the object. The object is always of type SdSpiCard, but in one case it is not an implementation of BlockDriverBase, so the function parameters can't refer it by base type.

#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
class SdSpiCard : public BaseBlockDriver {
#else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
class SdSpiCard {

use of BlockDriver typedef

class FatFileSystem : public  FatVolume {
 public:
  bool begin(BlockDriver* blockDev, uint8_t part = 0) {

I was curious why the version without BaseBlockDriver. I asked the author Bill Greiman and he answered:

  This is due to history. Long ago using a virtual base class cost lots
  of RAM and flash so I did this mainly for 328 boards


How to convert uint8 to int for maths operation in Arduino?

I am receiving a string from my bluetooth terminal in uint8 format. I want to convert it to integer for further processing. How can I do this? I tried toInt() but it is not working. Please help.

I am assuming that you are receiving to an uint8_t buffer and that it is correctly null terminated (i.e. zero as the last element).

Try this:

uint8_t buffer[BUFFER_MAX];
...
int num = atoi((const char*) buffer);

Cheers!


Which timer does Arduino Nano use for each PWM pin?

This is a good pinmapping picture of the Nano : www.pighixxx.com/test/portfolio-items/nano/

A timer has sometimes two outputs, A and B. The pins with OC0A and OC0B are timer outputs of Timer0. OC1A and OC1B are Timer1, OC2 and OC2B are Timer2.

Everything is also in the datasheet of the ATmega328P, but that picture is a lot easier.


Explanation of the formula of the map funtion

map() implements linear interpolation.

  In mathematics, linear interpolation is a method of curve fitting using linear polynomials to construct new data points within the range of a discrete set of known data points.


Timer Countdown to control relay (multiple functions in void loop)

I think what you're looking for is to declare your functions near the top of your file, usually before the first function you write, setup(), in this case. So add this just above your setup() function:

// Forward function declarations
void displayNumber(void);
void checkUp(void);
void checkDown(void);
void checkStart(void);
void countDown(void);

C compilers (and thus, C++ because it was derived from C) read the source code only once through, so any function must become known to the compiler ahead of where it is first called. This would require you to place all low-level functions first, then all functions that call those, then the functions that call those, ..., etc. And there are some cases that even this arrangement won't solve, e.g., functions that call each other (oww, my brain hurts!!). So function declarations are used to avoid this inconvenience.

Declaring a function just means informing the compiler of its name, the parameter types, and the return type -- the actual function code isn't required at this point.


How to monitor state of 50 Digital Inputs

I had a project that used 16 rotary encoders and I used the MUX Shield which uses 74HC4067 analog multiplexers. They port to A0 - A3 on the shield which is fine as you can set these pins to Digital Inputs else you can get teh breakout version and connect to any input pins.
I also used a Due since ALL pins can be interrupt enabled.
Reading was a bit of a pain but worked like this...
The method is.. Continually address each input in turn in the loop or an interrupt is not detected, when an interrupt fires, address each input in turn again to find out which pin changed state.
Hope that helps.


Preventing relay switch-off crashing Ethernet controller

I would suggest two things:

Use opto-isolators instead of (or as well as) the MOSFETs to control the relays, and
Add RC snubber circuits across the contacts.

The latter is the most important, since the spark across the contacts when they open will cause massive amounts of EMI.

The simplest circuit is a simple series resistor and capacitor placed across the contacts:

simulate this circuit – Schematic created using CircuitLab

Of course, ensure that the resistor and capacitor are rated for at least the voltage you are switching, preferably double.

Selecting the right values for the components depends very much on the load being switched and how much energy needs to be absorbed. I have shown ball-park figures that are usually "ok" for many situations.


How to Set the Control Register on the DS3231 RTC module for Arduino UNO R3?

I took a look at the FabioCuomo-DS3231 library, as I
guess that is what you are using, and I saw nothing related to setting
those two bits. However, you can take inspiration from the code in the
library to implement the functionality yourself.

I would try this:

void enableAlarmInLowPower(void) {
    // Read the control register.
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.write(DS3231_CONTROL);
    Wire.endTransmission();
    Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1);
    uint8_t value = Wire.read();
    Wire.endTransmission();

    // Update it.
    value |= bit(6) | bit(7);  // set bits 6 and 7

    // Write it back.
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.write(DS3231_CONTROL);
    Wire.write(value);
    Wire.endTransmission();
}

Warning: not tested.


Using timer2's ISR instead of timer1's in Arduino wiring.c breaks Serial object

Now everything works except for delay()

delay() uses micros() and micros() reads the hardware registers, like this:

unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT0)
    t = TCNT0;
#elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
    if ((TIFR0 & _BV(TOV0)) && (t < 255))
        m++;
#else
    if ((TIFR & _BV(TOV0)) && (t < 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

You would need to change all those references (TCNT0, TIFR0, TOV0 etc.) to use the Timer 2 equivalents.


Included files are included before compilation, really replacing the #include with the content of the file.

If you write int DebugX = 1; you define a variable. And it is defined in every source file which includes it. Then the linker finds it in more then one unit and ends with "multiple definitions" error.

The variable must be defined only in one compilation unit (.c, .cpp). For example in your case customFunctions.cpp. To make it available in other source files put extern int DebugX; into the .h file.


If you mean the variable stop1, it's true every loop it's set to 1.

If you don't want this, make it global, set it in setup (and change in loop when needed).

E.g.

int stop1 = 0;

void setup()
{
    stop1 = 1;
}

void loop()
{
    // Use stop and/or change it
}


I answer my own question in case someone has the same issue.
The ADAFRUIT_DHT lib DOESN'T WORK WITH ESP8266. It keep saying Failed to read from DHT sensor! until you unplug/plug the VCC on the DHT.

But the DHTesp (link) works very well at first try !

Thx @Juraj and @Jot for their support.


From: http://forum.arduino.cc/index.php?topic=6549.0

The documentation states that 13 cycles are neccesary for ADC conversion. Thus, using the clk/13*8 divisor configuration, and 16 MHz system clock, the upper bound becomes 154KHz

The forum post in the above link continues to say that "ADC clock frequencies above 1MHz are uncharacterised", however this was quoting another document for which the link is dead. I could not find this statement in the most recent documentation.

Edit: Another forum post where a user successfully used an atmega328p to achieve 360000 samples/sec, so it is technically possible:
http://forum.arduino.cc/index.php?topic=8795.0


How can I make std::cout write to Serial?

The ARM gcc libraries offer a simple way to redirect standard outputs. It is enough to implement function _write(int fd, char *ptr, int len) and it will replace the default implementation used in library to direct the standard outputs to debugger semihosting. The function must be compiled as  C to match.

#include <Arduino.h>
#undef max
#undef min
#include <stdio.h>
#include <iostream>

using namespace std;

extern "C" {
int _write(int fd, char *ptr, int len) {
  (void) fd;
  return Serial.write(ptr, len);
}
}

void setup() {

  Serial.begin(115200);
  while (!Serial);

  Serial.println("START");

  printf("HERE WE ARE\r\n");

  cout << "TEST COUT\r\n";
  cerr << "TEST ERR\r\n";
}

void loop() {

}

the #undefs undefine the Arduino macros, which are in conflict with includes used in <iostream>


Atmel studio 7 vs Arduino IDE for register level coding?

I actually wouldn’t recommend either for professionally developing for Atmel chips. Although Atmel Studio is a nice enough IDE (the simulator is amazing!), it does make it very difficult to unit test your code or to set up a build server. I would personally recommend you set up a Make (or possibly CMake) based setup directly on top of the avr-gcc tool chain and then simply use the text editor of your choice.

As for learning about programming against raw registers, I have to recommend Atmel Studio and one of their XPlained evaluation boards. Atmel Studio includes a simulator that actually shows you, bit by bit, the current state of the registers.


Multiple I2C slave devices on Arduino - Pull-up values

You should consider adding some bus isolation between each slave and the master. The reason being is that the ESD diodes in the SCL/SDA pins of a slave that is powered down could be interfering with the I2C bus as they leech power from the bus to feed through the internals of the slave.  Given the low current imposed by the pullup resistors being the only power source this shouldn't cause any damage to the slave, but it may well cause the I2C bus to be seen as LOW when it shouldn't, causing communication to fail.

You should add a buffer with an "enable" pin of its own between each slave and the bus.  My device of choice is the PCA9306 from Texas Instruments.  It also means that the slave has its own separate pullup resistors powered by its own 3.3V rail, keeping all the power separate.

You would then have sequences such as:

Power up slave
Give short powerup delay (if needed)
Enable PCA9306
Do I2C transactions
Disable PCA9306
Power off slave

The PCA9306 can also be used to connect 3.3V slaves to a 5V MCU if needed.

simulate this circuit – Schematic created using CircuitLab


Parallel connection to Wiegand 26bit RFID readers

It looks to me like the Wiegand interface is an open-collector interface (like I2C), which is why they can be wired in parallel like that.

As long as the Arduino has both connections set to INPUT (not INPUT_PULLUP and certainly NOT OUTPUT) it shouldn't interfere at all.

By the way, for Wiegand, the two signals are DATA0 and DATA1.  To transmit a 0 the DATA0 line is pulled low. To transmit a 1 the DATA1 line is pulled low.

You should also check that the idle voltage on the lines is indeed 5V as it should be.  Anything more than that could cause the Arduino to chip the voltage to 5V through its internal ESD protection diodes.

Also you must ensure that the Arduino has its ground pin connected to the ground connection of the Wiegand system (which it should be since you are powering it from that).


How to add prefactor to clock frequency at compile time?

1 and 3 can be solved by putting it in one of the initialization sections. 2 can be solved by creating and using a board.txt entry with the appropriate FCPU.

#include <avr/power.h>

void __attribute__((naked, section(".init1"))) preprescale(void)
{
  clock_prescale_set(clock_div_2);
}


Send signal to vibrate a Restaurant buzzer via web based app to a PC

You need a webserver, a defined interface for the client to connect to and a buzzer you can make some noise with.

Because you want to do it over WIFI, an Arduino is probably not the best choice.  As 'Look Alterno' says you might be better with an ESP8266 based device, because that has inbuilt WIFI.  I would suggest a Wemos D1, its an ESP8266 12 with a power supply and 2.54 pitch connectors, which means its easy to use with things.

Now you can program an ESP8266 using LUA, but I really wouldn't try that. Also if you do that you won't get any help on this forum.  Use the Arduino IDE and program it in the same language as an Arduino (You will need to download support for the ESP via the Board Manager in the IDE).  There is an example called "Advanced Web Server", done by Majenko on here, that will suit your needs.  You just need to change the root handler to activate the buzzer for n seconds and then return HTTP code 200.

Then your client just needs to connect to the root page of the webserver and the buzzer will sound.  You don't say how many clients will use this, but this will allow 5 simultaneous clients, if you need more that can be achieved easily.

You can then expand this to identify which client sounded the buzzer.

As to keeping it local, use the firewall on your router.


How to use BlueTooth on mobile device to find AccessPt and enter PW for ESP8266 WiFi on an Arduino controller?

Don't overcomplicate things by adding bluetooth.

If you want to set the WiFi credentials at run time, use the WiFi Manager library. It's exactly what it was designed for.


A shift register is an output device. You won't be able to "Read" 7 push buttons in this way.

A shift register like that is for taking a "series" of bits on one wire and parallelizing them onto 8 wires.

It does not work in reverse. The reverse is called a multiplexer.


It sounds like what you want isn't really "binary", nor the bit-to-characters expansion of the touch readings.

Rather it sounds like what you want to do is to print the character '0' or '1' for the state of each button.  You already have the decisioning code for your outputs, so you can simply extend it for the serial prints:

if(sensor1 >= 1000) {
   digitalWrite(3,HIGH);
   Serial.print("1");
} else{
   digitalWrite(3,LOW);
   Serial.print("0");
}

and so on, with the next set having tabs and the last a newline.

Worth noting, intermixing the printing and digital outputs will put some time delay between the outputs (potentially quite a bit if the evaluation gets ahead of the serial buffers), so another option could to do all the outputs and then all the prints, or store the decisions in a bit mask for later printins, etc.


Duemilanove serial TX/RX: which is what?

I will not be using SoftwareSerial

That means you'll use the standard Serial() library.

  Do I have to[...] declare it?

Not if you use the standard Serial.begin() instruction. The Duemilanove uses pins 0/1 automatically for TX/RX

  Do I have to know which is TX and which RX?

Kinda... you have to know which one is which so you wire it correctly. The TX of the board should go to the RX of the GSM shield, and vice versa. Pin 0 is RX and 1 is TX.


Firstly, let's look into documentation for Ruby IO#gets:

  Reads the next "line" from the I/O stream; lines are separated by sep ...

Secondly, look into documentation for Arduino Serial.print:

  Prints data to the serial port as human-readable ASCII text ...

Finally, you don't print new line char \n in your "arduino sketch" above.

I recommend you to use Serial.println in the last line from your sketch:

void setup() {
  Serial.begin(9600);
  // ... do some gyro stuff here
}

void loop() {
  gyro.read();

  Serial.print((int)gyro.g.x);
  Serial.print(" ");
  Serial.print((int)gyro.g.y);
  Serial.print(" ");
  Serial.println((int)gyro.g.z);

  delay(500);
}


In theory, any compiler which outputs AVR assembly could be used (modulo limitations on code size, ram usage etc).

AVR backends exist for both LLVM and  GCC -- so in theory, with some effort, most languages which are supported by LLVM and GCC's front-ends could be compiled to AVR. A big question will be library support, etc.

Never the less, here's a couple of odd choices for the spirit of the question, rather than its letter [1].

AMForth, a forth dialect can be flashed onto an Arduino.
AVR-Ada: Ada for AVR micro-controllers.
BASIC: Bring back the Goto!

Oh, and you could write raw AVR Assembly!

[1]- I Haven't tried these though!


Turn on relay for amount of time by continuous input

I would suggest having a buzzerPlaying state, an oldInput state, and a buzzerOffTime (unsigned long millis when you should turn the buzzer off.
Ignore input if buzzerPlaying == true and just check the buzzerOffTime. When buzzerOffTime passes, turn off the buzzer, set buzzerPlaying to false, and start checking the input again.
If the buzzerPlaying == false and input is high:

check buzzerPlaying. If it's true, do nothing.

If buzzerPlaying is false, check oldInput. If oldInput is high, do nothing (The input has not been reset.) else set buzzerPlaying to true, set oldInput to high, turn on the buzzer, and calculate buzzerOffTime.

If the buzzerPlaying == false and input is low, set oldInput to low (Once the buzzer has stopped playing and the input has dropped low, start looking for more inputs.)


Logging multiple gigabytes of data with Arduino

I'm not sure where you have the impression it won't work. I haven't used 64GB cards, but have used 32GB cards and they work fine in terms of FAT32 and writing files.

As you have already worked out, reading or searching the file system can get very slow as size increases.

That said, I have found that larger capacity cards are more likely to have problems with the SPI interface being poor quality. Consumer devices do not use the SPI interface, and it seems that some manufacturers are willing to skimp on this side of it. The SPI interface can be buggy or unstable as a result. Genuine name-brand cards should work fine though.


Loop one specific case inside of a switch

You need to split your cases into multiple parts.

For example, you have a case which sets up a mode, and a case that runs a mode, and if needed a case that finishes a mode.

For example:

switch (mode) {
    case 0: // Idle
        break;
    case 1: // Start - do whatever to set up the mode here
        redValue = 100;
        greenvalue = 200;
        mode = 2; // Switch to the next case
        break;
    case 2: // Run - this is the bit that repeats
        if (digitalRead(3) == HIGH) {
            mode = 3; // Finish it
        }
        // Do whatever for each loop here.
        break;
    case 3: // It is finished.
        redValue = 0;
        greenValue = 0;
        // etc.
        mode = 0; // Or whatever you want to do next
        break;
}

The key thing here is that case 1 is equivalent to a mini setup() and case 2 is equivalent to a mini loop(). You switch to case 1, which does the setup, and that case then switches to case 2, which it stays at until you tell it otherwise. That case will keep getting executed until you tell it to move to another case.


Concerning your questions about clock division settings: have a look at this pretty tool, it gives you a avrdude query for setting fuses (take care!). The CKDIV8 bit of the low fuse is set by default, so an AT328p will run at 1MHz, clearing this bit will result in 8 MHz.

When flashing you should never override any checks as this may damage/lock your chip.

I see that avrdudes states the supply voltage to be 0.3 volts which is far to low for communication. Any received bits would be low level and therefore any information read will be 0. ISPs usually provide a supply voltage which often can be selected by switches on the programmer. If you are sure your programmer is allright, check your circuit in general.

Btw, which ISP-model do you use?
Is your mcu assembled on a custom pcb (setup?)? If yes, do you have an arduino(like) board to verify this behaviour?


How do I power a linear actuator at different speeds for specified periods of time

You can do this easily by using Arduino built-in PWM function and using delay function. But remember that using delay in your code will block your code so if your program just want to sit and wait for 3 seconds at some speed then delay is ok for you else you need to implement Millis function.
first you need to define different speeds as per your requirement remember PWM function has value from 0-255 where 0 in min speed and 255 is top speed.
So here I will define speed1 for top speed and speed2 for low speed
So now your program will look like this
int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 255; // Top speed you can change it between [0-255]
int speed2 = 150; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(LPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(LPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
   // analogWrite(LPWM,0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(RPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(RPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
    // analogWrite(RPWM,0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
  }
}


Do we need to burn bootloader in new Atmega328p before uploading the arduino code

Tools > Burn Bootloader in the Arduino IDE does two things:

Set fuses according to the settings in boards.txt for the Tools > Board selection
Install the bootloader.

The latter is pointless since when you do an Upload Using Programmer the bootloader will be overwritten but the former is very important to do the first time you use a new chip(or anytime you want to change the fuses) to be sure that the correct fuses are set, which likely will be different from the default settings of the chip when you get it. Upload Using Programmer does not set fuses, the only way to do this via the Arduino IDE is Tools > Burn Bootloader.

So yes, you should Burn Bootloader.


The datasheet of the ATmega328P (the main chip of the Uno) states:

  The ADC is optimized for analog signals with an output impedance of
  approximately 10 kΩ or less.

The Thevenin equivalent output impedance of most taps of
your voltage ladder is higher than 10 kΩ. You 1 MΩ pulldown is
way beyond that limit. Cross talk from previously read channels is
exactly the symptom you expect from excess output impedance.

Taking each reading multiple times, until the value stabilizes, should
help. A buffer (e.g. an OP-amp set as a unit gain amplifier) is the
usual solution to this kind of impedance problems.

  Actually, the whole works perfectly with R as 220 and pull downs as
  10K. The problem comes when connecting more than 3 strings at the same
  time, on any tap, as the pull down resistors become part of the
  ladder (i belive).

The pull down resistors will indeed have an effect on the potentials of
the voltage ladder, especially if you connect several strings. This
could be minimized by having the pull-downs be a lot more resistive
than the resistors along the ladder, but then you would need very low
resistances along the ladder, which is not desirable because of current
consumption and heating.

Here is an idea for an alternative solution: If you can spare 6 digital
pins, you could build for each analog input a pull-down circuit that is
switchable between a “strong pull” mode and a “weak pull” mode. Assuming
D0 is the “pull strength control” pin for A0, it would look like this:

A0 ---+--- 1 kΩ --- D0
      |
     1 MΩ
      |
     GND

Whenever you want to read A0, you:

set D0 to OUTPUT LOW, which creates a strong pull-down to ground
take a couple of analogRead()s
set D0 as INPUT, which leaves only the weak 1 MΩ pull down
take a couple of analogRead()s, keep the last one.

If A0 is not connected to the ladder, then the first reads will
discharge the internal sampling capacitor of the ADC. The final read is
done with only a weak pull-down, but this should be OK since the
capacitor has already been discharged.

The potentials along the voltage ladder will be disturbed by any string
connecting a tap to its strong pull-down, but this disturbance will
disappear when you switch to weak pull-down, so it will not affect the
readings.


Solution from the original poster :

Hello everyone, I did a test in another laptop and it worked. I didn't know what happened with my laptop . Look this new image I needed to change the number Serial.begin to 9600. Now everything is working. Thanks for your help and have a nice week.


Try to connect "Pin RX on Mega to Pin RX on Shield" an "Pin TX on Mega to Pin TX on Shield":

Pin 50 (Rx)  on Mega <==> Pin 2 GSM Rx on Shield
Pin 51 (Tx)  on Mega <==> Pin 3 GSM Tx on Shield

I use an Geeetech Shield with a Mega 2560 and connect RX to Rx and TX to TX. Works fine.

Another solution is to use Serial1 instead of using SoftwareSerial ...

First connect:

Pin 19 (Rx1)  on Mega <==> Pin 2 GSM Rx on Shield
Pin 18 (Tx1)  on
Mega <==> Pin 3 GSM Tx on Shield

    //Serial Relay
    unsigned char buffer[64];  // buffer array for data receive over serial port
    int count=0;               // counter for buffer array

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

void loop()
{
  if (Serial1.available())
  {
    while(Serial1.available())
    {
      buffer[count++]=Serial1.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);
    clearBufferArray();
    count = 0;
  }
  if (Serial.available())
    Serial1.write(Serial.read());
}

void clearBufferArray()
{
  for (int i=0; i<count;i++)
  {
    buffer[i]=NULL;
  }
}

You can use a Arduino IDE's Serial Monitor, Serial Terminals(sscom32) or Bray++ Terminal to send AT commands to the Shield, communicate with it.

I hope this information is helpful.


Arduino Uno unable to detect usb port on Mac OS Sierra 10.12.5

I installed the CH340 Driver and the board now shows the USB serial as port option: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver


Changed my SIM card to Ting from Hologram and it worked just fine!


Is it dangerous to connect two output pins together?

You can connect but requires resistor between two pins to limit the current.


The HG-C1100 has a resolution of 70 μm (= 0.07 mm) over a measuring range of 70 mm.
You quote errors of 0.28 and 0.38 mm, which is worse than can be expected (±0,07 mm).
The resolution is 1‰ of the measuring range. Therefore the 10 bits range (1024) of the Arduino's Analog-Digital Converter (ADC) is sufficient.
You map the ADC output of 0-1023 to a range of -3500 to +3500 which results in a value in 0,01 mm. Then you divide by 100.0 resulting in a value in mm.
According to Arduino's Reference the function map() uses integer arithmetic, but the arguments are longs and the calculation order is such that maximal accuracy is maintained. This provides sufficient accuracy for this purpose. I am only not sure if you constants should be post fixed wit an "L".
So far everything looks all right.
The errors you mention correspond to about 5 counts of the ADC.
I assume the solution lies in taking measures to prevent noise entering your signals (signal conditioning).
Addition:
When you read the same sensor repeatedly do you get stable readings? You could try to use an average over multiple readings. Did you look at the signal(s) with an oscilloscope?


The article is saying that the circuit wouldn't work, thus it illustrates (correctly) something that won't work. What is the confusion?

To turn the PNP transistor off, the base voltage needs to be low with reference to the emitter voltage. Thus with an emitter voltage of 12V, and the most the Arduino can output is 5V, the transistor will never be off.


Sending MIDI CC to multiple midi Channel

A single CC message applies to a single channel. If you want to affect multiple channels, you have to send multiple messages:

usbMIDI.sendControlChange(controllerAx, nx, 0);
usbMIDI.sendControlChange(controllerAx, nx, 1);
usbMIDI.sendControlChange(controllerAx, nx, 2);
usbMIDI.sendControlChange(controllerAx, nx, 3);
...

And this should of course be done in a loop:

for (int c = 0; c < 16; c++)
    if (c != 10)
        usbMIDI.sendControlChange(controllerAx, nx, c);


Problem with a DHT11 Temperature & Humidity sensor

Finally I was able to solve the problem by not using the resistor and connecting it directly, I also had a problem with the sensor pins since some were badly connected, but it was also solved. Now both sensors are working well including the melted one. Thanks!.


Apparently the library in the OP's link has been updated to support the Leonardo, so this problem should now be solved.


Read information from Twitch's API and execute actions depending on the output

Break your problem into small steps and try to identify the success criteria for each step. So you might:

Try to set up the Ethernet shield and get it to respond to a ping on your local network.
Try to connect to a site outside of your network.
See if you can find some examples of using the Twitch API.
Try to replicate one of the simple examples.
See if you can get the Stream object that you want.
See if you can read the value of the object.

If you have a plan and try to follow it you'll be able to tell us what you've been doing and where you got stuck / confused. That is likely to get you better answers – both because we can be more specific and also because we can see that you're "carrying your weight" as we work on the problem.


How many Infrared sensor modules can be added to a single Arduino (eg;Uno)

You just want to know how many you can attach to an Arduino board or how many Arduino Uno boards you need, but it does not work like that.

Some sensors with a led require 5mA or 10mA or 20mA. The reflective optical sensors use a IR (InfraRed) led. The Arduino Uno 5V pin can probably not supply enough current for 40 leds. Therefor you might need a seperate power supply.
I think the TCRT5000 is typically set at 10mA.

The Arduino Mega 2560 and the Arduino Due have many pins. But with 40 TCRT5000 sensors, the total current is too close to the limit.

In such situation often extra hardware is added. You can use one Arduino Uno board, with extra hardware for multiple inputs or outputs.

An "expander" is a chip or a module that connects to the Arduino with a few wires, but has many input and/or output pins. For example a "expander" with I2C interface to the Arduino Uno as mentioned by @matsk. Although a I2C expander has a slow I2C interface, they are sometimes smart and can tell which pin has changed by reading a single byte.

"Shift registers" are chips with for example 8 input pins or 8 output pins. The data of the pins is shifted into the chip with a data and clock signal. There are many examples for that: ShiftOut with a 74HC595.

A analog "multiplexer" or "mux" is a chip that can connect one common pin to one of 8 pins. The signal can go both ways. Nick Gammon about a multiplexer.

A "ADC" is short for "Analog to Digital Converter". The Arduino Uno has an internal ADC, but also a external ADC can be used. They have often more than one analog input.

"Polling" is when an Arduino is reading many inputs continuously one by one. If for example it takes 5ms to read a sensor, then 40 sensors take 200ms. That means that every sensor is read once per 200ms. If a train would pass within that 200ms, then it might be not detected.
The opposite of polling is with interrupts. If an external event happens, it could trigger an interrupt and the Arduino can react right then at that very moment. However, 40 interrupts is not possible.

Conclusion:
The best way depends on your hardware and software skills, on the maximum interval that you want to read the sensors, on the sensors themself, and how far apart the sensors are, and if you want 40 wires to a Arduino board.
The best Arduino board also depends on what you want to do with the data and what else the Arduino has to do.
Some sensors have a analog output and some a digital output. It depends on your situation and the way the train is detected.
If possible, then I would choose a solution where all the hardware can be easily be replaced. If the sensor has digital outputs, then I would connect them to a Arduino Mega 2560 or Arduino Due.


Why am I receiving random input values in my Arduino?

You're getting noise pickup on the input pin when the button is not pressed. You need a pull-down resistor, about 10 kΩ to ground, to quiet the noise when the switch is open.
Or even easier, use the built-in pull-up resistor in the Arduino, which is ~10 kΩ to +5 V, wire your button to ground instead of +5 V, and reverse the if tests to test for logic LOW instead of HIGH, to detect a button press. You'd change your pinmode statement to:
pinMode(switchPin, INPUT_PULLUP);  // engage the input pullup

and your test to:
 if (digitalRead(switchPin) == LOW ){ // Negative logic

No additional (external) hardware is needed!


How do I erase the memory of the Arduino Uno?

When booted, the Arduino will run whatever program was put on it last. Solution: Don't turn it on if you don't want it to run.

When out of the box, the Arduino usually runs the Blink program. So you can just load that and call it a day if you want to "reset" it.

Or have a loop program with a sleep command.

If you've been messing with the USB bootloader via the icsp pins, this isn't enough though, you'll need to reinstall the bootloader. But if you've been uploading programs via usb or directly using a programmer, there is no issue with uploading Blink or some other dummy program to reset it.


Why does my 16x2 LCD displays weird letters and can't insert key from keypad?

In your changealarm() function, you call atoi(buffer), and buffer is defined as char buffer[2].

atoi() expects a c-style string, which is null-terminated, and you have to include space for the null termination character ('\0', 0, 0x00, etc.), but you write to both allocated spaces in the changealarm() function. If your 2nd byte of each EEPROM space (1, 3, 5) is non-zero, then your have an unterminated string.

atoi() expects a null-terminated string, and so the behavior is unexpected. Probably atoi() is running into other memory. If the string being sent is not representable by a int type, then the behavior of atoi() is undefined.

A quick fix would be to increase the size of buffer and guarantee null termination:

char buffer[3];  // Make the buffer 3 bytes long
[...]
void changealarm() {
  buffer[2]=0;   // Set the 3rd byte to zero to null-terminate

  buffer[0]=EEPROM.read(0);
  buffer[1]=EEPROM.read(1);
  h = atoi(buffer);
  buffer[0]=EEPROM.read(2);
  buffer[1]=EEPROM.read(3);
  m = atoi(buffer);
  buffer[0]=EEPROM.read(4);
  buffer[1]=EEPROM.read(5);
  s = atoi(buffer);
}


Communication between Arduino and python: serial port sending empty data

There can be different reasons for your issue. But from the update you added later, we can at least say that your Arduino sometimes doesn't receive the character "1". And when that happens, your Python gets stuck in the infinite loop of trying to read something from the serial port.

As your Arduino responds with "1" when it receives "1", you can base your application on that i.e. if Arduino doesn't respond with "1", keep sending "1".

I wrote a sample program based on your code. I removed the "Wire" part in the Arduino code as I don't have your sensor. I would urge you to test with this Arduino code to make sure that Your sensor is not blocking your Arduino. Wire read can be blocked forever depending on the IC you are trying to read (and if you don't have a timeout).

int16_t AcX,AcY,AcZ;
unsigned long time;
bool allow = false;

void setup()
{
  Serial.begin(19200);
}

void loop()
{
  if (allow) //if allow == true, read data
  {
    for(int i = 0; i < 10; i++)
    {
      AcX = 1;
      AcY = 2;
      AcZ = 3;

      time = millis();
      Serial.print(time); Serial.print(",");
      Serial.print(AcX);  Serial.print(",");
      Serial.print(AcY);  Serial.print(",");
      Serial.println(AcZ);
    }
    Serial.println('0');
    allow = false;
  }
}

void serialEvent()
{
  while (Serial.available()) //wait for command
  {
    int incom = Serial.read() - '0';
    Serial.println(incom);
    if (incom == 0)          //if 0 - stop
    {
      allow = false;
      delay(100);
    }
    if (incom == 1)          //if 1 - read data
    {
      allow = true;
      delay(100);
    }
  }
}

In the Python code, I checked if I received "1" from Arduino. If not I kept trying.

import serial
import time

def sensors():
    # Clear receive buffer
    arduino_port_sensor.reset_input_buffer()

    while True:
        # Send command to arduino to send data
        arduino_port_sensor.write('1'.encode())

        # As arduino send LF and CR at the end, let's strip those from the end
        response = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

        # Arduino should respond with the cmd that it received,
        # if not, send cmd again
        if response == '1':
            # Arduino acknowledged
            break
        else:
            print('Did not receive 1. Retrying...')

    main_array = []

    while True:
        values = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

        if values == '':
            print('!!!!')
            # This should never happen, but if it does happen, try to read again
            continue
        elif values == '0':
            # print(main_array)
            # We are done receiveing packets
            break
        else:
            # We are still receiving packets
            main_array.append(values)

arduino_port_sensor = serial.Serial('COM50', 19200, timeout=3)

# Let PySerial get ready
time.sleep(3)

while True:
    sensors()
    time.sleep(1)


Creating Sine wave with DAC and feeding it back

I ran your code unmodified and plugged in an oscilloscope to look at DAC0 (looks an OK sine wave) and A0 (looks flatline). Hope this helps.


Arduino Pro mini is based on Atmega328 which does not have a unique ID. It has only device signature which you can read if you turn on Show verbose output during upload in Arduino IDE's File > Preferences.


What is the best data type to be used through i2C

I2C works with fixed size byte arrays.

Single bytes for commands should be sufficient. For positions you might need int16_t or even bigger numbers. Unsigned positions relative to (above) zero might make things easier, eventually (?)

As you have the same architecture on both sides, mapping of byte arrays to bigger numbers via union will work well.


How to control a DRV8266 motor controller with an ESP8266?

No, since it uses AVR defines. Convert the code that uses these defines to the equivalent ESP8266 code instead.


The arduino can't seem to output correctly

I cannot check it, but I guess you have to change the or commands like:

if control == "W" or "w":

Change to

if ((control == 'W') or (control == 'w'))

And similar for the other if statements.

Also, you can do not need to check for control == 0, since it will not be a character otherwise.

Besides that, the elif (else if) construct is normally used in Python, so instead of:

if control != 0:
    if control == "W" or "w":
        MotorRight.write(1)
        MotorLeft.write(1)
        time.sleep(1)
        MotorRight.write(0)
        MotorLeft.write(0)

    if control == "A" or "a":
        MotorLeft.write(1)
        time.sleep(1)
        MotorLeft.write(0)

    if control == "D" or "d":
        MotorRight.write(1)
        time.sleep(1)
        MotorRight.write(0)

    else:
        print("Invalid Commmand")

You can write:

if ((control == 'W') or (control == 'w')):
    MotorRight.write(1)
    MotorLeft.write(1)
    time.sleep(1)
    MotorRight.write(0)
    MotorLeft.write(0)

elif ((control == 'A') or (control == 'a')):
    MotorLeft.write(1)
    time.sleep(1)
    MotorLeft.write(0)

elif ((control == 'D') or (control == 'd')):
    MotorRight.write(1)
    time.sleep(1)
    MotorRight.write(0)

else:
    print("Invalid Commmand")

Also, you can combine the or in a list (but I cannot check it, no python compiler at hand), e.g.

if (control in ['W', 'w']):