Which pins of an Arduino UNO can be used as Tx and Rx pins for connecting to GSM GPRS SIM 900A

The best choice for serial communications is obviously the HardwareSerial object, Serial, on pins 0 & 1.  However, it is really dedicated to the USB connection (via the onboard Serial-to-USB adapter).  There are ways to connect other devices to these pins, but it is an advanced topic, and should not be attempted by beginners.

The second best choice would be pins 8 & 9, because AltSoftSerial requires those pins.  It is very efficient and reliable.

After that, any other pins can be used with one of these two software serial libraries:

NeoSWSerial is less efficient than AltSoftSerial, but much more efficient than SoftwareSerial.  It only supports baud rates 9600, 19200 and 38400, but it does support simultaneous TX and RX.  I maintain this library.

If you must use a different baud rate, SoftwareSerial is the last choice.  It blocks interrupts for long periods of time and can interfere with other libraries.  It cannot transmit and receive at the same time.


Arduino keypad and RF 433MHz transmitter problem

The problem is you send a character of type char, thus exactly one byte.
However, when you send it you have to give the length and you use strlen. However, msg is an array (at least that is what you want), but that array contains only the character to sent. What you want is to send only 1 character, so use 1 instead of strlen.

Also, you can get rid of the special msg pointer and instead of

  const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
  driver.send((uint8_t *)msg, strlen(msg

use

  driver.send(&key, 1);

Where &key defines the address (pointer to) key, and since there is always exactly 1 byte in key (the key itself), 1 can be used. To be more safe, you can use sizeof(key) thus

  driver.send(&key, sizeof(key));

What you also can do is create a string that ends with \0, so the first is the character to send, and strlen can be used, but the easiest way is to set the length to exactly 1.

Actually, using strlen on a string that does not end with \0 can result in strange behavior, because maybe there is no \0 in memory.


Although I am still figuring things out, but i hope the following things help:

http://www.solar4rschools.org/sites/default/files/robotic-sunflower-lesson4-handout4.pdf

The problem, as far as I think is that the enable pins are the ones which are supposed to help you control the speed. Please connect them to the PWM ports on your Arduino/any other device you may be using for your project.

Or, you can simply write a code which keeps on disabling and enabling the enable pins to get the desired speed (that's what PWM is supposed to do but you can try it this way, at least).


Windows 10 does not recognize Arduino Leonardo

Sounds like you've bricked it.  Your broken sketch (wrong MCU selected) means that it's not presenting a CDC/ACM port.

Your best bet is to use a hardware programmer (eg USBASP or another Arduino) to erase the chip and reload the bootloader.


Can Arduino Leonardo use USB port and RX TX serial pins at the same time?

32u4 is multi-serial uC. USB connection works on default serial communication which can be used via Serial.print("somevalue"). On the other hand if you want to use RX/TX on pins 0, 1 which are actually RXD1 and TXD1. So, if you use Serial1.print("somevalue"). So the answer is a yes. You can use USB and RX/TX (hardware serial) at the same time.


Arduino hangs after less than a minute, but not on USB

The problem is that when you are using the external 9V power supply, you are relying on the Arduino's on-board regulator to provide the 5V power supply to both the Arduino and the Ethernet shield. This regulator has very limited current capacity — much less than the 500 mA that's available from a PC's USB port — and you're overloading it.

To avoid this problem, you should use a 5V plug pack with a USB connector to power your system.


Arduino Due & Spec gas sensor - how to choose specific information from a stream of incoming bytes to store

Since the length of each data varies, you should extract data using spererator like comma in the stream.

First, get one data line from sensor. Read the string until the "Line feed(LF)" character or "Carriage Return(CR)" character appears. located at the end of line(EOL), these two characters seperates each string by changing line. Without these two characters, the monitor shows the stream like this(no line change).

  102617010933, 8486, 22, 35, 13464, 25716, 21962, 00, 00, 20, 06102617010933, 87216, 22, 35, 13576, 25223, 21442, 00, 00, 20, 07

So you can see there are CR, LF characters at the EOL. Utilize CR or LF as a terminator of ReadStringUntil() function.
https://www.arduino.cc/en/Serial/ReadStringUntil

Second, parsing process. This process is extracting data you want from strtok() function. strtok() is from C language. It divides string by seperator characters.
https://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Lastly, utilize the data and repeat whenever sensor sends the data.

I'm not expert at coding. I haven't tested the code below. But this code would be helpful.

int data[12];
int isDataReceived = false;

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

void loop(){
  while(Serial1.available()>0) {
    String inString = Serial1.readStringUntil('\n');
    char * pch = strtok(inString, ","); //Serial number would be ignored
    for(int i=0; pch != NULL; i++) {    //following data are stored in data[12] string
      pch = strtok(NULL, ",");
      data[i] = atoi(pch);
    }
    isDataReceived=true;
  }
  if(isDataReceived) {
    Serial.print("Data:");
    Serial.println(data[0]); //just example code. You may see ppb on the serial monitor.
    isDataReceived=false;
  }

}


Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space?

The question is a little vague.

AltSoftSerial only works on pins 8 & 9, so I thought you were asking if you could connect both the cell and the GPS to pins 8 & 9 (using jumper pads on the back of the board), and use one AltSoftSerial instance to talk to both devices.  If it were possible, this would save RAM (just one instance) and program space (you wouldn't need two link in another software serial class, like SoftwareSerial).  However, this is not possible.  Serial connections are always point-to-point.  Although two "things" can listen to one RX line, the TX line cannot be shared by two devices.

If you were asking if you can have two instances of AltSoftSerial on two separate pairs of pins (e.g., 2/3 and 8/9), the answer is again "No", because... AltSoftSerial only works on pins 8 & 9.  Also, the SparkFun library only uses SoftwareSerial to talk to the cell.

  what could i do to reduce space.

Use NeoGPS instead, and use the F macro around double-quoted strings that you print:

    sms.print( F("Imposible ubicar equipo, intente mas tarde...") );

That will save several hundred bytes of RAM.

Also, you may be sending multiple SMS's per second.  It depends on what sentences the GPS emits.  As it is, your sketch will send one SMS per sentence (i.e., one for each encode).  Even if you don't use NeoGPS, look at the example program NMEAloc.ino et al for the correct program structure.  The Troubleshooting section also contains some tips.


Making CS (chip select) work in SPI (for and SD card and OLED)

I wanted to write to 2 SD cards simultaniously with one Arduino Mega. Used all the relevant pins including CS on 53 for the first SD card and 13 for the second SD card.  Can be any digital pin I think but this one makes the LED blink too).  Before the SD.begin(13) of the second SD card I do a digitalWrite(53,HIGH).  That de-selects the first SD card. and digitalWrite(13,HIGH) when switching back to SD.begin(53) I do a digitalWrite(13,HIGH).  This works real fine.
Now I tried to impelment this on a D1-Mini.  Cannot get it to work.
SD.begin(D8) starts the first SD fine.  By doing a digitalWrite(D8,HIGH) I tried to de-select SD1 and with SD.begin(D4) opened the second card. Strangely enough it still opens the first SD card again regardless of the pinnumber-parameter.
Maybe the SD library for ESP8266 remembers the first setting of the CS and later settings og the parameter with fifferent pinnembers are ignored???


Cannot find Arduino under /dev Directory

Note that lsusb does not guarantee the drives are loaded (See https://superuser.com/questions/165733/will-lsusb-and-lspci-list-devices-for-which-the-system-has-no-drivers)

Per the https://stackoverflow.com/a/14586884/1653571 answer, try an 'lsmod' and see whether you have a 'cdc_acm' module loaded.


Is it possible to overclock the baudrate from the mega to 230400 bps?

Yes, setting that baud-rate is not a problem but this specific baud-rate may will give a high error rate. According to the AVR baud-rate calculation (UBRRn Settings for 16 Mhz system clock) the error is 8.5% (U2Xn=0) and -3.5% (U2Xn=1).

Simply choosing 250000 bps will remove this error.

Cheers!


Why are characters with value above 127 "padded" with 1s to be 16 bits long, while ones with values 0-127 aren't?

On the AVR platform the char type happens to be signed, and it can
store numbers in the range [−128, +127]. Thus, when you write
char bar = 128;

You are asking to store in bar a number that does not fit. It then
gets reduced modulo 28 into the value that does fit, namely
−128. For the kind of manipulations you are trying to make, I would
recommend you use uint8_t instead of char.

it would be always safe (and not undefined behavior) if I did it as
follows

It is indeed safe, and the casts you use are needed to make it safe.


Sending more than BUFFER_LENGTH(32) bytes in slave answer I2C

The limitation is purely in software. The I2C hardware has a limit of one byte at a time, and the software creates a 32 byte buffer and feeds each byte from that in turn.

While it would be perfectly possible to increase that buffer size, you may find you have other problems when you get above 255 bytes, since lots of parameters and internal variables for the library are limited to 8 bit values.

It would also be considered very "hacky" since you can't easily upgrade the Wire library in future.

A better strategy would be to split your data into chunks and make multiple requests, each one saying "Give me chunk number ..." and then recombine them upon reception.


The only thing I didnt do is to use the 22 Ohm resitors, is that a problem?

Yes, that's a huge problem. The resistors are there to prevent reflections from distorting the signal. Without them the best you can hope for is a garbled mess.


How do I change fuse bits - not communicating?

If AVR is bricked because of wrong fuses I suppose it's typically non-working external oscillator you need provide signal to particular AVR pin to get programmer working again. Thread related to unbricking http://www.avrfreaks.net/forum/locked-out-atmega-328p-possible-clocklow-fuse-byte-issue.


Arduino Micro blue light dimms and turns off when I plug in my circuit

This sounds like a lot to have connected to the Micro's 5v pin. Without knowing your exact model of servo, I would still believe you are hitting the current limit. Can you try unplugging the servo and see if the circuit functions without the servo? I would power the servo externally with a 5v supply.


using multiple hc-05 with one arduino mega

HC-05 modules use Serial (UART) for communication with the Arduino. Thus you need 4 Serial interfaces for 4 HC-05 modules. The Arduino Mega has 4 hardware Serial interfaces, so just connect once HC-05 to each Serial interface. Then handle each module in your code the same just with a different Serial interface. If you already know, how to use one HC-05, then it should be rather easy to implement the same with all 4 modules.


Managing configurations via EEPROM by writing it with the hex file

AVRDUDE can program EEPROM. I usually do this as part of the firmware burn - the operator can pick which config block should go into the board while running the programming cycle. In some cases the EEPROM info is even generated programmatically during the cycle to contain dynamic info like unit serial number and commision date.

Here is an example command line that will program the file filename.hex into EEPROM...

avrdude -c stk500v2 -P COM6 -p atmega328p -U eeprom:w:filename.hex:i

The AVRDUDE write command (U) has many options to do almost anything you want...

-U memtype:op:filename[:format]
Perform a memory operation. Multiple ‘-U’ options can be specified in order to operate on multiple memories on the same command-line invocation. The memtype field specifies the memory type to operate on. Use the ‘-v’ option on the command line or the part command from terminal mode to display all the memory types supported by a particular device. Typically, a device’s memory configuration at least contains the memory types flash and eeprom. All memory types currently known are:
(...)
MEMTYPE:
eeprom
The EEPROM of the device.
(...)

OP:
w
read the specified file and write it to the specified device memory

(...)

FILENAME:
The filename field indicates the name of the file to read or write. The format field is optional and contains the format of the file to read or write. Possible values are:

i
Intel Hex

s
Motorola S-record

r
raw binary; little-endian byte order, in the case of the flash ROM data

e
ELF (Executable and Linkable Format), the final output file from the linker; currently only accepted as an input file

m
immediate mode; actual byte values specified on the command line, separated by commas or spaces in place of the filename field of the ‘-U’ option. This is useful for programming fuse bytes without having to create a single-byte file or enter terminal mode. If the number specified begins with 0x, it is treated as a hex value. If the number otherwise begins with a leading zero (0) it is treated as octal. Otherwise, the value is treated as decimal.

a
auto detect; valid for input only, and only if the input is not provided at stdin.

d
decimal; this and the following formats are only valid on output. They generate one line of output for the respective memory section, forming a comma-separated list of the values. This can be particularly useful for subsequent processing, like for fuse bit settings.

h
hexadecimal; each value will get the string 0x prepended.

o
octal; each value will get a 0 prepended unless it is less than 8 in which case it gets no prefix.

b
binary; each value will get the string 0b prepended.

The default is to use auto detection for input files, and raw binary format for output files.

Note that if filename contains a colon, the format field is no longer optional since the filename part following the colon would otherwise be misinterpreted as format.

As an abbreviation, the form -U filename is equivalent to specifying -U flash:w:filename:a. This will only work if filename does not have a colon in it.

Any of these files types can be used depending on what kind of data you are writing to the EEPROM and how it is being generated.

More info here...
https://www.pololu.com/docs/0J67/5.8


Directly read analog voltage using PWM duty cycle timer registers

In the end I managed to do this by reading the timer/counter control register relevant to pin 6:

// read the voltage on an analog output pin
int analogReadOutput(int pin) {
    switch(digitalPinToTimer(pin)) {
        case TIMER4D:
            if (TCCR4C & (1 << COM4D1)) {   // PWM active
                return OCR4D;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        case TIMER4A:
            if (TCCR4A & (1 << COM4A1)) {   // PWM active
                return OCR4A;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        default:
            return -1;
    }
}

Note that this assumes two things that possibly aren't always true (outside of my simple program):

COM4D1 bit is a reliable way of telling if PWM is enabled,
duty cycle value is 8 bit with a max of 255.


You have to call the functions:

#include <DHT.h>
#define DHT11_PIN 7
DHT dht(DHT11_PIN, DHT11);

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

void loop() {

    float humidity = dht.readHumidity();
    float temperature = dht.readTemperature();

   if (isnan(humidity) || isnan(temperature)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    Serial.print("Temperature = ");
    Serial.println(temperature);
    Serial.print("Humidity = ");
    Serial.println(humidity);

    delay(1000);
}

Edit


Arduino Uno, HM-10 Bluetooth Module, Not Discoverable

Ah, I jumped the gun. Just found out Mac/iPhone can't scan for BLE devices, so I downloaded a BLE scanning app and once I set AT+ROLE0 and AT+RESET it appeared.

So, the answer is you need a BLE scanning application.


Serial port /dev/cu.usbmodemfa131 vs /dev/cu.usbserial-A702NY8S

Drivers are different. On older boards, such as Duemilanove you may need to actually download serial drivers to talk to them at all in Lion, Mountain Lion, Mavericks.
There's some discussion of that problem here.


How do I install the latest Arduino IDE on Ubuntu 14.04LTS?

Follow the following step to download, install and run Arduino IDE on Ubuntu

First Download the Tar (tar-bal) from this link http://arduino.cc/en/Main/Software (download the correct 32 / 64 bit linux version ) depends upon your Ubuntu version.
Then goto download folder using terminal (shell) or the folder where you downloaded the tar and unpacked that tar using the following commands
like
cd /Downloads
tar -zxvf arduino-1.6.7-linux32.tgz
where 1.6.7 is the version of ide
you also need java runtime environment for arduino IDE download and install it using the following command
   sudo apt-get install openjdk-7-jre
you also need to provide the UART permissions for your hardware using following commands
sudo chmod a+rw /dev/ttyACM0
where ACM0 is the port number if you are using multiple or many arduinos just give permissions using the above commands by replacing the ACM0 to ACM1 to ACMN

then create a shortcut of arduino ide from the folder where you extract the tar
cd ~/Desktop
ln -s /Downloads/arduino-1.6.7/arduino

and then double click the shortcut to run arduino if it gives permission error then right click the shortcut and in file preferences gives permissions to the shortcut


Is there any library for use Arduino Uno with esp8266-01 module?

Why involve the UNO at all.  The ESP88266 could be programmed with the Arduino IDE to read the sensor and deal with the internet all by itself.  It doesn't need the UNO to do what you want.


Function for converting milliseconds to minutes?

Your sConversion returns an int as argument. You need to declare it as unsigned long.

This is what you are lookin for:

unsigned long conv(int x) {
  return x * 600000L;
}


TCP connection CPU usage, multiple signals?

As the Arduino typically has no demand-based clock scaling, or alternate threads of comparable priority you can schedule, there's really little point in using a delay (which is implemented as a busy-wait) rather than a tight loop - really, the primary appropriate reason would be to reduce the frequency of status output.

However, if you want to design a power-efficient system, you could consider sleeping the CPU between checking if there is anything worthwhile to do, or until an interrupt indicates that there is.  This is not something which delay() will take care of for you, so it is a fair amount of extra work and testing to get right, but it can be very worthwhile if running from batteries.

If your application is not particularly intensive you can also configure the clock divider fuse and slow the chip down generally.


The error you see, 'EthernetUdp2' does not name a type, means exactly that - there is no type EthernetUdp2 defined.

If you look at the source of EthernetUdp2.h, you'll see that the class declaration is EthernetUDP. See:

class EthernetUDP : public UDP {
    private:
        // Private members...
    public:
        EthernetUDP();  // Constructor

      // Public members...

};

class EthernetUDP : public UDP defines a class called EthernetUDP that inherets from the base class UDP. The constructor is what gets called when you instantiate a new object of type EthernetUDP.

Replace the line EthernetUdp2 udp; in your code with EthernetUDP udp; and it should work because the types will match. For reference:

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp2.h>
#include <Twitter.h>
#include <util.h>

#include<SPI.h>

EthernetUDP udp; // <---- This works

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

}

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

}


How to transfer data from Arduino to some software in computer?

Just use serial communication. Make sure you know which port your Arduino is recognized in your system, make a sketch to send data through Arduino's serial communication and try making a simple Node.js application using serialport package which will receive your data. There is a code sample where you can start from. Just set the port and start receiving data. And that's good, using Node.js you are really close to web tools, so it's easy to migrate your application to web.

It's really simple and you can get it done in a few minutes, even if you have not been introduced to node.

These kind of embedded applications have been accepted by Node.js and there are plenty of robotics projects which use node on the web.

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM0", {
  baudrate: 57600
});

Usually Arduino is recognized as ttyACM0 on Unix-based systems.
With this line of code you establish a serial communication with your board.

Going further you can register events like data, which is fired when data comes from Arduino:

// it opens the connection and register an event 'data'
serialPort.on("open", function () {
  console.log('Communication is on!');

  // when your app receives data, this event is fired
  // so you can capture the data and do what you need
  serialPort.on('data', function(data) {
    console.log('data received: ' + data);
  });
});

In this example your app just receives data and log it to your terminal.


That grounding scheme looks right since the Load ground is coupled back to the supply separately from the logic ground.

The only reason you would separate supplies would be to isolate them for safety or other reasons. For example, if the load side was a large or ac voltage.

Isolation requirements vary with application so it is hard to be more specific than that here.


Independent of the setting of port direction (input or output), pin can be read through the digitalRead():

int pin_light = 3;
int status = digitalRead(pin_light);


If you want files, then you need a filesystem. The only simple to use and reliable things on an Arduino that have a filesystem are SD cards or USB memory sticks through the USB Host Shield.

However, most of what people think they want to store in "text files" is actually data that can better be stored in other ways. Using text to store numeric values that only the Arduino will ever see is pointless - store it as numeric values.

The most convenient place to store such values (if you don't have lots of them) is in the internal EEPROM.

If you have more than a few values you can use an external EEPROM or serial Flash chip to store larger amounts of data.

Anything more than that, though, and SD card rapidly becomes the most cost effective method.


What data type are the analog pin labels (A0, A1, etc)?

As you can see in Arduino.h, the analogRead() has uint8_t as parameter. You can define them as byte or uint8_t and you don't have to use the sizeof().

The type of A0 is defined in the file pins_arduino.h:

#define PIN_A0 (14)
static const uint8_t A0 = PIN_A0;

Nevertheless, what you have with integers is 100% okay as well.

When you don't have a Arduino board available, you can use the simulation of an Arduino Uno at Tinkercad.

As @DataFiddler writes below this answer, using a 'const' keyword is preferred:

const uint8_t analog_pins[] = {A0, A1, A2, A3};


Can I use a 6 pin Bluetooth module in a 4 pin socket?

After some more concerted searching I have found the answer on Success Using the JY-MCU (linvor) Bluetooth Module:

  The module has 6 pins labeled on the back, but most modules only have
  4 of those populated with pogo pins.  KEY & STATE seem to be not
  required, as KEY is used for flashing the device and STATE simply
  indicates if the device is awake or not.  So that leaves only GND,
  VCC, TXD, RXD.  Not shown is Pin 11 which is the RESET pin, resetting
  the module when pulled LOW.

So, the answer is apparently yes, and you can buy a cheaper 6 pin module and remove (snip/desolder) the two additional pins.  The EN pin is also apparently labelled as KEY on some modules.


Is new.cpp programmed improperly? Arduino 1.8.9

http://www.cplusplus.com/reference/new/operator%20new[]/:

  in C++, new[] is an operator with a very specific behavior: An
  expression with the new operator on an array type, first calls
  function operator new (i.e., this function) with the size of its array
  type specifier as first argument (plus any array overhead storage to
  keep track of the size, if any), and if this is successful, it then
  automatically initializes or constructs every object in the array (if
  needed). Finally, the expression evaluates as a pointer to the
  appropriate type pointing to the first element of the array.


Add the crypto library to your build, Makefile or whereever your IDE expects it.

--> http://bbs.espressif.com/viewtopic.php?f=46&t=1442


Try connecting via ethernet to 192.168.255.1 with root/root

The SSH access for Dragrove is:
IP: 192.168.255.1 on LAN port. If you want to connect to the Dragrove via WiFi, the IP should be 192.168.1.108.
Username: root
Password: root

http://www.seeedstudio.com/wiki/Dragrove_-_Generic_gateway_for_internet_of_things


All you need to do is ignore any reading within the first  milliseconds.  Off the top of my head there is a delay statement before reading from this sensor, just alter that.  You can work out how long it needs to be by working out how fast sound waves travel through the air and measuring the distance between the sensor and the source of the reflection.  I think you might know how to do that :)


Multiple transmitters and problem with ref

You want to send data from 3 (or 4?) different Arduino transmitters to one Arduino receiver and you want to be able to distinguish the packets sent by each transmitter as they are received. The most straightforward way is to create a struct for your data and attach a unique header and trailer that can be used to identify the sender.

typedef struct {
  uint8_t header = 0x01;
  int temp1;
  uint8_t trailer = 0x10;
} PACKET;

Something like this should be present in each transmitter but with unique header and trailer for each one. Then the receiver should have the header and trailer bytes for all the transmitters and, whenever it receives data, it checks the first received byte against the list of header bytes to know who sent the data before it continues. Finally, it checks the last byte to know if it's the correct trailer byte for the assumed sender and also as an additional (but perhaps unnecessary) layer of error detection to know if the received packet is a complete valid one.


Programming Arduino Pro mini 328 with Arduino Uno SMD

check this tutorial:

  http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/

Works fine for me (I have a redboard, also with SMD microcontroller). In short this is the pinMap:

UNO BOARD (SMD)    Pro Mini 5V
       GND             GND
       5V              VCC
       RX              RX1
       TX              TX1
       Reset           GRN


Communicating to arduino as fast as real-time

Going over USB will add about a millisecond of jitter to your data in both the sensing and command directions.  Using a part with direct USB rather than then needing to go through a serial link from USB chip to processor could help limit what is added on top of that, but it will still be there.  If you could get a USB high speed solution that would reduce this as the polling interval is shorter, but there are few such solutions for simple microcontrollers.  Ultimately, USB is meant to move a lot of data in a reasonable amount of time - it is not designed to move small messages promptly.

True realtime systems put the processing and the actuation in tightly connected local circuitry. With the increasing isolation of PC processors from external I/O by multiple layers of intermediate architecture on the chip and motherboard, you see very little realtime use of PCs today.  An embedded board with a decent processor and good direct I/O (Beaglebone, maybe the Linux side of a Yun or comparable) would be better, but be aware that multi-tasking operating systems like Linux or Windows are fundamentally in conflict with real-time performance - it takes very complex hacks to make that work, for example running a realtime scheduler directly on the hardware  and having it run an ordinary operating system as a low priority task.

The architecturally cleanest solutions would be to find a way to fit your calculations on a fast single processor - in the realm of Arduino-style solutions perhaps one of the latest in the Teensy series.  Beyond that you are really out of the realm where this could be considered an Arduino question - trying for example to run a realtime scheduler on the Linux half of a Yun is really not related to "Arduino" at all.

One thing that is not clear however is if your system needs to react in real time, or merely to sequence with precise timing.  Mere sequencing is a far easier problem, as you can send the data a bit in advance of need and hold it in a buffer, so that communication latency doesn't delay operations.  A 3d printer could be an example of this - the really complex  calculations are done on a PC, then commands are drip-fed a bit in advance of need to a simpler executive traditionally running on a repackaged Arduino Mega, and that moves the motors with sub-millisecond pulse precision.  Given that there are no realtime inputs to the calculations, their results can also be stored on an SD card for use months later with no PC connection at all.  If your need does reduce to such pure non-reactive sequencing then things are a lot simpler; if it doesn't, then the rest of the explanation here applies.


arduino I2C maximum number of writes per Transmisson

There are five buffers used by the TWI and Wire library. They are defined as 32 bytes.

In wire.h:

#define BUFFER_LENGTH 32

In Wire.cpp:

uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
...
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];

In twi.h:

  #define TWI_BUFFER_LENGTH 32

In twi.c:

static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
...
static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
...
static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];

So immediately you are using 5 x 32 bytes (160 bytes).

You could increase that to (say) 64 bytes, bearing in mind your 160 byte overhead is now 320 bytes, and you don't have a lot of RAM.

The comments about endTransmission() are correct. After a Wire.beginTransmission() nothing is actually transmitted until the endTransmission() call. This lets you fill up the buffer at your leisure, and then let the library do the writes in a fairly timing-specific way.

Reference

I2C
Wire Library


From the pic, it looks like a 2x16 female header, PCB mount, with the pins bent outward and soldered to some male header pins.

I think they do this to provide mating sockets for the 2x5 male pins on the CC11001s that can be hooked up to a breadboard.

You could avoid this by prototyping on something like "stripboard' or 'Veroboard' like https://www.amazon.com/Soldering-Prototype-Printed-Circuit-Stripboard/dp/B019Q14GRQ/ and cutting/soldering a few traces where appropriate.

Or you could use a small chunk of stripboard tor protoboard to do the adapting from the 2x5 at 0.1" centers, to 2x5 on 0.1"x0.4" centers.


What happens if I try to draw power from the VIN port while under USB power on an Uno?

You do run the risk of damaging the 5V regulator, yes.

Power will attempt to flow from the 5V rail (USB port) through the voltage regulator (backwards) and into the shield to power it.

As your shield doesn't mind being under-powered from 5V while you're programming the Arduino you can add a diode between 5V (anode) and Vin (cathode). This will bypass the regulator when the voltage of the 5V rail is higher than the Vin rail, and your shield will be supplied with about 4.3V (slightly higher for a schottky diode).


When distance == 20 you pause for 5 secs. So all calculations after that will be off by 5 secs. So, prevTime should equal 5000.

unsigned long time = millis();
unsigned long curTime = time - prevTime;    // 0 or 5000
int speed = 6;
unsigned long distance = (speed * curTime) / 1000; // calculating distance in meters for every milli second
Serial.println(distance);
// Only pause once
if (distance == 20 && prevTime == 0) {
  delay(5000);
  prevTime = 5000;  // Adjust for the delay
}


How do I connect Arduino to RS232 via USB?

This is effectively not workable.  USB is not a peer-to-peer standard, but a host/device one.  Both your Arduino and the USB-serial converter are intended to be devices, so they cannot communicate.  While it would be possible to use another microcontroller acting as a host to bridge to serial that would be pointless, as the actually central problem of RS232 vs. logic level serial would still need to be solved.

Instead, what you want is an inverting serial level shifter - essentially a board with an IC like a MAX232 or one its many successors.  You would either connect this to arbitrary digital pins of the Arduino and use a Software Serial instance, or decide that it is okay to block usage of the USB port by a computer while this is being operated, in which case you could connect it to the D0 & D1 pins used by the on-board USB interface (there are typically resistors in between the chips on the board to support this overriding).

Ironically, in a way what you want is one of the original Arduino boards that had a serial level shifter and 9-pin connector in place of the USB chip and USB connector of modern boards.  But then, you probably want something with an ATMega328p rather than the earlier, more primitive ATmega chips used on the original boards.  If you can still find a board of the original design, upgrading the chip may be an option, or it may be that your task is simple enough not to require it.

There have been many other non-Arduino embedded controller boards released with native RS232 ports as well, especially those dating from around a decade ago might give a good combination of fairly modern capability with not yet having abandoned RS232 in favor of USB.


Arduino IDE supports upload to a network port. Network ports are detected with mDns and made available in Tools>Port menu.

The ArduinoOTA library bundled with the esp8266 Arduino boards package supports upload from IDE with 'network port' over WiFi. See the example of the ArduinoOTA library available in Examples menu in IDE.


That's a Crystal Oscillator, not a crystal. Take the 22pF caps off to start.

Did you set the fuses to use an external clock source, vs a crystal with the internal oscillator driver (where the caps would be needed)?

Is the part oriented the correct way so it receives power and Gnd correctly?

Also, is it's performance any better than if you had just used a crytal?

https://support.epson.biz/td/api/doc_check.php?dl=brief_SG7050CAN&lang=en

vs these with +/- 10ppm stability (is that the same +/- 10 x 10 ^ -6 ?, which would b be better than 25 to 100 x 10 ^ -6)
https://www.digikey.com/products/en/crystals-oscillators-resonators/crystals/171?k=crystal&k=&pkeyword=crystal&pv1989=0&pv183=6185&pv2150=u16MHz&pv253=19&FV=ffe000ab&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25


Serial.print skips or hangs inside a "if" statement. Trying to call a function VIA serial uart

High likely you are exceeding your character array, see:
char a[5];

Which can hold 5 characters. However, you write:
if(strcmp(a,"RGB_1") == 0)

Which assumes you receive "RGB_1" which is 6 characters, because a string ends with a 0.
What also might happen is that you indeed receive only 5 characters without the ending newline, which means strcmp keeps searching until it finds a string end which may not happen.
So you can increase the array size a few just for testing purposes, and print i as jsotola proposes. Beyond that, also print each character you put into the array so you know how/if to handle a new line.
If you don't receive a string end, then use instead of the strcmp function, then use strncmp, which can search for exactly 5 characters, not checking until the end of the string.


Use an electromagnet for reading induction as well

You can use a hall sensor from an old computer fan.

If the magnet is not moving you are not going to be able to sense it with the coil of your electromagnet.
You can also decouple de input of your arduino with a cap in series with the coil, but again if the magnet is not fast enough you will have to use a bigger cap.

You can also make a voltage divider between your coil and sense from there. When the 12V are applied just add some code to offset the input signal.


You have to have a master for an I2C bus to work.  Can't you allocate one of the dip switches to define the master?

Edit to be able to remove the downvote
Nick his answer seems to imply that you do not need masters but that is wrong.
What Nick is saying is that you can swap masters over time.
But each time there is communication there is a master.
So the statement "You have to have a master for an I2C bus to work" is 100% right.
As I misunderstood this myself I downvoted this answer. I hope this edit will enable me to remove my downvote and add a upvote.


The green board is probably a custom PCB that controls the vehicle. Unfortunately, the image does not have enough quality to determine much else.


H Bridge for microcontroller power management?

While it may be possible to bend one of those to your proposed usage, it's far from ideal, for a number of reasons:

It's far more expensive than the single P-FET that you need to get the job done
It's risky: you can easily reverse the current through your components and blow them up
It imposes a ground offset which can cause you communication problems.

All you need is a single P-channel MOSFET (assuming you are switching 5V with a 5V logic signal) and a single resistor (10kΩ would be fine, but any large value is ok).

simulate this circuit – Schematic created using CircuitLab

Pull the GPIO LOW and the power switches on. As simple as that.

If you want to switch a higher voltage then simple use an N-channel MOSFET to pull the GPIO line LOW for you - which you then switch with your GPIO signal.


Pro micro Wire.endTransmission() does not return

Seems like the module has a defect, since the same code on another board produces the expected output on the I2C lines


Programming Other Atmel chips using Arduino

Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

Do you mean if the "Arduino as ISP" sketch and an Arduino would work to flash another Atmel AVR MCU? If so the answer is yes but I guess that you also want to generate code for the new MCU. In that case there is some work to be done before that is possible.

Start by reading about how to install additional cores and the guideline for a custom core. Then select an custom core to study. Here you will find the files you need to provide to support a new AVR based MCU.

Cheers!


Emergency Vehicle - Make two LEDs flash with buttons and a passive buzzer change sound

Your problem is the delay() in your BlueLED() and RedLED() calls. To get more "simultaneous" activities, you'd need to use timer interrupts to implement those delays. It's a lot more complex conceptually, but the right way to do it.


Motor for a winch (with controller and external power supply)

Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?

No, you should never ever power a motor through an Arduino. It can only provide a limited amount of current, before it gets fried. You need to provide the motor driver with voltage directly from your power source. You haven't stated, what you are using as a power supply. I assume, you are just using an USB port of a PC. That is also a no-go, since it will only provide 500mA at max (that's even less, than the Arduino can bear). You should power your motor with a power supply of 12V, since it is rated for that voltage. You can buy a simple wallwart for that.

Also, currently you are providing the 12V motor with only 5V, so it cannot give you it's full power. Use a power supply with the correct voltage and more than enough current capability. Though you should keep an eye on the current ratings of the ULN2003. The datasheet is not really clear, if that chip supports 12V supply voltage. Some variants like the ULN2004 seem to support it, but I'm not sure about the ULN2003. If it is not rated for 12V, you can destroy the chip that way.

We cannot know, if the motor with it's driver will be able to rotate the winch, since the seller does not name the torque of the motor. You could try to contact the seller and ask directly about this. More specialized sites, where you can buy motors, will tell you exactly, what the torque of the motor is, that you are buying. Buying a cheap part at Amazon is somewhat the lightweight variant of buying it directly from china: The documentation is a bit better, but still not great. Without documentation or information from the seller, you are stuck with just buying and trying.

  is there a shield for my MEGA which can enable these motors to
  function in parallel?

It isn't clear, what you mean by that. You can control as many motors simultaneously, as you have pins and as you have enough computation time (meaning not too much steps per second or other stuff going on in the program). As mentioned above the power has to be supplied to the drivers from outside of the Arduino, so that does not apply here.

  otherwise, is there a strong continuous servo with an external power supply that would work here?

Power supply and motors are 2 different parts, that aren't usually sold together. Also you should start with the motor: Look for a motor, that can provide the torque, that you need. Then look for a driver circuit, that can provide the functionality, is rated for the same voltage as the motor and can provide enough current for the motor (the max. motor current is also information, that a good seller will provide). Then look for a fitting power supply. Unless you are buying some kind of kit, you need to choose these parts yourself. (We don't do product recommendations here)

A possibility, that you might not have though about: You could buy a normal DC motor, which provides enough torque. As speed is not your biggest concern, you could buy a geared DC motor, which can be rather strong. For a driver you would need to buy or build a H-bridge controller (which is essentially just 4 transistors put together). Be sure to use a MOSFET based driver, if you want to buy a driver chip. The standard L298n is pretty lossy.

It seems, that you generally don't know, how to build such a project. So here are some notes, that might help you with that:

Connecting everything together: In most cases (and especially when handling high current motors) you cannot get around soldering. You can buy a perfboard (cheap PCB material, with some pads already connected for ease of use), put the parts onto it and solder everything to the perfboard. Using shields as no-solder solution can only work, when you find a fitting shield and fitting motor for your requirements. That can be a far fetch. So if you want to get into electronics and Arduino, you probably should get yourself a soldering iron (there are also many tutorials about using it on the web).
Connecting the power supply: When buying a walwart power supply, it will normally come with a cable attached to it. At the end of this cable may be a connector. You have 2 options: Cut the connector and solder the wires in the cable directly to your perfboard, or buy the counter part of the connector, which you then can solder to your perfboard. Depends on if you want to disconnect the power supply from the circuit or not.

As I'm suggesting here to invest in this a bit, I want to also sketch an alternative, if you just want to get it work and don't experiment (this site is full of makers, you do this for fun, but that does not have to apply to everyone):

You may be able to use a shield to do, what you want to. This might cost a more, than putting the parts together yourself, but it will safe you the investment in tools, which you might not need in future. As above you need to choose the parts fitting your requirements. Decide on the type of motors, that you want to use (if money is not such a deal, you can nearly use any motor with enough power, stepper motor, DC motor, ...). Look for a shield, that can provide the needed current and voltage to the motor.

Every motor shield has a terminal for connecting the external power supply for the motors. On good shields this is a screw terminal, so you would simply strip the cable of the power supply and put the wires of it into the screw terminal.


Random characters generated by LCD during serial.read()

The character to the right of the 'A' on your LCD display does not correspond to any of the built-in character bitmap definitions (either on a EU or Chinese display).  This random pattern is likely one of the 8 programmable character bitmaps supported by the LCD that has not been defined yet (ASCII codes 0 to 7).

So, you're likely sending the LCD a character with a value between 0 and 7.  It's probably a good idea to filter out invalid characters before attempting to display them on your LCD.

Filtering Example:

char c = Serial.read();
if ((c >= 32) && (c <= 128))
  lcd.write(c);


You can decipher most of them yourself.

A u prefix means unsigned.
The number is the number of bits used. There's 8 bits to the byte.
The _t means it's a typedef.

So a uint8_t is an unsigned 8 bit value, so it takes 1 byte. A uint16_t is an unsigned 16 bit value, so it takes 2 bytes (16/8 = 2)

The only fuzzy one is int. That is "a signed integer value at the native size for the compiler". On an 8-bit system like the ATMega chips that is 16 bits, so 2 bytes. On 32-bit systems, like the ARM based Due, it's 32 bits, so 4 bytes.  Of the three it is the only one that changes.

Personally I rarely use int and always use uint8_t etc., since the variable type is the same no matter what architecture you compile for.  When you use int you can run into problems if you had a program that worked fine on a 32-bit ARM but then doesn't work right on an 8-bit ATMega, since the int can only store a fraction of the range of numbers on the 8-bit system compared to the 32-bit system.


SIM800l doesn't respond on arduino micro

Here is some edit in your code

#include <SoftwareSerial.h>
#include<Arduino.h>

//Arduino Micro
//SIM 800l

SoftwareSerial mySerial(9,10); // RX, TX

void setup()
{
  // Open serial communication
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  Serial.println("Setup finished");

}

void loop() // run over and over
{
  Serial.println("Sending AT command");
  mySerial.write("AT\r\n"); //OK should be returned
  delay(1000);
  //read sim-module response
  Serial.println("Response: ");
  while( mySerial.available() )
  {
    String c = mySerial.readString();
    Serial.println(c);
  }

  mySerial.write("at+cmee=2\r\n"); //set sim-module into debug mode

  delay(1000);

  mySerial.write("at+cpin?\r\n"); //check if pin is necessary

  //read sim-module response
  while( mySerial.available() )
  {
    String c = mySerial.readString();
    Serial.println(c);
  }

}

Change UART pins to 9,10 as 0,1 are already used in normal serial. Secondly change Seria.read() to Serial.readString() because as far as i know the response is string.


How to connect 5V sensors to 3.3V digital input (Due)?

Well if you're not sure of what you're doing, you can always go with level-converters for your sensors (that does not apply to shields though)

Level-converters (sometimes called level-shifters) come in different flavors:

breakout board (the easiest to work with)
IC
DIY circuits with a few components

Some are "one-way": they have pin-pairs with converters 3.3V -> 5V, and other pin-pairs with 5V -> 3.3V conversion; others are bi-directional, i.e. you can use the same pair of pins in 2 directions 3.3V <-> 5V.

There are plenty of these converters, and they are rather cheap; here are just a few examples:

one-way breakout usable with 4 pairs of pins
bi-directional breakout usable with 4 pairs of pins
74HC4050 IC discussed here


For shift (making an a into an A), simply program in some ands. Pseudo-code:

if shift AND a:
    return A
elif shift AND b:
    return B

and so on and so forth.


Best practise when dynamically updating sketch

You won't be able to download the whole binary and test its checksum before flashing because RAM is so much smaller than flash. To do that, you'd need an external storage device to hold the new binary, and a custom bootloader to install it from the device.

Otherwise you'll have to load-and-flash, testing the checksum on the fly, and retry if you need to until you get a good reload. Can your device and its environment tolerate stopping for however long a couple of retry cycles might take? You can't recover if the process is interrupted once you start flashing; you can only move forward. Can it tolerate a conceivably long outage if communication goes down once the reload process has started?


See jwpat7's answer.
My answer is correct re address word BUT
his points out that "Words" are being addressed and not bytes.  While my answer is not wrong, his is more likely to be what the writer meant in his excessively cryptic footnote.

A Byte is most usually used to refer to an 8 bit quantity.

A "word" is usually used to refer to a multi-Byte variable with the length depending on both processor type and context.

In this case, on page 296, table 28-19 information is given on the format of 4 byte Instructions. These instructions are NOT referred to as Words although in some other contexts they might be.

However,  the "Write Program memory page" instruction contains the address of a memory page. This address is made up of a 16 bit field comprised of 2 Bytes - an MSB and an LSB.
The notation "Words" is shown against the MSB and the LSB to denote (not very clearly) that a single 16 bit "Address Word"is formed by the MSB + LSB combination.


How to connect both MicroSD module and MPU9235 power in an arduino

VIN takes 6-12v and it sends it through the on board regulator - so that is the best way to power the nano.

If you take a wire from the 3v3 pin and split it (solder two wires to one) then you will have two 3v3 feeds to wire to your two devices.  This will be the same as you have to do for the Gnd connections, back to the Nano.

Does that make sense? (if not I'll try and draw you something).


Up to six Serial Communication Interfaces (SERCOM), each configurable
to operate as either:

USART with full-duplex and single-wire half-duplex configuration
I2C up to 3.4 MHz
SPI
LIN slave

It is an error in the overview of the SAM D21 features in the datasheet. The SERCOM is half-duplex for I2C. USART can't be configured half-duplex.
see Application Note about SERCOM configuration

1 Introduction to Serial Communication Interfaces (USART, I2C, and
SPI)
... The exchange of data can be half-duplex or fullduplex depending on
the serial module specification. ...
1.1 USART
... It is full-duplex in operation. ...
1.2 I2C
... It is half-duplex in communication. ...


Can I connect an RFID reader to the ICSP header?

Yes you can. However the SS isn't present on that header. You can however use any pin you want for SS (if the library you use supports it, that is)


MIDI output circuit behaving incorrectly when not connecting with USB

If you are connecting multiple devices then they have to share a common ground.

I only know about British mains sockets, they all have an earth pin connecting to a common ground, so usually you are OK.

Plug in transformers 'wall warts' sometimes don't connect to ground, the give away is the plastic pin.  In this case you need to provides a separate earth and connect it to the rest of the equipment.

PCs normally have a good earth and this is passed by the USB to connected devices.  So "the Arduino always works when it is connected to the PC" is usually a good indicator of an earthing issue.

I think your keyboard uses a wall wart and therefore when you remove the USB they both float.  Touching the USB lead to the Arduinos USB socket grounds it all again.

So it looks like you diagnosed the fault correctly :)


LMT 84 temperature sensor measurement error

The Arduino uses an analog voltage as reference. It is default set to the Vcc of the microcontroller, which is about 5 V for an Arduino Uno. The function analogReference can be used to set something else as reference.

When that reference is not precisely 5.0 V, it is impossible to measure a voltage in a accurate way. It is almost never precisely 5.0 V. When using the USB connector to power the Arduino board, it might be somewhere between 4.5 and 5.0 V.

The Arduino Uno has an internal voltage reference of 1.1 V. That is better than using the default 5 V. The actual voltage can be 1.0 to 1.2 V, you have to put the actual value in your sketch.

The LMT84 has an output of 1034 mV at 0°C and 476 mV at 100°C. That means your calculation is not correct. In the datasheet are two ways to calculate the temperature, an accurate formula and a simple calculation.

You can avoid all these problems with a temperature sensor that has a digital interface to the Arduino board. For example the DS18B20. That is a cheap and accurate temperature sensor.


Safe to control multiple power sources through a switch through the ground?

You have the grounds of the batteries permanently connected together, so opening the switch won't remove them from the circuit altogether: it will leave a potential difference of 3v between the Arduino's power input at the L293's power input.

That would be exactly equivalent to having a 3v battery with its +ve terminal connected to the Arduino power input, and its -ve connected to the L293's power input, with their grounds connected together - so they're sort of wired in series, with one of them backwards, with a far-too-small supply voltage.

I suspect it won't kill anything but I would imagine it would drain the batteries and probably isn't what you want to do.


Will a genuine Arduino board have the same issues with High Sierra as other non genuine ones?

As long as the firmware on the ATMega16U2 chip is the same as on a Genuine Arduino and the bootloader on the ATMega2560 chip is the same as on a Genuine Arduino then your boards should function exactly the same as a Genuine Arduino.

If you find a Genuine Arduino works but your boards don't then there must be a difference, and that can really only be in the software on the chips - so reprogramming the chips to match a Genuine Arduino would probably help.

I haven't heard reports of High Sierra not working with Genuine Arduino boards, but given the severity of some of the bugs that have crept in recently, it seems likely that more problems are hidden away under the hood that no one really knows about yet.


The answer is that arduino is little endian, so the byte order is correct. I was just expecting big endian order as ive seen in some other network protocols. If that is desired instead I can just do some bit shifting and re-arranging.


Error compiling for board Arduino/Genuino Uno

This is a known incompatibility between the Arduino IDE and Microsoft OneDrive. A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.


Arduino IDE: Board nodemcuv2 (platform esp8266, package esp8266) is unknown

Did some digging and found a solution that worked for me:

Uninstall (by logically deleting folders) and reinstall ESP Libraries.

Open Arduino IDE
Go to FILE -> PREFERENCES

Open the preferences folder (this works in Linux, Mac and Windows)
Go to PACKAGES > ESP8266 > HARDWARE > ESP8266

Delete all libraries (if your issue is similar to mine and to others', you should have 2 or more folders, with different versions).

Restart Arduino IDE.
Go to SKETCH > INCLUDE LIBRARY > MANAGE LIBRARIES
Install ESP8266 Community
Go to TOOLS > BOARD and scroll down to your model of NODEMCU

Run compile and your problem should be fixed.


Unfortunately I think you are missing the actual error message and have just copied the result.  I suspect if you scroll back up through the output it will say loop is missing.

All Arduino sketches (well almost all) have to have setup() and loop() functions.  The underlying 'stuff' will call setup() once and loop() repeatedly.

I hate global variables, but in this case I would be tempted to move those arrays out of the function and make the constant global values.  That way they will be in memory as the Arduino boots and you won't have to waste processor cycles setting them up.

It may be a silly question, but are you using the right hardware?  This might help check that http://playground.arduino.cc/Main/LedControl


can I check if why my motor isn't working?

Well, your wiring is OK, but I think the

'digitalWrite(enB, HIGH);

in the loop() code is causing your problem.  You don't want to try to use the same pin for both digital and analog functions.

I wired up a Uno here with your setup and a L298N, and got a motor to run fine with the following sketch that doesn't use the loop() at all - it does everything in setup().

char data = 0;
int enB = 9;
int InC = 8;
int InD = 7;

void setup()
{
    Serial.begin(9600);
    Serial.println("Motor test !");
    pinMode(enB, OUTPUT);
    pinMode(InC, OUTPUT);
    pinMode(InD, OUTPUT);

    Serial.println("motor should start moving now !");
    digitalWrite(InC, HIGH);
    digitalWrite(InD, LOW);
    //digitalWrite(enB, HIGH);

    for (size_t i = 0; i < 10; i++)
    {
        analogWrite(enB, 20*i);
        Serial.print("motor speed = "); Serial.println(20 * i);
        delay(2000);
    }

    Serial.println("quitting!");
    while (true)
    {

    }

}

void loop()
{
    //Serial.println("Entered loop, should start moving now !");
    //digitalWrite(InC, HIGH);
    //digitalWrite(InD, LOW);
    //digitalWrite(enB, HIGH);
    //analogWrite(enB, 255);
}

If you can't get your motor working with the above program, then you most likely have a connection or power supply or component problem that you'll need to troubleshoot.

Hope this helps,

Frank


How are Arduino's OSH if Atmel AVR is proprietary?

The components are necessarily going to be proprietary.  There is no feasible way around this.  If you wanted to design a new open source microcontroller from scratch with no proprietary components, it would set you back several billion dollars.  The software used to design integrated circuits costs hundreds of thousands of dollars to license and represents billions of dollars of investment.  Production of the chips themselves takes place in wafer fabs that cost billions of dollars to build, and represent billions of dollars of investment in process technology and semiconductor physics research.  The equipment and process technologies are very closely held trade secrets.  If you are OK with proprietary production, then you can submit GDSII design files (developed with your own open source IC design software) to fabs such as TSMC for production, but the line setup costs will run in the hundreds of thousands of dollars.

Bottom line: you have to draw the line somewhere as to what is acceptable to be 'open' and what is not.  Open source hardware generally means the board-level design files and firmware sources are available, and generally nothing more.

Interestingly, there are many open source CPU designs available.  Sun's OpenSPARC is an open design, you can download the RTL description of the CPU core and modify it.  However, convering RTL to a chip requires IC design software or implementation on a proprietary FPGA with a proprietary development environment.


Passing arguments to LCD.print through another function

One way to do this is to use generics. And we also need to use an unnamed namespace to get around the IDE's "helpfulness":

namespace {
    template<typename T>
    void lcdPositionPrint(int row, int col, T content) {
        lcdPosition(row, col);
        LCD.print(content);
    }
}

This will cause the compiler to create one function for each type passed in content that the function is actually called with.


Phone lines run off of the RS-232 telecommunications protocol which can run off -25v to 25v, which would completely destroy your Arduino. Luckily there is an IC made to help you with that. You can use the MAX3232 IC to convert RS-232 to TTL 5v or 3.3v (Same chip can do either). Look at providers like Digikey for just the chip or you can get a breakout from providers like SparkFun.

TL;DR Yes, but you need a special IC to not fry your Arduino.


How to fix 12V RGB LED Strip connection to NodeMCU?

So now we finally know the reason is MOSFET's threshold voltage is too high. The solution is to drive the gate with NPN transistor (you can use BC547 or 2N5551 or similar). You have to connect it's collector to 5 V and it's emitter to GND. Put 10k or 100k resistor between 5 V and the collector, connect the collector to MOSFET's gate and GPIO to the base of NPN transistor. Put some resistor between GPIO and the base of the transistor, maybe 4k7 or similar.

Note:
HIGH from GPIO will switch off the LED strip and LOW will switch it on.

Another solution is to use MOSFET with lower threshold voltage.

EDIT:
If you want to avoid adding NPN transistor you can use NTD5867NL MOSFET which has max threshold voltage 2.5 V so it will for sure work with 3.3 V at the gate but is rather expensive (about $4). Much better solution is adding cheap NPN transistor.

EDIT:
Here is the schematic:

simulate this circuit – Schematic created using CircuitLab

EDIT:
Here is the correct wiring:


Please take a look at the documentation of SerialEvent.

This might be exactly what you are looking for (after several small tweaks)

Code from the example:

/*
  Serial Event example

  When new serial data arrives, this sketch adds it to a String.
  When a newline is received, the loop prints the string and clears it.

  A good test for this is to try it with a GPS receiver that sends out
  NMEA 0183 sentences.

  NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
  other ATmega32U4 based boards.

  created 9 May 2011
  by Tom Igoe

  This example code is in the public domain.

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

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:
    inputString = "";
    stringComplete = false;
  }
}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}


Connect a sensor to Arduino without knowing much info about the sensor

You have linked to the datasheet of the sensor.

In the datasheet, look at the "Application Circuit" section. You must build this circuit. The sensor produces a very small electric current, and the application circuit is high-gain amplifier to translate that very small electric current to a varying voltage you can sample with the Arduino ADC.

Note on the circuit, the wire labled "To ADC" -- that is the part which you connect to your arduino.

As for calibration, the datasheet itself notes that the process is non-trivial, or that they can perform a calibration, for an additional fee, at the time you order a batch of sensors. Presumably their calibration will include the precise resistor values used to set the gain of the amplifier, and also an equation to associate PPM values to the analog voltage provided at the "To ADC" wire.

As for reading the circuit diagram (schematic), you may already know resistors and capacitors. For the other items, search online for the part numbers given, to find out what they are.

The datasheet also notes that the application circuit is available pre-built from the sensor manufacturer. You may want to contact them to determine how to purchase one for yourself.

Most electronics products have a datasheet that explains all you typically need to know about the device, such as it's operating parameter minima and maxima, typical values, typical outputs, etc. This sensor is no different, except that the calibration procedure is not described in great detail due to the complexity.


I've found the solution, it's strange since I enabled CTC mode, but it started to work normally as soon as I reset Timer 1:

ISR(TIMER1_COMPB_vect) {
  TCNT1 = 0;
}


You cannot set the fuses using the Arduino bootloader, since they cannot be self-programmed. You must use either serial or parallel programming via ArduinoISP or an external programmer to set them. Since the chip is configured to use an external crystal you must either connect a crystal up to the chip appropriately (see sections 9.3 or 9.4 of the datasheet) or use parallel programming. You will then be able to use the lfuse, hfuse, and efuse memory types to read and write the fuse bytes.


Powering Multiple Servos From One Battery- What is my circuit missing?

One thing to ask, it is not clear if you are going to run the Arduino Uno off the same battery, or off a different battery?

If the same battery, then you are likely going to need to create an V+ output for the Uno, but will need to ensure that any drain from multiple servo's running are not going to impact on the voltage supplied to the arduino, and also that the voltage supplied is compatiable with the Uno (e.g. don't run 6V+ into the 3V outlet)

Just to note as well, the Arduino Uno has (to my knowledge) only has about 6 PWM pins which is what you will need to drive the servo's through the signal pin. You can add I2C PWM expanders which give you more pins (e.g. https://www.adafruit.com/product/815) but YMMV


I can't understand the purpose of connecting *RE/DE to GND/Vcc. With
this setup, the driver inside the transceiver is always enabled, and
it's always driving the A/B pair. Meaning the device at the other end of
the link cannot drive the pair itself without making a collision.
Basically you have a simplex link, where the Pro Mini is always the
sender.

The normal way to connect an RS-485 transceiver is to have DE driven by
a GPIO pin of the MCU. You pull this pin HIGH when you want to talk, and
leave it LOW the rest of the time so you can hear other devices talking.
The *RE pin is connected either to GND (if you want to hear the echo of
what you say) or to DE (if you don't).

That being said, you are correct in that the transceiver may cause
problems when uploading the firmware on the Pro Mini. One possible
solution is to put a resistor between RO and A-RX. The TX of the FTDI
cable should have a low output impedance and be able to overpower that
resistor. Another option is to use ICSP (in-circuit serial programming)
instead of going through the bootloader. It would be easier if you can
put an ICSP header on your board.


Generate single pulse from timer 1 in arduino nano

Timer1 has a few extra features, so you need to set the registers slightly differently from timer0 (or timer2). You need to also set the WGM13 bit in the TCCR1B register.

Since timer1 is a 16 bit timer, you need to change OSP_SET_AND_FIRE to also use 16 bits.

Lastly; Arduino pin 10 is port B, not port D.

#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10);
    DDRB |= _BV(DDB2);//pin 10; PB2
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint16_t m=0xffff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}


Look at timing on sheet 4 of the datasheet, and the times on sheet 3

A Low bit is 400 +/- 150nS wide Low followed by a 800 +/- 150nS wide High

A High bit is 850 +/- 150nS wide High follow by a 450nS wide Low.

To do what you suggest with a checksum, you'd have to send the checksum (minimum of 3 bytes to fake the data for an extra WS2812B for example) first, and see if the 24 bits were received correctly while at the same time the last 3 bytes were being sent out.

A Due might be fast enough to do that. I don't think a 16 MHz Arduino could.

Checking power level is not really feasible, as many strips get power attached to the beginning, middle, and end of a strip to ensure uniform brightness and to keep the strip's power traces from overheating from excess current flow.


There is more than 1 option how this can be done. A frequency of 40Hz is relatively slow, so you are not limited by this.

In my comment I first suggested to use the Timers/Counters with the signal as input, but I found, that this is only possible with one of the two timers of the ATtiny. Despite that, I will add this to the answer for information (and because this can be possible on other boards with more timer input pins).

Using the PinChange interrupt and doing counting in software: Since the ATtiny85 has only 1 external interrupt, you have to use the PinChange interrupt for this. If activated, this interrupt will trigger, when ever one of the pins 0 to 5 changes it's value. You can mask away any pin in this range, so that it doesn't count. You would use 2 pins and mask the others away. In the interrupt routine you would check the state of the two pins and increment the respective counter:

volatile unsigned int counter1=0;
volatile unsigned int counter2=0;

ISR(PCINT0){
    if(digitalRead(input_pin_1)) counter1++;
    if(digitalRead(input_pin_2)) counter2++;
}

(Note the volatile declaration of the variables, because they change inside of an ISR). The counterX variables can then read in defined time intervals (for example very second) to calculate the RPM. Of course, executing code in an ISR can mean, that you miss another interrupt. During the short time period between the first interrupt and the completed execution of the ISR no other PinChange interrupt will get registered. If that is a problem is dependend on how often the pulses will be inside this small range. If that only happens very rarely you can ignore that, since it introduces only very small errors. You can even make the ISR faster by not using digitalRead(), which takes a bit to execute, but using direct Prt Manipulations. That makes the error more unlikely.

The interrupts have to be configured for this, so you need a setup code like this (this will use direct manipulation of the status registers of the ATtiny):

PCMSK = 0b000110; // Mask all pins for this interrupt,except for PCINT1 and PCINT2
GIFR &= ~(1 << PCIF); //Clear PinChange interrupt flag
GIMSK |= (1 << PCIE); //Enable PinChange interrupt

In the loop function you can use the non-blocking code style from the BlinkWithoutDelay example, to regularly calculate the RPM from the counter values;

void loop(){
    if(millis()-timestamp > INTERVAL){
        GIMSK &= ~(1 << PCIE); //Disable PinChange Interrupt, so that we don't get interrupted by ti
        unsigned int countervalue1 = counter1;
        unsigned int countervalue2 = counter2;
        counter1=0;
        counter2=0;
        IMSK |= (1 << PCIE); //Reenable PinChange interrupt
        // Do the calcuation here with countervalueX and show the result somewhere
    }
}

It is important to disable the corresponding interrupt, when you are accessing the counterX variables, because you have to prevent them from changing midway during processing. To keep this short, they are just copied to local variables and then released again.

Attention: the following suggestion doesn't work on an ATtiny85, since it only has 1 timer input pin.

Using both available Timers/Counters and the signals as clock input: If you really don't want to miss any pulses, you can utilize two Timers/Counters. Timers and Counters are the same. A counter increments a status register on every falling or rising edge (depending on the configuration) of a signal. If this signal is derivated from the chips clock, this is called a Timer. You would use it as a Counter, feeding each square wave to one Counter input pin. To actually get the RPM, you can either check the counters value (TCNT0) after defined time interval, or you can activate the overflow interrupt of both timers and measure the time between the overflows.

Since here the edge-sensing is done in hardware, no pulse can be missed. On the other side, this way needs more configuring and blocks 2 precious timers.

When working with the status registers in such a direct way, the datasheet of the ATtiny85 is a must read.


Arduino Smoothing does not work as expected

Yes, change the variable type to something that can hold larger numbers, because now adding up 100 measurements will overflow your variable.


Do You Put a Break after the Last case in a Switch?

You can, but you don't have to.

Should you? That's up to you.

I do. That's because it's then simple to add another case at the end of the structure in the future if you want, and you don't have to remember to add the break to the existing last case.


Not able to send SMS to Mobile using GSM900A and Arduino Uno

looks like you should be using Serial.begin(2400);

also, I'm assuming your sms phone number isn't actually 919449835011 and that that's not actually the number you used in your code


The "high density" connectors expose every pin of the MCU. The pins around the edge of the board duplicate just the immediately useful ones.
Every pin that is on the edge of the board is also on the high density connectors somewhere.
Why have the pin on both connectors? Simple: if you want to use it in a breadboard or with jumper wires then you want the useful pins on the edge. If you want to use a plug-in board then you don't want to have to connect to both the high density connectors and the breadboard connectors, that would just be really awkward (since both have completely different height profiles). So everything is on the high density connectors for plug-in boards, and the useful ones are also on the breadboard headers.
A0 is the Arduino name for the pin. ADC is the function of the pin. The A of ADC stands for Analog. It's a pin that Converts Analog to Digital. It's an Analog to Digital Conversion pin - ADC.


How might I add a delay, close the servo and go to the start again?

if (buttonVal == HIGH)
{ //Start of if2
  locked = true;
  digitalWrite(green, LOW);
  digitalWrite(red, HIGH);
  myServo.write(90);
  Serial.println("The box is locked!");
  numberOfKnocks = 0;
  delay(1000);
}

I have added numberOfKnocks = 0 at this part of the code so your knock value goes to zero on locking it which will not open the lock again as soon as you lock it. The problem was that you did not change the numberoflnock value which remains same even after locking it so when the code loops back to the unlocking part it automatically unlocks it.
Hope this helps you.


How to upload program to custom arduino board without USB FTDI and making it read only?

I think you cannot prevent overwriting the firmware, neither prevent viewed by others.

However, you can detect that someone overwrites it (besides you), by reading some code from e.g. EEPROM based on the content of your firmware. If you read a different code, than you can act upon it.


I find your onRequest function obscure:

void sendPI(){
     int values[] = {(int)out, (int)outReversed  };

     Wire.write(values[count]);
     count++;
     if(count > 1){
     count = 0;

     }
 }

Why only send one byte? I think you have a number of problems:

The size of int on the Arduino Uno is 2 bytes, on a Pi it is 4 bytes. So there is a mismatch there for a start.
Wire.write (written like that) sends one byte, so that is only going to be half of your int. So that is even less.
It isn't obvious what the Pi end is doing, but to make the int sizes match, I would be sending the lot in one hit like this:

void sendPI(){
     long values[] = {(int)out, (int)outReversed  };
     Wire.write((byte *) &values, sizeof values);
 }

Now you just read 8 bytes on the Pi (two ints).


What pin is the external interrupt #0 for an arduino micro?


ATtiny85 serial communication, bootloader and setting up fuses

If you search the internet, you mostly find statements, that the fuses will be set right, if you burn the bootloader from the IDE. However I had to set the fuses in an extra call to avr-dude, because the clock divider was still active, setting the clock effectivly to 1MHz, instead of the intended 8MHz. With a command like

avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v

you can read the current fuses. Note that you have to set the parameters according to your setup (I used an ArduinoAsISP on the serial port ttyUSB1). You can write the fuses with a command like this:

avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v -U lfuse:w:0xE2:m

depending on which fuse you want to set, you have to replace lfuse with hfuse or efuse.

SoftwareSerial should also work with other clock frequencies, but I don't know the limitations. Keep in mind, that lower clock frequency means you can only reach lower baudrates. It is crucial, that the fuses are set correctly for the intended speed, because the library takes the speed defined in the IDE. In my case this was 8MHz, but the ATTiny still run at 1MHz, which confused the serial communication.


esp8266 not responding to the AT commands

I had same problem. It helped to connect GNDs of both power supplies namely the one powering the arduino and the 3.3V one powering the ESP8266.


PWM signaling with Arduinos: What is the reason for the ground connection?

Is PWM really a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?

At the most basic, it is a signal because we call it such. Even a constant voltage can be a signal, signalling that e.g. a window has not been broken. A PWM signal indicates that we want to apply a certain fraction of full power to a load.

  If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

Because it is a voltage-based signal, and ground serves as the reference for this voltage. Voltage only exists between two points.

  This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

Radio signals are photon-based; the oscillation of photons at a given frequency being broadcast from a location are what define the signal. Since frequencies are absolute, they can be discriminated without a (relative) reference.


Can we burn Arduino bootloader into any microcontroller chip?

The answer needs to have multiple parts:

Yes, in principle you can create a bootloader for any microcontroller, which acts like the Arduino's.

Please be aware that there are different bootloaders, not just the common STK500 compatible one. Each of these bootloaders implements a certain protocol to transfer the binary code to the target system.

Additionally, some protocols also include commands to restart the microcontroller, to set configuration registers, and maybe more.

You need to read the bootloader's documentation to become familiar with its capabilities.

But it is your decision whether such a bootloader on a non-AVR system or an non-Arduino-AVR system is good for you.

No, the bootloader does not enable the microcontroller to "understand" the high-level language.

The standard Arduino IDE uses the specific compiler for the target microcontroller to translate the C++ source code to machine language. The resulting binary commonly runs on this target microcontroller only.

The bootloader just implements the protocol. In general, it is completely unaware of the meaning of the transferred data.

Microcontrollers in general use different processors with possibly different machine languages, contain different kinds of memory of different sizes, include different sets of different peripherals. But you know this for sure. You need to write and compile your source code for the specific part you're targeting.

Yes, you can use ATmega328P for a consumer product, as Michel already said.

You need to take the common measures that you take with any part of your product, though.


Processing is just Java.  If Java can do it Processing can do it.

And Java can do it.

Just ask Google about the Java ProcessBuilder class.


Adafruit esp32 Feather Failing to compile

So it turns out the problem is that you're using the esp32 1.0.1 library provided by espressif. I'm assuming you're using the Arduino IDE board manager URL: https://dl.espressif.com/dl/package_esp32_index.json

To fix this, don't use 1.0.1. Use 1.0.0! Remove 1.0.1 and install 1.0.0. That should get it to compile properly without the uart, app_main errors.


Vin is only rated to supply at most 1A due to the reverse polarity protection diode in series from the barrel jack to the Vin pin.  You try and draw 1.7A thru that and you may smoke it.
The Vin header is also only rated for 1A.

Connect the motor to the supply directly. The Arduino Gnd must also connect to the supply.
R2 limits Arduino IO pin current to a safe level. R1 keeps the MOSFET off while the Arduino boots up. Diode dissipates motor generated current when the MOSFET goes from On to Off. The RFP30N06LE looks to be rated for full turn on with Vgs of 5V, and Rds of 47milliohm, that part should be ok to use.

Powering the Arduino from the same source as the motor may cause issues. If you can power the Arduino from USB or a seperate battery pack and not the same 12V that powers the motor, that will probably yield better results, especially if the 12V droops at all under heavy loads from the motor. That could cause Arduino resets.

simulate this circuit – Schematic created using CircuitLab


How can I connect an ultrasonic sensor to my Arduino motor driver shield l239D when I don't have any space left?

you might have noticed that there are spaces for analog pins on the shield. All of those are free so you can connect your ultrasonic and IR sensor there. Talking about digital pins, some are free but some are not. So it is better to use the free analog pins instead of bothering about digital pins unless necessary. And your sensors will work fine on those analog pins


Using SIMCOM SIM800 as a Bluetooth SPP Client

By default i see that the Android handset i used did not have SPP profile enabled. You need to open a App which enables the SPP profile to be advertised. Then after that you can get that in AT+BTGETPROF list. I made a tutorial for this, Have a look here,

https://youtu.be/zdQb8r2xRK8

and

http://www.raviyp.com/embedded/215-sim800-series-bluetooth-at-commands


Arduino Micro project with Bluetooth low energy

I have started to look at the Arduino Uno schematics, which are free on the website. To make an Arduino is very simple, just need the chip, crystal, a few capacitors and that's it.

Try to copy the same schematics then add the Bluetooth to the RX and TX pins, but be careful about the 3.3V as you don't want to fry your Bluetooth module :)


Deep sleep mode for the Uno without complicated circuits?

Forget using an Arduino Uno if you want to do low power (less than 10 mA standby). There is too much extra circuits (LEDs, Voltage Regulators, etc) to allow that.

See for instance, https://www.gammon.com.au/forum/?id=11497

With an Arduino Pro Mini it is possible to achieve low power after removing the Power LED and cutting the Voltage Regulator.

The hardware/software support for low power cannot really be used before the board is design for that.

Cheers!


What is more power efficient: GPRS or SMS for a GSM sim Arduino application?

Looking at it logically SMS is probably the most power efficient method.

The thinking is this:

With SMS:

The shield sits there connected to the mobile network doing nothing much
An SMS is sent by you which travels through the mobile network
The SMS is sent from the mobile network to your GSM shield which then wakes up and does things with it
The shield sits there connected to the mobile network doing nothing much

With GPRS:

The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service and sees a request is available
The shield downloads the request
The shield acts on the request
The shield goes back to querying the on-line service
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
... etc ad nausium ...

As you can see with SMS the onus is on the mobile network to send the data to the shield, whereas with GPRS the onus is on the shield to keep querying an on-line service to see if there is any requests to handle. There is no way of you sending data to the shield directly (indeed, most GPRS services include at least one layer of NAT gatewaying). So your shield has to be active all the time and constantly looking at something online - not only power hungry, but potentially financially expensive too.


Is it possible to program Arduino UNO with USB/TTL adapter withouth connection Vcc

Is it possible to program Arduino UNO with USB/TTL adaptor without connecting the Vcc and GND pins (RX/TX and DTR only.)

No.
As a minimum you need to add ground as well - even if the Mac is battery powered.  Serial port signals are ground referenced so removing the ground would prevent operation.

Operation is possible without deriving Vcc from the USB port, but you will then need to derive Vcc from some other source.

If connecting ground alone causes your Mac to reset you have a serious system problem which may damage your Mac and which possibly may be dangerous to you.

Presumably you are NOT using an external power supply for the UNO.
In case you are: If the power supply for the UNO is AC mains powered it should be connected to the same mains outlet as the Mac. If the programmer powerpack is intended to be grounded but is not powered from a grounded socket AND using a 3 wire mains lead (ie with a ground pin and wire) then it s possible in some cases for the programmer to float at half mains voltage with a high impedance capacitive connection to mains. This is not usually dangerous to people but can cause minor nuisance shocks. It can destroy equipment (ask me how I know :-( .)
If you have a DMM (digital multimeter) set it to an AC voltage range greater than your local mains voltage and measure the AC voltage from a known ground (such as a water tap in most cases) and the programmer power supply (either wire or jack terminal). If you measure a voltage of about 50VAC with 100 VAC mains or about 115 VAC with 230 VAC mains then the power supply MUST be operated with a 3 wire mains cord and grounded power socket OR a ground lead from mains ground to power supply output ground.

If the Mac is battery powered and you have reset problems then something is wrong with connections or signal levels. You may be feeding voltage back onto the USB lines or loading the too heavily or ... ?


How to set counter for two ultrasonic sensors?

Just get the time when the first pin goes high, and get it again when the second pin goes high, and subtract them to find the difference.

This is an example of how you could do that. It doesn't contain anything about the ultrasonic sensors, just how to measure an elapsed time between two pins going high.

#define echo1 3 // Set your echo pins here
#define echo2 4

unsigned long startTime = 0;
unsigned long endTime = 0;

void setup() {
}

void loop() {
    // You can do stuff here

    // If the first sensor goes off
    if (digitalRead(echo1) && (0==startTime))
    {
        // Remember the time this happened
        startTime = millis();
    }
    // If the second sensor goes off
    if (digitalRead(echo2) && (0==endTime))
    {
        // Remember the time this happened
        endTime = millis();
    }

    // If we have both start and end times
    if (0 != startTime && 0 != endTime)
    {
        unsigned long duration = endTime - startTime;
        // Do what you want with "duration"
    }

}


How to combine Leonardo with Ultrasonic sensor?

What is your hardware setup?

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

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

I would recommand having an iterative approach:

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

That is divide and conquer: understand each bit before trying to assemble them.

THEN, and only then, you will have a better understanding of the different part of your project. You will then be able to formulate an overview of your project goals, and how you can do it. That is, start documenting your project before it is done: doing so will force help you to have a clear idea of what it is that you're trying to achieve... and thus how to achieve it.

But yeah, the overall project might look something like this:

// Ultrasound distance sensor #1, hooked to the arduino with xxx and yyy; generates movement along the x axis
// Ultrasound distance sensor #2, hooked to the arduino with zzz and ttt ; generates movement along the y axis
// Something for the wheel? The buttons?

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

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


Why do we need to amplify the signal of an electret?

Arduino (or any chip that uses ADC for that matter) has a resolution. For example, arduino analog read divides 5V to 1024 levels. A.k.a 0V -> 0, 5V->1024. That gives you 4.8mV per level.

Now assume that you want to read the voltage fluctuation of a very low voltage power supply that fluctuates from 0 mV to ~8mV. What does the arduino read? You'll see either 0 or 1. So basically, you just can't successfully read that low voltage with your current setup.

Now, if you use an analog OPAMP and amplify that signal to 5V, (0mV->0V, 8mV->5V) then you can use all 1024 levels available to you, provided by arduino.

That's why you need to amplify the signal.


Arduino Christmas light project with dimmer

I can think of a couple of ways to approach this:

Use a DMX dimmer, something like this 4-channel dimmer, or
Use an household X10 dimmer.

DMX is used for stage lighting and there is some information on controlling DMX devices with an Arduino in the Playground where there is also some information on the hardware interface and shields, it looks pretty simple. DMX is a differential RS485 interface.

X10 is used for home automation, the signaling is done over the AC line. There is some information on using X10 and an Arduino library in the Tutorials.

Both seem like viable approaches, if you're working in a theater it is likely that they might already have DMX equipment and it would be as simple as hooking up to the gear in the house. Then you'd only need to add a shield or build the interface hardware.


What is the theory behind the Arduino UNO being able to create AM waves at 800 kHz

Strictly speaking it's not AM, it's OOK (On-Off Keying) which just turns a carrier frequency (800kHz PWM, 50% duty cycle) on and off.

Many cheap 443MHz (eBay) modules do the same thing - turn the carrier frequency on and off.

The presence of the carrier frequency is seen as a logic 1 and the absence as a logic 0.

The fact that it's using PWM to generate a square wave means that the "cleanliness" of the signal will be incredibly horrible. You really want to get the carrier frequency as close to a pure sine wave as possible. A square wave has lots of harmonics at 3x, 5x, 7x, 9x etc the frequency. So your 800kHz signal will also have a 2.4MHz signal, a 4MHz signal, a 5.6MHz signal and so on, each at a lower level. That causes interference in other signals.

To understand more about why it works you first have to understand radio transmission theory, and that's not something we can cover on an Arduino site (it's an entire college course all by itself).


I have the error: expected unqualified-id before 'if'

The error is occurring because you have 2 if statements outside of a function. You could move them into the ping() function which would fix the error but there seems to be a logic error with the 2 if statements as well.

If distanceCm is 20, both if statements execute one right after another, so I doubt you'll see the LED turn on. Perhaps an if/else might work.

if(distanceCm < 21){
  digitalWrite(13, HIGH);
}
else{
  digitalWrite(13, LOW);
}


Confusion with two Serial.begin() function calls

It looks like a mistake, as Chris says.  I can't tell you what will happen but my guess is it will work at 9600.

I would recommend that you delete one of the lines to avoid further confusion.


Do you mean something like a sensor shield? They have three pins (Vcc, GND, signal), not four (because servos have three pins), but they are designed for connecting a large number of servos

These can be found easily and cheaply all over the internet.


I see two issues in your code. I cannot say for sure they are related to
the problem you experience, but anyway:

The Readline parser's line terminator defaults to "\n", whereas
Arduino's Serial.println() uses "\r\n". In order to get the line
terminators match, you should invoke the Readline constructor with
{ delimiter: "\r\n" } as an argument.
Piping the flow through the parser returns a new stream. You should
watch for data events on that stream rather the original port.

Thus I suggest you try:

const parser = new Readline({ delimiter: "\r\n" });
const parsedStream = myPort.pipe(parser);

myPort.on("open", onPortOpen);
parsedStream.on("data" , onData);
...


The PWM looks ok but I'm unsure of the analog signal.

The “analog signal” looks like the PWM smoothed by a first-order
low-pass filter. It still has some oscillations, 584 mV
peak-to-peak. If you can tolerate that, then it's perfectly fine. If
not, then increase the time constant of your filter.
A first-order low-pass filter behaves, in its stop band, like an
integrator. Thus, a square signal is turned into a triangle. You are
seeing exactly the expected behavior.

The oscilloscope is set to defaults

There are no “default” settings in the oscilloscope. You probably used
the “autoset” button instead. This button tries to find some settings
that let you see something on the screen. I mean, some kind of signal,
not just straight line. If the signal is almost flat, the autoset will
increase the gain until you can see it is not flat. In this case, it
increased the gain by a factor 10 (200 mV / division instead of
2 V used previously). It also added a negative offset in order to
avoid the trace going out of the screen. See the small pentagon on the
far left with a “1” inside? On the first picture this tells you where
the zero (the reference potential) is relative to your signal. On the
second picture, the polygon pointing at the bottom of the chart tells
you the zero is off-scale.
If you want to really appreciate the smoothing action of the filter, you
have to look at its input (the PWM signal) and its output (the “analog”
signal) using the exact same settings. Connect the input, hit “autoset”,
and look. Then connect the output, do not change the settings (do not
hit “autoset”) and look at the output.
Better yet: forget the autoset button, adjust the settings manually and
mind their values.
Better yet: as you have a two channel scope, display both signals
simultaneously, using the exact same settings on both channels.