esp32 crashes when trying to dereference a pointer value

Ah, one of my friends pointed out the issue. It's a scope snag:

chunks is allocated on the stack in get32BitInt By returning a pointer to chunks, you are pointing to memory that is deallocated. Think of it as pointing to a member variable of a class that has already been destroyed
when you try to dereference deallocated memory, bad things can happen. usually in debug the compiler makes sure you fail hard
the easiest way to test this is to allocate chunks outside of that function and pass it in as a reference

So yeah, I was allocating memory within the scope of a function and then blowing that memory contents away when that functions scope ended.
I refactored my code to move the array outside of the scope of the parsing function and passed the pointer in to the parsing function to get populated:
void get32BitInt(WebsocketsMessage message, uint32_t *chunks)
{
  Serial.println("--------------------------------");
  Serial.println("raw parse:");

  std::string raw = message.rawData();

  // uint32_t chunks[message.length() / 4];
  int chunkIndex = 0;

  for (int i = 0; i < message.length(); i += 4)
  {
    uint32_t chunk = 0;
    for (int j = 0; j < 4; j++)
    {
      chunk <<= 8;
      chunk |= raw.at(i + j);
    }
    chunks[chunkIndex] = chunk;
    chunkIndex++;
  }

  Serial.println("parsed chunks:");
  for (int i = 0; i < 11; i++)
  {
    Serial.print(chunks[i], HEX);
    Serial.print(" == ");
    Serial.println(chunks[i], BIN);
  }

  Serial.println("--------------------------------");
}

void addWebsocketListener()
{

  client.onMessage([&](WebsocketsMessage message) {

    uint32_t gameFrame[message.length() / 4]; // *try moving gameFrame out of scope
    get32BitInt(message, gameFrame);

    Serial.print("game frame address: ");
    Serial.println((int)&gameFrame);

    Serial.println("storing first 32 bit integer in a variable");
    uint32_t firstNumber = *gameFrame;

    Serial.print("game frame first value: ");
    Serial.println(firstNumber, HEX);

    Serial.println("printing frame:");
    for (int i = 0; i < 11; i++)
    {
      Serial.println(gameFrame[i], HEX);
    }
  });
}

And now my controller isn't crashing :D

And now I understand scope when dealing with pointers a bit better :)


What Arduino boards would be compatible?

As one can see from the pinout description page (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/pinouts):

So this board is literally designed to be powered by 3.3V and 5V and have compatible logic levels for both these voltage ranges, which is what every Arduino known to me and the Raspberry Pi use.

Furthermore, there is also Arduino Code (https://github.com/adafruit/Adafruit_LSM9DS1)  which is compatible with pretty much every Arduino Core and Raspberry Pi Python code (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/python-circuitpython).

So by means of voltage levels and platforms, this board is highly compatible with everything out there that is either 3.3V or 5V powered and has a SPI or I2C peripheral.


Is it possible to make 4hz readings with the DS18S20 temperature sensor?

I would expect some variations in temperature, but I would not say that is a problem caused by the 4Hz readings. You can test my assumption by reading every 3 seconds, does the temperature value change or is it still the same?

I see two potential problems:

your DS1820 is defect.
from your code I assume that you use parasitic power. In that case the chip consumes power from the data wire ( one wire ;-) ) through a pull up resitor (~4.7 kOhms). If you do not provide a special handling, to drive more current while the DS1820 is converting or copying data to EE or from EE memory to the scratchpad, then there will be (most likely) voltage drops.
Then the Temperature conversion will not happen and you read the old value from the scratchpad in your read cycle.

You can test point 2 by adding VCC to the DS1820, and do not use parasitic power.
If that is your problem, you can fix it with a switching FET Transistor, that provide more current (see DS1820 Datasheet from Maxim) or by using an additional VCC wire.


analogRead values all over the place, while measuring light

The problem you are facing is that the output of the LED is too high impedance for the ADC to work reliably.

Basically the LEDs can't produce enough current to charge the S&H capacitor properly, and on top of that the LED doesn't act as a resistive load when not forward biased, so the input is basically floating and picking up noise.

The best cure is to add a voltage-follower buffer with incredibly high input impedance in front of the ADC input.

By high impedance I mean something measured in the 10s to 100s of TΩ. Something like the OPA355.


Using TFT touchscreen with Arduino Uno R3 via I2C

A TFT touchscreen actually normally consists of two completely separate items:

TFT Display
Touchscreen and optional interface chip

While you can get both of those together on a board with both using I2C it is quite rare. It is far more common to find boards with either SPI or 8- (or 16-) bit parallel interfaces for the TFT screen, and SPI (or sometimes 4 channel analog - a direct connection to the touch screen itself) for the touch screen.

I2C is really only used for very small screens. The slow speed of the I2C protocol means that updating the display is very slow, which results in very poor performance for anything bigger than, say 128x128 pixels. It's usually used for things like small OLED displays rather than larger TFT displays.

Touchscreens with I2C are normally capacitative rather than the cheap resistive, so tend to be a little more expensive and harder to work with. The most common touch screen chip, the XPT2046, is SPI.

Fitting everything you want to do into an Uno is going to be tight, and not just because of the number of IO pins a display usually demands. Working with displays usually means lots of graphics (icons, symbols, fonts, etc), and that means a lot of flash memory. A Mega2560 would be a better choice for that if you want to remain with 8-bit.

However better graphical results would be obtained using a more powerful board. The Arduino Due, with its 32-bit ARM chip, would allow you to do much more graphical manipulation, such as drawing nice graphs etc.

My personal preference, though, is to use a PIC32 based board and the chipKIT core, coupled with my own powerful DisplayCore library. But then I'm biased.


Receiving message from arduino through wifi

Download the ESP8266 extension for the Arduino board in Arduino IDE,desktop. Then select the example code for ESP8266, use the Server example. If you wanna access your board outside your home then you need to open a port in your router.


Arduino esp8266 interferes with analog sensors

You read the analog pin of the esp8266, not the analog pin of the Seeeduino.


Can I make the BT module disconnect with a BT module and connect with another in the code?

Send AT+ROLE=1 to BT module to set module into master role.
To set module back to slave mode, send AT+ROLE=0

Also check this video, you have source code in the description. It will help you understand how to do it.


Yes it is possible:

With a different bootloader.

You need something which will erase the old sketch from the chip, read the data from the SD card, and write that into the flash of the chip. The only thing that can do that is the bootloader or some external device (another ATMega328p chip which we have to pretend you don't have).

Due to the way the architecture works you can only execute code out of the flash, so you need to program your sketch into the flash somehow. And that is the role of the bootloader.


First off you need to convert your signal's units from analog -> voltage. Do this by using the following equation. I've modified your code so you can copy and paste it into your IDE.

float volts = analogRead(A3) * ( 5.0 / 1024.0) ;

Hope this helps! Good luck!


High power consumption of ATmega32u4 when connected to iOS device

The major difference between ATmega32u4 and ATmega328 is that the former has USB functionality built in, while the latter requires an external USB to UART chip. When such UART chips go through enumeration, they will tell the host that they only consume 100 mA or less, because they have no idea what else you have on the board. ATmega32u4 however can potentially consume up to 200 mA (sinking 100 mA through each of the IO banks). Maybe it's requesting that current from the host when you connect it, and your phone refuses to power up a device requesting more than 100 mA of current.

You can connect your controller to a computer and check USB properties to confirm this.


ESP8266, I am trying to establish a SoftAP and I cant seem to get the WiFilocalIP function to give me my IP

The WiFi.localIP() is a function of the STA. To print the IP address of the SoftAP, use WiFi.softAPIP().


Self answering a Intercom and playing louldy for person to response

Let's try to break it down to several components:

Interfacing with POTS (Plain Old Telephony System):
There is a nice article by Joe Doll describing how to interface an Arduino and POTS. POTS involves high voltage during both idle and ringing time (48 V DC, superimposed 90 V AC) and the circuit itself is mostly analog. You can find the required parts and their values in his article, which goes down into the nasty details in a spectacular fashion. Here is the analog circuit, involving the Arduino, from his post:

Consider that there are other projects performing similar task in a different manner, like this one, and this one which specifically explains how to record sound from an old rotary phone.

Play/Record sound from Arduino Mega 2650:
There are many projects that describe how to Play or Record sound using Arduino. Most involve a SD card to store the wav files. There is also the option of an MP3 shield, that comes with a pre-built SD card slot, such as this one. They are fully documented and are easy to interface with.
Code that encapsulates the Logic:
Here you could decide how many times the Arduino should play the recorded name, and what happens if the user won't answer. The disconnection will be done utilizing the POTS interface you created in bullet #1. In addition, you should handle the logic of what happens when the user does answer. It is not clear what you mean by 'receiver', but if you plan to have a remote extension or similar, some extra work will be required.

As a side note, it might be easier to create/re-use a walkie-talkie kind of wireless communicator, accompanied by an Arduino, to signal or broadcast the names of the people called. This might not include reuse or interfacing with the current intercom device, but by thus I believe it will make development easier and faster.


Arduino potentiometer (external power) with amplifier

It's impossible. The pot is most probably acting as a passive variable attenuator. As such the top end will be the incoming audio signal, the lower end will be ground, and the wiper will be the attenuated incoming signal. There's not a lot you can do with that.

You would need to replace the pot with an equivalent triple pot (if such a thing exists) and have one third of it connected to the Arduino.  The pot you have at the moment is a dual pot, and a log taper at that.

Alternatively adding some kind of quadrature (motor) encoder to the shaft of the pot may be a possibility.


The reliability data is typically not in the product datasheet but in pen whitepapers. Generally speaking life span goes down exponentially as temperature rises. For some high temperature semi conductors ( designed specifically for high temperature applications) you are talking about hubdreds or thousands of hours at rated temperatures.

That should give you some sense as to what to expect.


Connect optocoupler 4N35 to Arduino Uno to control LED light strips

Can i connect the optocoupler's emmitter to the arduino ground?

Yes. Don't forget to either enable the internal pullup on the GPIO pin or use an external pullup on the collector.

  If i power the arduino with 12 V D.C power source connected to the D.C jack, can i give the power to the LEDs also using the V-in pin of the arduino?

Not at the current rating you are talking about, no. The header is only rated for 1A, and the diode on the barrel jack input is also rated for only 1A.  You would need to split the LED power off from the incoming power before it goes into the Arduino.

The way you have your MOSFETs wired at the moment is wrong. The moment you turn one on it will let the Magic Smoke escape. You are using them to short circuit the LEDs, which is very very bad.

Each one should be wired in series with the LED between the cathode and ground:

simulate this circuit – Schematic created using CircuitLab


As far as I know, the 1-wire library you linked in your question allows only to act as a master, not a slave.

I've just released a library to turn an Arduino board into a 1-wire slave, here: https://github.com/neuoy/OneWireArduinoSlave (edit: moved here https://gitea.youb.fr/youen/OneWireArduinoSlave). I use it in my custom home automation system, and it works flawlessly in my setup (the 1-wire master, a DS9490R, is connected to a laptop via USB, and also provides power to the Arduino, which is an Arduino Uno). The library handles low level details: match rom, byte send and receive (which is actually quite hard to get right, mostly impossible without a logic analyzer). The rest is up to you.

It's entirely implemented with interrupts, all communications are performed in background, you can execute other code as usual, in parallel, and are notified by callbacks when bytes are received etc. Sending bytes to the master is also asynchronous.

I also know at least one other library exists, https://github.com/MarkusLange/OneWireSlave, as commented above by Ryu_hayabusa. It didn't work for me (don't know if it's because of my hardware setup or for another reason), but it definitely work for others, so also worth a try. It seems this library is not implemented with interrupts, so your program is blocked while waiting for master activity (which is perfectly acceptable in a lot of scenarios).


Arduino mega 2560 Stacked with Ethernet/SD card Shield Heat up

the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.
  So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?

Well you're right in being a bit paranoid. And temperature building up is very likely to mean you've got a short somewhere, it might be a bad solder or a component that fails (like a cap that conducts).

So you've got to isolate the issue:

Isolate the faulty board: whichever board is getting hot, it might be that one that has a failure or the other one ruining it

you need to try the shield with another arduino (whatever version it is) and see if the issue is replicating
then you need to try the arduino you were using with another shield running on ICSP (like another ethernet shield, or an SDCard shield), which will confirm the hypothesis that only one component of the two is failing.

Once you've isolated the board, you need to isolate the component.

you first have to isolate which component is building up heat.
If you've got access to a thermal camera, it's a good idea to use it.
If not: start locating the area where heat is building with your finger, and then test each component of the area with a thermometer (like the ones you plug on a multimeter, or simply a "meat" thermometer for cooking).

Once you've isolated the component, then look it up on the schematics and layout, and lookup all connected components. Either that component or one on the track is failing, or there's a short on that track.

If the solution is not obvious, you can come back on Stack Exchange (get on the electronics QA site with your results), and some EE expert will help you find out what's wrong!

HTH


What Driver IC to use for 40v 2amp DC motor?

I am assuming since you did not state anything differently you simply want to turn it on or off and possibly PWM to control speed of the motor.  By far the easiest way is to simply use a N-Channel logic level MOSFET.  Connect the Arduino pin of your choice through a 51 (1) ohm resistor to the gate of the MOSFET, also Connect a 10K (2) resistor from the same microprocessor (Arduino) pin to ground.  The "Ground" low side of the 40V power supply needs to be connected to the low side of the Arduino.  The low side of the 40V power supply must be connected to the source of the MOSFET.

Connect the motor from the plus side of the 40V power supply (this will be removed for testing) to the Drain of the N-Channel MOSFET. Last and very important place a diode rated at least 2 amps at 60 volts from the positive side of the poser supply (cathode of the diode, with the band) to the Drain of the MOSFET (anode, no band).

Carefully check your wiring; if it is ok you are ready to test it.  The safest way is to use a led with a 510 ohm in series with the cathode on the Arduino +5 with the positive side of the 40v power supply disconnected.  The anode side connects to the drain of the MOSFET.  When the motor is turned on the LED will light, if it does not reverse polarity of the LED.  As tempting as it might be do not leave the LED connected to the Arduino when the motor is connected.  Up the value of the resistor to about 5.6K and connect it across the motor, it will light when the motor is on.

This helps dampen oscillations
Since the Arduino initializes with all pins as inputs this can drift high, this solves that potential problem which would cause the MOSFET to turn on.
For the MOSFET you need at least 60V with a 10A rating.  This should work with a small heat sink.  If you go to a higher amp rating on the MOSFET it will operate cooler.

Output of Arduino goes to 10K to ground and to a 51 ohm resistor (1/8 W or larger)
The other side of the resistor goes to the gate of the MOSFET.
Ground of the motor power supply, the Arduino and the Source of the MOSFET are connected together.  The 2A diode is connected with the cathode (no band) to the drain of the MOSFET, the cathode (band) is connected to the +40V.  The motor connects from the +40 to the Drain of the MOSFET, reversing the leads will probably reverse motor direction.

Good Luck,
Gil


As the comments already stated: No, not possible. For multiple reasons:

USB is a master/slave protocol. The slave (here the Arduino) cannot do anything without the master. It can just expose it's data endpoints and hold data ready to read at these endpoints for the master or wait for data from the master on these endpoints. When the application on the PC is not programmed to speak over USB, you cannot get the data over USB.

Even directly on the PC you cannot simply extract data from a different program. That would be a very huge security risk. Even more, when just initiated via an USB device. There are USB devices, which use certain behaviors of some OS's (like auto execution of specific types) to install a virus on the PC. But even then you cannot "just read" the data. It would be way more elaborate and not possible with a simple Arduino, thus off topic here. (And you might frown upon hacking your own PC this way)

From our point of view (means leaving the hacking off limits), I would aggree with Majenko in the comments. Using the visual output is the most viable and easy solution, though your results might vary.
For that you would need a camera pointing at the screen (check if you get a good image. It might be distorted due to slow refreshing...) and use a Raspberry Pi or similar to connect it. On the Pi you can then take pictures of the screen and use an OCR tool, which will read the text from the image. Then you need to extract and structure the relevant information. (Maybe it will be easier to create subimages in your program and let the OCR tool run over these to distiguish between the different data parts). Results will hardly depend on the quality of the image. If you can live with an additional program running the PC, you could instead make the images of the screen as screenshots, which will be way better quality. Though at that point you can also put the rest of the logic on the PC and just remove the Pi.
This way will still be hard to do for a beginner, but possible.


Testing for string equality with '==' is a mistake: https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c  The '==' operator on strings will compare the pointers to the strings rather than their content and likely always fail the if() tests.

To loop and block on the last bit, if that is what you mean, you might try:

   int btncheck;
   ...
   while(btncheck = digitalRead(buttonpressed)){ // wait for button
      if(strcmp(daction.substring(0,5),"delay")){
         delayMethod(indaction);
      }
   }  // blocked until btncheck == LOW
   if(strcmp(daction.substring(0,5), "print")){
         printlnMethod(indaction);
   }

This has the blocking on non-pressed button feature, but also has the same logic as the original.  If the string equality tests do not match, it appears you want to do nothing and quickly pass on.

To loop buttonMethod(), put it in a loop:

while(1)buttonMethod(string);

If you want to condition on getting the button press that corresponds with the string, I'd make buttonMethod return a value and loop conditionally on that:

int buttonMethod(...
    int retVal = 0;
    ...

  if(btncheck == LOW){
     retVal = 1;
     ...
  }
  return(retVal);
}

...
while(!buttonMethod(result[i]));  // wait for the button


Running stepper motor for specified no. of turns with Arduino?

Here's a post that will get you started.  It uses a Teensy 3.5, but the motor driver code will be the same. You will also need to modify the low-level driver functions to match with the actual motor driver module being used.  However, if you use a Teensy 3.5 and the L298N motor driver, you should be able to use the program with little or no modifications.


Connecting Arduino Uno WiFi Developer Edition to the Internet

Do you have access to the Webgui?

with the Webgui you can configure the wifi settings.
you do not need to upload sketches for this.
It is a good test if there is no defect.

Connect your PC Wi-Fi or with your smartphone directly to the Aduino uno wifi.
Start your browser and type in the following IP: 192.168.240.1
and now you should see the WebGUI.


Is it possible to recover an Arduino if it does not wake up after putting it to sleep

Not sure what you mean by "using the watchdog to put it to sleep". You can sleep with or without the watchdog enabled, and you can even use the watchdog to both wake you with an interrupt and also reset in case of a lockup. Check out section 8.5.2 in the datasheet...

  If WDE is set, WDIE is automatically cleared by hardware when a
  time-out occurs. This is useful for keeping the Watchdog Reset
  security while using the interrupt. After the WDIE bit is cleared, the
  next time-out will generate a reset. To avoid the Watchdog Reset, WDIE
  must be set after each interrupt.


You are running a wireless TCP stack, an SD card interface, and a web camera with some sort of motion detection, on a less than $20 computer?  I think you should congratulate yourself and move on to the next project.

I believe you are asking too much to add more to it. At $20 a pop, I would think about adding another UNO if you really do want to add more functionality. Let the 2 talk via serial, with one processing the video, the other processing the wireless.  The TCP part uses a considerable amount of resources, both memory and processing power.


Problem with tachometer using attachInterrupt and servo

Your problem is probably that of interrupt conflicts.

The 8-bit Arduinos don't have any concept of interrupt priorities. When one interrupt routine is running it is impossible for any other interrupt routine to run until that first one has finished.

Interrupts have a "natural call priority" in that lower numbered pending interrupts will be called in preference to higher numbered ones, however that doesn't mean that they can interrupt each other.

The problem here is that the servo library uses a timer (and its associated interrupt) to generate the waveform.  That uses a lot of interrupt calls running all the time - and while they are running your external interrupt can't be called - at least not until the currently executing timer interrupt completes, at which point your external interrupt handler will be called since it is the highest priority.

So the results you get with all that delaying are pretty meaningless.

So what can you do?  Well, there's a number of options - all of which involve not using interrupts.

You could not use the Servo.h library and instead reconfigure the hardware PWM to the right frequency and use that for the servo
You could use one of the timers with an external clock source to count your tacho pulses (I think Timer 1 has that ability on the Uno)

Or even better: do both.  That would give you the most efficient system whereby the main CPU is only involved in getting the count from the timer periodically, and adjusting the PWM value for your servo. The rest is then done by hardware completely asynchronously.

Of course, for this you will want to study the datasheet so you know how to configure the various hardware modules.


I think your commands are a little wrong. Let's look at them:

LcdWriteCmd(0xAE); // LCD set display enabled

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

LcdWriteCmd(0x21); // LCD set power COntrol

0x21 is 0b00100001. That command is 00100### where ### is the VLCD resistor ratio. That is being set to 2/8. ((# + 1) / 8).

LcdWriteCmd(0x14); // LCD bias mode 1:40

0x14 is 0b00010100, which is command 0001#### which sets the column address MSB. Quite why you're doing that I don't know, but that command has nothing to do with bias mode...

LcdWriteCmd(0xA2); // LCD basic commands

No, 0xA2 / 0xA3 sets the bias ratio set, which selects the bias from one of two groups of biases depending on the current duty. This is the default value.

So not only are you not configuring the screen correctly, but you aren't even then trying to put anything on the screen to see if it's working or not.

I suggest you work from the provided example code:

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

The "Initial" function sets the sequence of operations:

SET_ADC();
CLEAR_SHL();
CLEAR_BIAS();
Power_Control(0x07);
Regulor_Resistor_Select(0x06);
Set_Contrast_Control_Register(Contrast_level);
Initial_Dispay_Line(0x00);
DISPLAY_ON();

The main commands are defined at the top of the file:

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

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

Write_Instruction((0x28|vol));

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


Is there some sample code for operating a servo with an Adafruit Motor Shield?

On the Motor shield the servo headers are directly connected to pins 9 and 10 (I think 9 is servo 2 and 10 is servo 1).  So you can use the standard servo examples using pins 9 and 10.

If you need to power the servos with an external power supply you must cut a trace on the back of the board -- the silk screen tells you where to cut.  Then you need to connect power to the "Opt Servo" input.

The power to the servos is not changed by the power jumper used for the DC/stepper motors.


PWM using timer3 for servo control won't generate any output

I can see nothing wrong in your program except this:

DDRB |= (1<<DDB7);      // Output pin 5 OC3A

This is setting pin PB7 as an output, whereas
digital pin 5 (OC3A) is PE3.


Why is this RISING interrupt repeatedly triggering?

Turns out the short answer is that I'm still not great at using an oscilloscope.

Longer version is that the noise was very visible at smaller time scales. A filter capacitor had come disconnected from the breadboard in a way that was hard to see, and that was causing a whole bunch of noise. Replacing it fixed the problem.


I'll google it for you "AC motor speed control": google search

Short answer will be that it depends on motor. Frequency changer (or variable frequency drive if you need variable speed) is usual choice.


AT firmware upgrade in ESP-01 using Arduino UNO R3

Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware?

No, just connect RESET to GND to stop the MCU from running.

Does it going to affect Arduino Bootloader?

No.


Making WiFi hotspot for 3G network sharing controlled by Arduino

Not a chance, I am afraid (you were right not to buy things yet). Things like the 3G shield and WiFi shield don't work in the way that is needed for a WiFi hotspot like that. You're better off with a Raspberry Pi and a 3G USB dongle and run hostapd along with the other software needed for your project - things like apache, etc.

You may be able to do it with the Linux portion (OpenWRT) of an Arduino Yun with a USB 3G dongle attached, but it would be sluggish. Best to stick to something with enough processing to do what you want, which means a Raspberry Pi or similar.


to measure the time between the ON signal and OFF signal

Here's the catalog of errors I see at first glance:

const int CHANNEL_COUNT = 3;
Channel channels[CHANNEL_COUNT] = {
    { 2, LOW, 0, 0 },
    { 3, LOW, 0, 0 },
    //{ 4, LOW, 0, 0 },
    //{ 5, LOW, 0, 0 },
    //{ 6, LOW, 0, 0 }
};

You set up space for 3 entries but only fill 2.  Also, the Channel structure has 5 entries, not 4. You don't initialize the 5th (rose) entry (although it will be initialized to 0 for you - best to be explicit though).

for (int i = 2; i <= CHANNEL_COUNT; ++i) {
    pinMode(channels[i].pin, INPUT);
}

You start from entry number 2 (the third entry) and iterate to the 4th (non-existent) entry to set the pin mode of either undefined or invalid pins.

for (int i = 0; i < CHANNEL_COUNT; ++i)

You have only filled in 2 of the three entries. Yet you use the third as if it were filled in.

Serial.print(minutes);

If seconds is less than 60 then minutes is undefined here.

I would suggest changing your code so that Channel is a class and embed the code to manage that class within it.

Bonus Time

Here's your program re-written using a class. As an added bonus I have added automatic allocation of a channel number to each object as it's created.  To add more channels just add the pin number into the initialization list.

class Channel {
    private:
        uint8_t _pin;
        uint8_t _state;
        uint32_t _rise;
        uint32_t _fall;
        uint8_t _count;
        uint8_t _channel;

        static uint8_t channelCount;

        void display() {
            uint32_t diff = (_fall - _rise) / 1000;
            uint32_t secs = diff % 60;
            uint32_t mins = diff / 60;
            Serial.print(_channel);
            Serial.print(",");
            Serial.print(mins);
            Serial.print(",");
            Serial.print(secs);
            Serial.print(",");
            Serial.println(_count);
        }

    public:
        Channel(int pin) : _pin(pin), _count(0) {
            _pin = pin;
            _count = 0;
            _channel = channelCount;
            channelCount++;
        }
        void process() {
            int s = digitalRead(_pin);
            if (s != _state) {
                _state = s;
                if (s == LOW) { // Fell
                    _fall = millis();
                    _count++;
                    display();
                } else {
                    _rise = millis();
                }
            }
        }
        void begin() {
            pinMode(_pin, INPUT);
        }
};

uint8_t Channel::channelCount = 0;

Channel channels[] = { 2, 3 };
#define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

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

    Serial.println("Channel,Minutes,Seconds,Count");

    for (unsigned int i = 0; i < NUM_CHANNELS; i++) {
        channels[i].begin();
    }
}

void loop() {
    for (unsigned int i = 0; i < NUM_CHANNELS; i++) {
        channels[i].process();
    }
}


Link Arduinos over 5 acre laser tag field

You can use nRF24L01+

The chips offer:

Really high range with power amplifier (1km open field radius (776 acres if I'm right) , but fairly high power consumption 100-150mA @ 3.3V)
High range with PCB antenna (50-80m open field, low power consumption 14mA peak)
Low cost (0.8£-6£ a piece)
Many easy to use libraries available, possible to create a mesh network
High usable voltage range (direct Li-Po for example without step-up)


You don't really need a library for that chip. You just do a pair of SPI transfers with the CS pin low.
For example:
digitalWrite(pinCS, LOW);
uint8_t msb = SPI.transfer(0xFF);
uint8_t lsb = SPI.transfer(0xFF);
digitalWrite(pinCS, HIGH);

uint16_t val = (((uint16_t)msb << 8) | lsb);
val = val >> 2; // For 14 bit devices shift it twice. For 12 bit do it 4 times.


A MAC is usually (unless it is really old) running a derivative of Unix. I would open a console install and use "lsusb" to list out all the USB connected devices.
A (Linux) example of lsusb:
$ lsusb
Bus 001 Device 004: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port

I would do this with and with out the Arduino FTDI chip connected and look for the difference. This stackexchange question/answer contains how to do this on a MAC or use other MAC commands to do the same.  As pointed out in the comments the more native MAC command is:
ioreg -p IOUSB

Note, if you have fake FTDI chips there was a time when the FTDI driver that Windows ran would brick the fake FTDI chip. I think it would assign the vendor and device IDs both to zero. You should be able to see this with the "lsusb" command.


srcPath = C:\Users\mikep\Documents\MWPRobotics\Pilot\Pilot
bldPath = $(srcPath)\build
arduinoCmd = "C:\Program Files (x86)\Arduino\arduino.exe"
arduinoFlags = --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files --preferences-file $(bldPath)\pilotPrefs.txt
prefs = --pref sketchbook.path=$(srcPath) --pref build.path=$(bldPath)

deps = $(srcPath)\Pilot.ino $(srcPath)\commands.h $(srcPath)\publish.h  $(srcPath)\motor.h

pilot.hex : $(deps)
#   type $(srcPath)\Pilot.ino
    $(arduinoCmd) $(arduinoFlags) $(prefs) $(srcPath)\Pilot.ino

Apparently it is really picky about absolute full paths (contrary to the comments that say it is relative)


How to properly process large arithmetic

You're getting the same value every time because that is the value that is being calculated.

I think you have something wrong with how you have implemented your formula.  If you start from "answer = " and repeatedly substitute the variables with the formulae or values that make up those variables you end up with this:

  answer = (11.4 - (((4401 * 14.164) + ((((12404 - 4401)*(1-((14.3 - (12404 - 4401))/((14.3 - (12404 - 4401))+(12404 - 4401 - 1.8)))))/2) * 14.3) + ((((12404 - 4401)*(1-((12404 - 4401 - 1.8)/((12404 - 4401 - 1.8)+(14.3 - (12404 - 4401))))))/2) * 1.8)) / 12404)) / 22.65

There's nothing variable about that at all.

Your input value is being used to calculate batterymoment. batterymoment us being used to calculate totalmoment. totalmoment is being used to calculate wheelmoment. wheelmoment is being used to calculate cgwheels. cgwheels is never used for anything.


Is this the MusicPlayer.h that you have?  https://github.com/Seeed-Studio/Music_Shield

From the description it says:

  The music player reads data from SD card and then feed into the VS1053 chip via SPI bus. This is done in TIMER1's ISR with a interval of 2ms. This job has a high priority and uses the cpu exclusively. In the spare cpu time, player does some process control, like play/pause.

That's the same timer that Servo.h uses.  So the two libraries are not compatible.  You could try using ServoTimer2 library or rewriting this library to get the 2ms timer with Timer 2.


How to start particular event for particular time using millis()?

Use an extra boolean variable. Some use the previousMillis and make it zero to tell that the delay is not active, but please don't do that. Let previousMillis be the value of millis and use an extra boolean variable.

To start the millis delay, three things are needed: enable the delay, set previousMillis, and turn the led on.

To stop the millis delay, two things are needed: disable the delay, turn the led off. There is no need to do something with the previousMillis since the millis delay will be disabled.

const int ledPin =  LED_BUILTIN;

unsigned long previousMillis;
const unsigned long interval = 5000UL;
boolean enableDelay = false;

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

void loop()
{
  unsigned long currentMillis = millis();

  // Trigger the delay, I use analogRead.
  if (analogRead(A0) > 500)
  {
    enableDelay = true;
    previousMillis = currentMillis;
    digitalWrite(ledpin, HIGH);
  }

  // Checking the millis delay should be done in the loop.
  // This code is not inside the code to start the delay, but
  // at the same level as other code in the loop.
  if (enableDelay)
  {
    if (currentMillis - previousMillis >= interval)
    {
      enableDelay = false;
      digitalWrite(ledPin, LOW);
    }
  }
}

There are libraries that can do this. The above code is the basic way to make a millis delay. I have changed the variable "interval" to a unsigned long, because the other two (currentMillis and previousMillis) are also unsigned long. That makes it more straightforward. The currentMillis and previousMillis must be unsigned long, but it is okay if "interval" is a long.

This way of a millis delay can be used with a finite state machine. If your sketch has many states, and one of those states is to keep a fan or a motor on for some time, then you can use it. The variable "enableDelay" is probably not needed in a finite state machine, because the "state" variable tells if that specific state (with the millis delay) is active.


how to calculate correct resistor value to use with LEDs Potentiometer and other devices?

If the LED has a forward voltage of 2.2V and is rated for 25 mA, then you're correct that a 120 Ohm resistor should be OK. It's theoretically calculated as the voltage across the resistor divided by the desired current in the LED. (In practice, it's often more complicated than that, but that's a good starting point.)

It's important to note that not all LEDs are rated the same though. I imagine the 220 Ohm resistor was selected for the tutorial to provide a bit of a safety margin, as that should be OK for most LEDs a hobbyist is likely to use. If you don't have access to the full specifications then it's probably better to under-drive it. The LED might be a little dim, but at least it's unlikely to be destroyed.

Here's a useful online tool for calculating theoretical resistor values for one or more LEDs:

http://led.linear1.org/led.wiz

For other devices, the resistor values required can depend on a huge number of factors. The best thing to do is to check the datasheets. For some components (such as ICs), you'll often find an "Applications" section towards the back which shows various ways you might want to connect the item to an external circuit. If things like capacitors and resistors are required, it will often explain how to select the correct ones for a given situation.


Powering ESP8266EX with batteries and a voltage divider

There's a good reason why you can't do this.

When you power something like an ESP, the current it consumes will vary over time, as it does different things. For the purposes of current consumption, you could model the device as a resistor  whose resistance varies (greatly) over time. When it's in sleep mode with the radio off, it might be a 10k resistor. When it's active with the radio on full power, maybe a 30ohm resistor.

A potential divider divides voltage according to the ratio of the resistances. You are talking about putting your ESP in parallel with one of the resistors. Putting two resistors in parallel creates a new resistor with a resistance lower than either of the two.

If you want to calculate the resistance of two parallel resistors, it's R = (R1 x R2) / (R1 + R2).

What values would you choose for the resistors in the potential divider?  You'd have to go for values much lower than 15ohm in order for the 'resistance' of the ESP not to greatly affect the behavior of the divider - say 5ohm in total. This would mean your divider alone would draw a current of 1A from a 5v supply.

Fortunately, voltage regulators and buck converters are easily and very cheaply available. I recently bought a pack of five 3.3v regulator modules from China, delivered for less than £2.

Alternatively, you can create a reasonably stable supply from a reference voltage with just a single NPN transistor, but I don't know offhand whether it would be good enough for this application.


How to run my buzzer for few more seconds after switching off

If you are using a digital buzzer, you can do:
digitalWrite(buzzerPin,HIGH);
delay(1000);
digitalWrite(buzzerPin,LOW);


toCharArray is alias for getBytes. getBytes is documented as "Copies the String’s characters to the supplied buffer." You did not allocate the memory for the copied characters.

the right use of 'getBytes' and 'toCharArray' is

char buffer[BUFF_SIZE];
str.getBytes(buffer, sizeof[buffer]);

note: getBytes functions sets the terminating zero of the c-string in buffer


Networking multiple Arduino Megas and updating their programs from one master

In principle, yes, you can do it. It's what existing bootloaders do -- they take code over the serial port, or USB, load it to flash, and then branch to it. Not to mention OTA.

So yes, you can modify the bootloader to use different pins, talk rs485, come up with code-integrity checks, specify particular bit patterns to signal "reboot" or "now load new code", and so on. If you have enough flash, you can even keep two copies, a working and a new, like most OTA code does.

I am not aware of a ready-made library that does that. If I wanted to roll my own, I would start by studying the OTA code.


Why SD.exists() only looks for inside media/realroot on Intel's Galileo?

The Intel Galileo runs Linux.  Most Linux distributions (auto) mounts media under specific directories like "/media".  So this is likely not so much a feature of the Arduino paradigm but of the Linux paradigm.  If you really want to change this you will probably have to research how Linux (specifically how the Intel Galileo version of Linux) auto mounts media.

This is a stack exchange question about auto-mounting using a Linux distribution called Ubuntu.  I am not sure how close the Intel Galileo Linux is to Ubuntu.  But it's a starting point.


FTDI Breakout with additional ISP connector

There's a thread about that on the Arduino Forum - someone had a similar question.

I found a schematic (below) which is not for that board, however the header pins are labelled the same as you found, so it is plausibly similar.

It appears that header is used for "Synchronous Bit Bang mode" as documented here: Bit Bang Modes For The FT232R and FT245R (Application Note AN_232R-01, Document Reference No.: FT_000339)

You can in fact configure that header to be an SPI programmer, as described for example, in FT232R Bitbang Programmer.

I made up a test as I had a similar board in my parts drawer:

It had provision for a 6-pin header similar to yours. Turning the board over we can see that they were labelled exactly the same as yours:

I soldered on a header (in yellow, to be consistent) giving me this:

I added a white dot to indicate pin 1 (visible on the edge) so I plug the cable in the right way around.

When I attempted to use the board I got this message from avrdude:

  avrdude: error: no libftdi or libusb support. Install libftdi1/libusb-1.0 or libftdi/libusb and run configure/make again

So, it had to be compiled from scratch! I am using Ubuntu 14.04 if you are trying to follow along. :)

Download avrdude

Go to the site http://www.nongnu.org/avrdude/

I downloaded version 6.3 source: http://download.savannah.gnu.org/releases/avrdude/avrdude-6.3.tar.gz

Install libusb and libftdi

Before compiling I had to grab libusb and libftdi:

sudo apt-get install libusb-1.0-0-dev
sudo apt-get install libftdi-dev

Compile avrdude

Now we make avrdude after extracting the archive and navigating to its folder:

./configure --enable-libusb --enable-libftdi
make

Find correct configuration

Inside the avrdude.conf file which comes with avrdude I found (after some pondering) this seems to be the correct entry:

# see http://www.geocities.jp/arduino_diecimila/bootloader/index_en.html
# Note: pins are numbered from 1!
programmer
  id    = "arduino-ft232r";
  desc  = "Arduino: FT232R connected to ISP";
  type  = "ftdi_syncbb";
  connection_type = usb;
  miso  = 3;  # CTS X3(1)
  sck   = 5;  # DSR X3(2)
  mosi  = 6;  # DCD X3(3)
  reset = 7;  # RI  X3(4)
;

The mapping of pins to numbers works like this... From the PDF about bit bang mode mentioned above we have this table, with annotations in blue by me:

The numbers refer to the bit number (i.e. in the range 0 to 7) in the "bit banged" data byte. We can see from the earlier schematic that, for example, MISO on the ICSP header is wired to CTS on the FT232RL. Thus MISO is data bit 3, which we tell avrdude in the above configuration. Similarly SCK is data bit 5, and so on.

I attempted to test like this:

./avrdude -C avrdude.conf -carduino-ft232r -pm328p  -v

Fix permissions

I got a permissions error which was fixed by creating a file in the folder /etc/udev/rules.d/ called 71-FTDI.rules. Inside this is:

SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE:="0666"

The numbers may vary for your board. You need to find the vendor and product ID. In Ubuntu you can do lsusb and see (amongst other things):

Bus 003 Device 061: ID 0403:6001 Future Technology Devices International, Ltd FT232 Serial (UART) IC
                       ^^^^ ^^^^

Note the two hex numbers, which get copied into the rules file.

After doing that, tell the system to reload the rules:

sudo udevadm control --reload-rules

Then unplug and replug the FTDI board to get it to notice the new permissions.

Test board detection

Finally, the avrdude line above works and reads the chip:

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as FD

avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:DE, L:FF)

avrdude done.  Thank you.

I had mine plugged into an ATmega328P.

Example connected to a Diavolino

Once we have got this far you just connect the FTDI board to your target board with a straight-through cable.

Summary

The FTDI board you have (and the one I have) can be used as a ICSP programmer for the AVR chips, as described above. Thus a simple board can be both a USB to serial converter, and also an ICSP programmer.

I see similar boards selling on eBay for around $5 so that is probably quite a cheap programming option.


The problem with your program is that it does not loop fast enough. Each
call to delayMicroseconds() should take roughly the requested time to
execute, but the CPU also needs time to execute the rest of your code,
including the time needed to return from loop() and call it again.
The period of the signal ends up being considerably longer than the
desired 10 µs.

The simplest software-only approach would be to get rid of the delay
using the technique described in the Blink Without Delay Arduino
tutorial. With one twist: instead of

// save the last time you blinked the LED
previousMillis = currentMillis;

you would use

// save the last time you should have blinked the LED
previousMillis += interval;

This way the small timing errors do not add up: you get, on average
the correct period. Oh, and obviously, you track time in microseconds,
not milliseconds:

const uint16_t TOGGLE_TIME = 5;  // toggle pin every 5 us

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

void loop() {
    static uint16_t last_toggle;
    static uint8_t pin_state = LOW;

    if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
        pin_state = !pin_state;       // invert pin state
        digitalWrite(13, pin_state);
        last_toggle += TOGGLE_TIME;
    }
}

This may somehow work if you have a fast enough Arduino, maybe a Due or
a Zero. If you have an AVR-based board (like the Uno and actually most
Arduinos), you will not get anything faster than ≈ 50 kHz with
this. This is because digitalWrite() is sooo slooow, it cannot cope
with your 100 kHz. You can improve things by using direct port
access[] instead of digitalWrite():

void loop() {
    static uint16_t last_toggle;

    if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
        PINB = _BV(PB5);             // invert pin state
        last_toggle += TOGGLE_TIME;
    }
}

Now you have roughly the requested frequency, but with some terrible
jitter: testing on my Uno I could see each level being held for
slightly less than 5 µs. Then, from time to time, one level is
held for ≈ 9 µs. Things could still be made faster by wrapping
the if inside an infinite loop, instead of relying on the Arduino core
to repeatedly call loop():

void loop() {
    uint16_t last_toggle = 0;

    for (;;) {  // infinite loop
        if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
            PINB = _BV(PB5);             // invert pin state
            last_toggle += TOGGLE_TIME;
        }
    }
}

And now the signal looks still worse: with the program running faster,
levels are held most of the time for only 3.5 µs, and then one out
of every ≈ 4 levels is held for about 9 µs. The average
frequency is probably right, but the jitter is absolutely awful, which
is likely due to the 4 µs resolution of micros() noted by user
Talk2.

The conclusion from these tests is: your only hope to get a somewhat
clean signal at this frequency is to generate it in hardware, not in
software. Choose one of the timers and have it generate the signal you
want. I would avoid timer 0, as it is needed by the Arduino timing
functions (delay(), millis()...). Here is how it can be done with
timer 2:

void setup() {
    // The output will be on digital 3 = PD3 = OC2B.
    pinMode(3, OUTPUT);

    // Configure timer 2 for PWM @ 10 kHz on OC2B.
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS21);   // clock @ F_CPU / 8
    OCR2A  = 19;          // period = (19 + 1) * 8 CPU cycles
    OCR2B  = 9;           // HIGH for (9 + 1) * 8 CPU cycles
}

void loop() {
    // Nothing to do here, the signal is generated in hardware.
}

And now you have a perfectly clean 10 kHz square wave, while your
program is free to do other stuff at the same time. Notice that the
output is now on pin 3: the pin choice is limited when using the
hardware-based approach. Notice also that you loose the PWM capability
on pin 11, since it depends on timer 2.


There is a json for ATtiny 167 at https://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips

So add that json to your preferenses.


Use ISRs inside a library more elegantly

As a matter of efficiency, I would favor chrisl’s advise to use the
platform's low-level interrupts if at all possible. This, however, comes
at the cost of portability: you would need an implementation specialized
for each platform you want to support. If you don't want to or cannot
maintain all this platform-specific code, attachInterrupt() may be a
reasonable option.

Then, you will absolutely need all those glue routines: since the
interrupt system calls your handlers with no parameters, you will not be
able to share handlers between interrupts, and you end up with as many
handlers as interrupts you are going to use.

There is, however, an elegant way of creating all these specialized
functions without writing them explicitly: you can ask the compiler to
write them for you on the basis of a template you provide.

Below is a version of Nick Gammon's example code modified to use a
template class. Note that you do not necessarily need a class to use
templates: you could use template functions as interrupt handlers if
that is appropriate for your use case.

template <uint8_t pin>
class myClass
{
    static volatile bool switchChanged;

public:
    static void begin()
    {
        pinMode(pin, INPUT_PULLUP);
        attachInterrupt(digitalPinToInterrupt(pin),
                        switchPressed, FALLING);
    }

    static void switchPressed()
    {
        switchChanged = true;
    }
};

template <uint8_t pin>
volatile bool myClass<pin>::switchChanged;

myClass<2> foo;
myClass<3> bar;

void setup()
{
    foo.begin();
    bar.begin();
}

void loop(){}

Note also that myClass<2> and myClass<3> are two different classes:
you actually have a different class for each pin. This means that
foo::switchChanged and bar::switchChanged are two different class
members even though both are static. Since you should (in principle)
have at most one instance of each pin-specific class, you can make
everything within the class static.

The main caveat of this method is that the pin numbers have now to be
compile-time constants. The great advantage is that you will have a
class created for each interrupt that is actually used: no need for an
array of 32 instances on an ESP32 if only a handful of interrupt pins
are going to be actually used.


How can I reduce current drawn by micro SD card module?

another good practice might be to add a Transistor to your Systems so that you can physically disconnect parts of your System from the power rail while not in use. this will obviously decrease power consumption...


Why is observed clock rate < 3MHz on Arduino Uno?

As Michael says there is a lot more going on than you think.

Firstly there are interrupts triggering which can slow things down (used to calculate milllis()).

Secondly you vastly under estimate the number of instructions that are being called.  For a start the loop is being called from a for(;;) loop in main():

    for (;;) {
        loop();
4   572:    0e 94 73 00     call    0xe6    ; 0xe6 <loop>
        if (serialEventRun) serialEventRun();
2   576:    20 97           sbiw    r28, 0x00   ; 0
2   578:    e1 f3           breq    .-8         ; 0x572 <main+0x10>
-   57a:    0e 94 1d 01     call    0x23a   ; 0x23a <_Z14serialEventRunv>
2   57e:    f9 cf           rjmp    .-14        ; 0x572 <main+0x10>
10 total

Then for the call to loop() the registers used get pushed to the stack, then your code executed, and the registers popped off again before returning.  This is the code for loop when disassembled:

000000e6 <loop>:
    // Save the registers to the stack
2   e6:     cf 92           push    r12
2   e8:     df 92           push    r13
2   ea:     ef 92           push    r14
2   ec:     ff 92           push    r15
8 total

    // Add to the sum
2   ee:     40 91 44 01     lds r20, 0x0144 ; 0x800144 <counter>
2   f2:     50 91 45 01     lds r21, 0x0145 ; 0x800145 <counter+0x1>
2   f6:     60 91 46 01     lds r22, 0x0146 ; 0x800146 <counter+0x2>
2   fa:     70 91 47 01     lds r23, 0x0147 ; 0x800147 <counter+0x3>
2   fe:     80 91 42 01     lds r24, 0x0142 ; 0x800142 <sum>
2   102:    90 91 43 01     lds r25, 0x0143 ; 0x800143 <sum+0x1>
1   106:    84 0f           add r24, r20
1   108:    95 1f           adc r25, r21
2   10a:    90 93 43 01     sts 0x0143, r25 ; 0x800143 <sum+0x1>
2   10e:    80 93 42 01     sts 0x0142, r24 ; 0x800142 <sum>
18 total

    // Check the value to see if it's time to print
1   112:    40 31           cpi r20, 0x10   ; 16
1   114:    57 42           sbci    r21, 0x27   ; 39
1   116:    61 05           cpc r22, r1
1   118:    71 05           cpc r23, r1
2   11a:    d1 f5           brne    .+116       ; 0x190 <loop+0xaa>
6 total

    // From here on is the "IF" section - skipped by the BRNE above
-   11c:    0e 94 f5 04     call    0x9ea   ; 0x9ea <micros>
-   120:    c0 90 3e 01     lds r12, 0x013E ; 0x80013e <__data_end>
-   124:    d0 90 3f 01     lds r13, 0x013F ; 0x80013f <__data_end+0x1>
-   128:    e0 90 40 01     lds r14, 0x0140 ; 0x800140 <__data_end+0x2>
-   12c:    f0 90 41 01     lds r15, 0x0141 ; 0x800141 <__data_end+0x3>
-   130:    6c 19           sub r22, r12
-   132:    7d 09           sbc r23, r13
-   134:    8e 09           sbc r24, r14
-   136:    9f 09           sbc r25, r15
-   138:    0e 94 68 06     call    0xcd0   ; 0xcd0 <__floatunsisf>
-   13c:    6b 01           movw    r12, r22
-   13e:    7c 01           movw    r14, r24
-   140:    60 91 44 01     lds r22, 0x0144 ; 0x800144 <counter>
-   144:    70 91 45 01     lds r23, 0x0145 ; 0x800145 <counter+0x1>
-   148:    80 91 46 01     lds r24, 0x0146 ; 0x800146 <counter+0x2>
-   14c:    90 91 47 01     lds r25, 0x0147 ; 0x800147 <counter+0x3>
-   150:    0e 94 6a 06     call    0xcd4   ; 0xcd4 <__floatsisf>
-   154:    9b 01           movw    r18, r22
-   156:    ac 01           movw    r20, r24
-   158:    c7 01           movw    r24, r14
-   15a:    b6 01           movw    r22, r12
-   15c:    0e 94 c7 05     call    0xb8e   ; 0xb8e <__divsf3>
-   160:    ab 01           movw    r20, r22
-   162:    bc 01           movw    r22, r24
-   164:    22 e0           ldi r18, 0x02   ; 2
-   166:    30 e0           ldi r19, 0x00   ; 0
-   168:    88 e4           ldi r24, 0x48   ; 72
-   16a:    91 e0           ldi r25, 0x01   ; 1
-   16c:    0e 94 a9 04     call    0x952   ; 0x952 <_ZN5Print5printEdi>
-   170:    60 e0           ldi r22, 0x00   ; 0
-   172:    71 e0           ldi r23, 0x01   ; 1
-   174:    88 e4           ldi r24, 0x48   ; 72
-   176:    91 e0           ldi r25, 0x01   ; 1
-   178:    0e 94 0b 03     call    0x616   ; 0x616 <_ZN5Print7printlnEPKc>
-   17c:    60 91 42 01     lds r22, 0x0142 ; 0x800142 <sum>
-   180:    70 91 43 01     lds r23, 0x0143 ; 0x800143 <sum+0x1>
-   184:    4a e0           ldi r20, 0x0A   ; 10
-   186:    50 e0           ldi r21, 0x00   ; 0
-   188:    88 e4           ldi r24, 0x48   ; 72
-   18a:    91 e0           ldi r25, 0x01   ; 1
-   18c:    0e 94 b0 03     call    0x760   ; 0x760 <_ZN5Print7printlnEii>

 // All this is just counter++
2   190:    80 91 44 01     lds r24, 0x0144 ; 0x800144 <counter>
2   194:    90 91 45 01     lds r25, 0x0145 ; 0x800145 <counter+0x1>
2   198:    a0 91 46 01     lds r26, 0x0146 ; 0x800146 <counter+0x2>
2   19c:    b0 91 47 01     lds r27, 0x0147 ; 0x800147 <counter+0x3>
2   1a0:    01 96           adiw    r24, 0x01   ; 1
1   1a2:    a1 1d           adc r26, r1
1   1a4:    b1 1d           adc r27, r1
2   1a6:    80 93 44 01     sts 0x0144, r24 ; 0x800144 <counter>
2   1aa:    90 93 45 01     sts 0x0145, r25 ; 0x800145 <counter+0x1>
2   1ae:    a0 93 46 01     sts 0x0146, r26 ; 0x800146 <counter+0x2>
2   1b2:    b0 93 47 01     sts 0x0147, r27 ; 0x800147 <counter+0x3>
20 total

 // Get the registers back and return
2   1b6:    ff 90           pop r15
2   1b8:    ef 90           pop r14
2   1ba:    df 90           pop r13
2   1bc:    cf 90           pop r12
4   1be:    08 95           ret
12 total

That's more than 10 instructions.  I make it 74 clocks to run one full iteration. (counter++ alone is 20 clock cycles - double your estimation for the total...)

You have to remember two important things:

AVR is a RISC CPU - that means that seemingly simple operations can take multiple instructions to perform.
AVR is an 8-bit CPU - that means that working with any variables bigger than 8 bits in size require far more complex code, and you work with 32-bit variables (and floats, but that's outside the timing loop section of your code).


Telit GPRS Module never returning and never timing out for command AT#FTPOPEN

The issues were:

Pin 9 MSM_nRESET should be explicitly set to HIGH.
Pin 10 (DTR) and pin 11 (RTS) should be explicitly set to LOW.
The Nimbelink device requires 5V external power. With USB power, the modem can intermittently reset during period of high activity. If the modem resets, then the command can appear to run forever when nothing is actually running.
Must use FTPOPEN with connection type 1 (passive).


Range of Offset Value in pH sensor module?

When converting real world sensor measurements into usable data there are several issues to consider:

Noise from any number of sources such as (unavoidable?) long cables and power supplies to name two.  Consider using exponential averaging to minimize the effects of noise.  If the noise if predictable consider sampling only when the noise is absent.
Slope of the data is important when converting to known scales.  For example the slop of the resistance of a thermistor verses heat may not have the same slope as the temperature in Celsius verses heat.  Simply multiply by the appropriate constant to correct for slope error.
After you correct for slope the values may still not be correct.  When all values are equally less or more then the expected values an offset is required.  Simply add or subtract the appropriate constant to correct for offset error.
Linearity is often corrected using lookup tables.  Linearity is a measure of how closely the sensor tracks the physical value being measured.  For example, after slope and offset corrections, a thermistor measurement may appeared curved when compared to the actual temperature in Celsius.  For this final correction the sensor measured value is used to index into a lookup table which returns a correction value.  Interpolation is used to control the size of the lookup table when space is a consideration.


I'm aware of a few JSON parsing libraries for Arduino.

aJSON
Arduino JSON Parser
JSON Arduino

I've never used any of these but I did do some simple JSON parsing in a project I'm working on so I'll show you how I did that.

NOTE: I'm reading serial data using the software serial library. You'll need to change this code to work for you. This will only work on very simple JSON strings. It's very limited but if that's all you're parsing then it'll work.

Example of JSON response from server:

{"id":"TEST1","lat":"38.56050207","lng":"-121.42158374","total":"3","available":"2"}

First, only read data between curly braces.

String response = "";
bool begin = false;
while (SIM900.available() || !begin) {

    char in = SIM900.read();

    if (in == '{') {
        begin = true;
    }

    if (begin) response += (in);

    if (in == '}') {
        break;
    }

    delay(1);
}

This code reads data one byte at a time and once it gets an open brace, it starts saving it into response. When it gets a closing brace, it ends it. So here's a clear limitation, you can only have one set of opening/closing braces in your string.

Once I have the string, I use indexOf and substring to extract relevant information:

start = response.indexOf("id\":\"") + 5;
end = start + 5;
nodeId = response.substring(start, end);

This code sets start to the beginning of id":" + 5 characters in the string. It's +5 because that's how long id":" is. So start points to TEST1 in the JSON string. In my system, the ID is always going to be 5 characters long so end is start + 5. I then use substring to extract that.

Again, before anyone starts down voting me for this horrible solution: if you know exactly what you're working with, and understand the limitations of this code, then this is not a bad solution. It's a solution that gets the job done.


Storing byte array from serial and converting to a floating point number

Two things I see wrong:

  Serial1.write('O');                                            //Send command 'A' to device *noting Serial1 not Serial

No, you send O not A... ???

  for(int n = 0; Serial1.available() < 8; n++)

While there are less than 8 bytes available in the buffer read one.

Erm...  The buffer starts off empty - empty is less than 8. It remains empty (always less than 8) until a byte finally arrives. Then it's still less than 8. I can't really see this ever working, and your array will overflow instantly and clobber the entirety of the rest of your RAM. I guess it finally finished when the serial object itself gets clobbered and available() returns some garbage number. In the meantime your array is just full of nothingness.

You need to completely rewrite that whole section. The simplest way is to wait until there are 8 bytes in the buffer (which will take some time - serial is slooooow):

while (Serial1.available() < 8);

You now have 8 bytes available to read, so you can go ahead and read them.

A better way is to look to see if there is at least one byte available, then read it into the right place in your array - and keep count of how many bytes you have read:

int n = 0;
while (n < 8) {
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

Of course, it's better to add some form of timeout in there too - so if nothing arrives soon enough your program doesn't lock up - or if you miss a byte it doesn't get completely out of sync. Also purging your read buffer before sending the command can help to prevent sync issues:

// Purge any old data
while (Serial1.available()) {
    Serial1.read();
}

Serial1.write('A');

int n = 0;
uint32_t start = millis();
while (n < 8) {
    // 1 second timeout
    if (millis() - start > 1000) {
        break;
    }
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

if (n == 8) {
    // We got the data - do something with it
} else {
    // It timed out
}

Now when it comes to converting to a pair of floats there's better ways than your byte-wise manipulation.  For instance, you could use a union:

union FloatPair {
    struct {
        float a;
        float b;
    };
    char bytes[8];
} __attribute__((packed));

FloatPair data;

Now you can use:

data.bytes[n]

to access the memory directly, and

data.a;
data.b;

to access the float values.

You can also do something similar with casting:

struct FloatPair {
    float a;
    float b;
};

FloatPair data;

char *bytes = (char *)&data;

bytes is now a byte-wise view of the memory used by a pair of floats.

You can even work the other way around:

char data[8] __attribute__((aligned(4)));

The aligned attribute will force the address of the array to be on a 4-byte boundary. Not important for a little 8-bitter, but vital if you ever port to a 32-bit MCU since a float always has to be on a 4-byte boundary, so a good habit to get into.

Now you can map floats into that memory space:

float *a = (float *)(&data[0]);
float *b = (float *)(&data[4]);

and access the floats as *a and *b. The * dereferences the pointers back into real numbers.

One thing to note: these methods all depend on the endianness of your data matching the endianness of your MCU - if they differ then you will have no choice but to do it all with manual byte-wise mapping.


POST to server using ESP8266 module- Arduino Uno- AT+ commands

Your code doesn't work because you start by sending ESP-specific AT commands to open a socket, then you suddenly switch to SIM800-specific AT commands, and the ESP goes "WTF dude?!"

I suggest you read some tutorials on accessing web sites with the ESP8266 not with the SIM800.


I have just done this same code but not getting exact time as per Indian timezone...What thing should I add to get exact time?

Use NeoGPS instead of TinyGPS, it has time and date functions for timezone offsets.

Ref:
https://forum.arduino.cc/index.php?topic=473294.msg3237680#msg3237680


Error when trying to write analog and digital signals from different pins (Arduino UNO)

I tested your code and it does indeed behave the way you said. But that is because you have not declared any pins as output.

analogWrite does this for you automatically in the library, however digitalWrite does not. This is because sending a digital pin HIGH when it is INPUT turns on the internal pull-up resistors. These are around 50k. Thus you will only see very dim output on the LED. Add this line to setup:

 pinMode (8, OUTPUT);

(And preferably pin 9 as well, just in case you decide to change to digital writes later).


The vector is empty after its default constructor. And nothing was ever added into it in your code. So you can't use anything like idexing by vect[index] or method vect.at(index). And as there are no exceptions available, who knows what it does after the out of range call.

You should consider ring buffer instead, using dynamic memory is tricky on such constrained platforms. Even using Arduino's String class is often source of memory fragmentation and out of memory type errors.


My ESP8266 web server is only displaying text, even after ensuring content type is text/HTML

Don't use the low-level tools to handle http, use the built-in http tools. They  make creating http responses trivial. No more concatenating headers or worrying about client status; it provides a nice clean function ex:server.send(404, "text/plain", message); and nice subscription method: server.on().

Checkout its usage on one of the Arduino ESP8266's built-in examples:
https://github.com/esp8266/ESPWebServer/blob/master/examples/HelloServer/HelloServer.ino


This Arduino topic is an over-simplification and not very robust, but it presents in code the basic principle of threshold detection and the subtraction of adjacent pulse times (period).  BPM = 60.0 / period in seconds.

If you want something that would work under a larger range of conditions, you can add the three primary missing features used by medical instrumentation.

Automated zeroing, which can be accomplished with an analog filter and pull-up or with a digital high pass filter that attenuates frequencies below 0.3 Hz.  This can be done with a series capacitor leading to the analog input being sampled, with a pull up resistor to V+ and another resistor to ground to center the Voltage to an appropriate positive steady state value.
Attenuation of frequencies above those representing a pulse to avoid false triggers from high frequency noise, cross-talk, or transients, which can be accomplished with an analog filter or with a higher sample rate and a digital low pass filter that attenuates frequencies above 100 Hz 1.
Dynamic range compression, which detects the trend in pulse amplitude and continuously adapts the trigger threshold accordingly to avoid false indication of beats or the missing of weaker but legitimate beats.

To do the filtering digitally, you may want to read up on DSP (digital signal processing).  There are several great books on it, and you can search for simple algorithms for both low pass filters and high pass filters in GitHub or elsewhere in the open source community.

[1] Wikipedia's article on low pass filters


UNO's digital pin continue to read 1 for a while

Digital inputs should either be low or high. In this image acceptable input voltages on the left represent common TTL voltages based on a 0 to 5 volt range:

It is bad practice to leave a digital input floating.  A floating or disconnected input implies the voltage is unknown.  I suspect in your case a small amount of input capacitance held a charge for several seconds.  Once leaked off the input appeared to change from 1 to 0.  Even though you know what might be happening, you should not depend on it as it is unreliable behavior.

If connecting a SPST switch use a pull up (or pull down) resistor to pull the input pin to the opposite voltage the switch is pulling.  In this image the switch is connected to ground so the resistor is connected to positive voltage as a pull up:

The fist image comes from this Logic Level tutorial.


Your problem is here:

char datar = '';

...

 len = radio.getDynamicPayloadSize();
 radio.read(&datar, len);

The variable "datar" is one byte long. You then find the payload size (presumably greater than one byte) and read into datar more than one byte. This overwrites other parts of memory and the program crashes. You need to make datar larger, eg.

char datar [50];

The exact size would depend on your maximum payload size.


arduino due-Python interfacing for high speed data rate

There's two things you need to know:

The Serial.write(buf, len) function sends the raw data - one byte for every "len" count.
On the Due integers are 32-bits, so each one takes 4 bytes.

So first you need to define how big the numbers are you'll be dealing with and use data types that are big enough without being wasteful - you have 3 choices: char, short and int - 8, 16 and 32 bits respectively.

Values between 0 and 255 use an unsigned char (uint8_t)
Values between -128 and 127 use a signed char (int8_t)
Values between 0 and 65535 use an unsigned short (uint16_t)
Values between -32768 and 32767 use a signed short (int16_t)
Values between 0 and 4,294,967,295 use an unsigned int (uint32_t)
Values between −2,147,483,648 and 2,147,483,647 a signed int (int32_t)

One very tricky thing with this kind of binary data transfer is knowing where a value starts and ends.  You don't get that kind of issue with ASCII representations as you have a line feed and/or a carriage return after each full value and the range of valid characters that make up a value is very narrow and can never contain the delimiting character.  You don't have that luxury with binary transfers as there is no byte value that can't appear in a data stream.  However, there could be byte sequences that could never appear in the data stream - numbers you know you'll never be using that could form part of a synchronizing header (say, in hexadecimal, 0xFF 0xFF 0xFF 0xFF 0x00 0x00 0x00 0x00 - or in signed shorts that would be a sequence of 65535 65535 0 0) - once you see that sequence of bytes you know you're lined up with your data stream and can receive it byte by byte and build up the right sized values from that.

You can estimate your transfer time by working with the baud rate and knowing the data size.  For instance, to transfer 1000 short (16 bit) values at 250000 baud should take around:

1000 * 2 = 2000 bytes
250000 baud = 25000 bytes per second (8 bits for the byte, 2 bits for the start and stop bit)
2000 / 25000 = 0.08s


How to connnect Arduino to Wemos D1 (send data)?

A) Throw out the Arduino, and just connect your display and sensor to the WeMos directly.
B) Connect the Arduino to the WeMos using UART, SPI or I²C and send the temperature value to the WeMos. Keep in mind that the Arduino UNO is a 5V device, and the maximum voltage for the ESP8266 is 3.3V, so you'll need a level shifter.
You can send the temperature as a binary value (beware of framing errors), but the easiest way is to use a text-based protocol. Since you just have to send a single value, you can just use a single delimiter (e.g. new line). That makes it very easy to parse.


Reading data from ThingSpeak via Arduino Uno+ESP8266

HTTP GET request needs to end with an empty line and HTTP 1.1 requires a Host header.

Add an empty line and eiher change the HTTP version to 1.0

client.print("GET /channels/421932/feeds.json?api_key=");
client.print(apiKey);
client.println("&results=2 HTTP/1.0");
client.println(); // empty line

or add the Host header

client.print("GET /channels/421932/feeds.json?api_key=");
client.print(apiKey);
client.println("&results=2 HTTP/1.1");
client.print("Host:");
client.println(host);
client.println(); // empty line


Regarding turning exact 180 degrees using an MPU6050

As I understand, you want the robot to position itself automatically at either 180° or -180° and stay there. When an outer force get's applied to the robot - turning it out of the target positions - it should again try to reach the target positions.

The first problem was pointed out in the comments and your own code correction seems ok to tackle that:

if(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
    stp();
} else {
    turn();
}

But I see a second problem: In the real world sensor mostly have some kind of noise imposed on their signal (not necessarily meaning electrical noise). For example if you shake the table, where the robot stands on. Or - more importantly in my opinion - The motor, that you use, might not stop fast enough. The MPU might return a value of 179° or 181° when it should be at 180°, because the motor could stop the robot fast enough (inside the time span it needs to travel 1°). In your current logic, this would trigger another turn command. Since you are only turning in one direction, this can create an instable system, which will turn infinitely.

This kind of problem is often solved by using a feedback loop control (of course in combination with the ability to control/turn into both directions). A good and useful example is a PID control (Proportional, Integral, Differential: This is how the control is mathematically structured), where there are already Arduino libraries for it (like this one). If you want it easier, you can define a range of angles, which are acceptable for your positioning (where it should stop) (for example 175° to 185°). The size of the range, that you need, would depend on the mechanics of your robot and the motor. Note, that this also has drawbacks, but it might be easier for now, depending on what exactly you want to achieve.

As Tom pointed out in his comment, you also get trouble with your first approach, if the method getAngleZ() returns not an integer, but a float, which it indeed does. You can see this in the source code of the used library here. The line

float getAngleZ(){ return angleZ; };

tells us, that the return type of the method is float. The problem with this type is, that it cannot represent every rational value inside it's range. There are gaps between two following float values. The values inside this gap cannot be represented by float. Instead a value nearby will be used (Actually I'm not sure, how this is been done. Probably by going to the next lower value, like with int). This also means, that not every integer is representable by float. Even if the Z angle is exactly 180°, the float value may be something like 179,98. But since 179,98 is not equal too 180 the statement

mpu6050.getAngleZ() == 180

would never become true. Of course the mentioned solutions above apply here too.


Looking at your library source, it seems the number of devices is clamped at 8. This isn't a hard limit imposed by the chip but rather practical design. SPI, especially at high speeds, can get unreliable when the bus capacitance, related to the cable lengths, gets so high that signals are skewed beyond recognition. Also the buffer in the library used to hold the row data is 64 bytes in size, intended to hold the data for 8 devices with 8 rows each.

You can edit the library to make it support 12 devices though it will require attention to detail like, increasing the buffer to 96 bytes, getting rid of short-circuits within the methods that make sure that no more than 8 devices can be addressed, for-loops, etc.


Just putting the jumper wires in the plated holes, doesn't always give a good connection. Try applying some lateral force, to make sure all of them have proper contact. Wiring looks otherwise fine.

A more permanent solution would be to solder some male headers to the display, so you can properly seat it into the breadboard.


Parsing HTTP get response to extract values

First of all, I would avoid using the String class, because of the
memory fragmentation issues that come with it. The most obvious solution
is probably to store the result in a character array, then parse the
array, with strstr() or sscanf(), to extract the values you want.
However, this requires storing the whole response in RAM, which is
expensive. A better option is to parse the string as it comes, character
by character, using a kind of finite state machine.

Here is how I would do it. First, I assume you know what you want to do
with these values. Since I don't, I will instead use this dummy function
to just print the values out to the serial port:

static void parse_relay_callback(uint8_t index, uint8_t value)
{
    Serial.print("parsed: relay ");
    Serial.print(index);
    Serial.print(": ");
    Serial.println(value);
}

You will have to replace this with whatever is appropriate for your
application.

Then here is the parser:

static void parse_relay(char c)
{
    static const char templ[] = "RelayI = V#"; // I: index, V: value
    static uint8_t pos, index, value;
    char expected = templ[pos++];
    if (expected == 'I' && c >= '0' && c <= '4')
        index = c - '0';
    else if (expected == 'V' && (c == '0' || c == '1'))
        value = c - '0';
    else if (expected == '#' && c == '#')
        parse_relay_callback(index, value);
    else if (c != expected)
        pos = 0;
}

You just feed it one character at a time, with something like:

while (ESP8266.available())
    parse_relay(ESP8266.read());

Feeding the parser with your response example gives the following on the
serial port:

parsed: relay 1: 1
parsed: relay 2: 0
parsed: relay 3: 0
parsed: relay 4: 1


Arduino raise the error "variable-sized object 'my2dArray' may not be initialized" while trying to change the elements of 2d array

The error is in this line:

  int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

The presence of the word int there tells it to try and make a new variable. You don't want to do that, since it's an error.  Lose the int and it might work.


Replace 6 pin on/off switch on Power Bank with 3pin or 2pin?

Looks like only 2 of the 6 pins are used. It's a simple on-off. The switch itself is a "Double Pole Double Throw", but the two poles are tied together to make it single pole (like a 3 pin switch), and one throw is ignored, making it 2-pin.

You can see on the underside of your board which pins are tied together with traces. Bridge those pin pairs to turn the board on.


Which are the unused digital pins after L293D motor shield is installed on a Arduino Uno board?

If this is the same board as seen on Banggood Which may also be seen at Adafruit
The schematic shows most of the digital pins in use
D3  - PWM2B
D4  - DIR_CLK
D5  - PWM0B
D6  - PWM0A
D7  - DIR_EN
D8  - DIR_SER
D9  - PWM1A
D10 - PWM1B
D11 - PWM2A
D12 - DIR_LATCH

The analogue pins A0-A5 are still free - these can be used as digital pins.


There is a bootloader on those chips to slow serial programming. A much easier way to to get a stlink debugger.

There are also some packages that allow Arduino styled programming on those chips. I wrote one myself that runs on iar and I think at least one on sdcc.

Those chips are really nice.


Do you want to eventually do 12 / 10 or 1 / 10 and 2 / 10? If the second one, you'll have to read all the serial values into an array and convert those characters to their plain integer values (subtracting 48 from each value). After that, you'll have to add them together with the correct placeholders (A * 100 + B * 10 + C).

Basically, the read() function returns one character in the ASCII format. ACII basically representing characters on your screen with numbers. 48 displays a 0 on your screen, 49 a 1, and so on.

You're also facing a problem where your numbers are getting truncated. This means it cuts off the decimal. For when you send 100, it is 48 / 10 = 4.8, however 4.8 becomes just 4. The same thing happens for 49.

To fix this, you need to use a float data type. This allows decimal values. You also want to make sure that the conversion from float to string works correctly for the Serial.print() so you don't end up with 4 again.

Final code:

while(Serial.available()) {
  float number = (float)(Serial.read() - 48) / 10;
  Serial.println(number, 4);
}


How can a USB keyboard emulator (TrinketKeyboard) type Unicode characters?

You could hack it.

Make it press CMD+SPACE
type terminal.app
press ENTER
type  echo -e
"\xC2\xAF\\_(\xE3\x83\x84)_/\xC2\xAF" | pbcopy
press ENTER
press CMD+Q
press CMD+V

though the user would see a terminal window for a second.


It depends on how precise you want your time-base to be. The plotter's x-axis is in sample-count, not time, so you have to emit samples at a fixed rate for it to have time-significance.

Your

loop(){
   yadda();
   zadda();
}

may or may not run at a constant rate, depending on what takes place in each iteration of the loop, as well as on your definition of "constant" (I don't believe I just said that...)

Even if none of your code is conditional, binary to ASCII conversion, clock and Serial interrupts, and other low-level code we don't see, may run slightly differently from iteration to iteration; e.g. the number of interrupts during any given iteration may well vary.

If you need to hold a tighter timebase, stalling at the bottom of the loop until millis() reaches (the previous millis() + an interval constant) will at least get you to within a millisecond of a fixed loop-rate. You could, of course, do the same thing with micros(), as long as you know for a fact that the loop can never take longer to execute than 1/frequency you need it to run at, and even then, it should take a fair slop-factor (that's a technical term! :) less than that, "just in case".

Update:

Though I wrote "stalling" at the end of the loop, a better technique is to call every job (in your case, 1 of them - for now ? ) as frequently as possible and let each job decide whether it needs to execute. So in your case:

loop {
  maybeSampleAndPlot();
  // maybeDoSomeOtherThing();  // not implemented yet...
}

maybeSampleAndPlot(){
  time = millis();
  if time - previousSampleTime >= MSEC_040
    save (time + MSEC_040) as nextSampleTime;
    sample the data;
    plot the data;
  endif
}


How to properly use interruptions with twi (I2C)

After some tests, it's working !
First off all, I used Serial.println in my ISR, that's made it freeze apparently.
Second, apparently, I can't send more than 6 bits, else I'll have an error (data NACK), I thought it was 8.

This is my code working :

//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

volatile int8_t etat = 0;
volatile uint8_t _addr;
volatile uint8_t _data;

ISR(TWI_vect)
{
  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
      }
      else
        etat = -1;
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
      }
      else
        etat = -2;
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
      }
      else
        etat = -3;
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      break;
  }
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE)|(1<<TWINT);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b0010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }

  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

Thanks a lot to jfpoilpret !


May I use both USB-serial and tx/rx pins at the same time?

The usb port and the tx/rx pins are one and the same thing. You can't use one thing for two jobs at the same time. So you will either have to implement some kind of multiplexing system (switches) or come up with a different way of doing things, maybe using the SoftwareSerial library or the Wire Library or investing in a better board with more than one serial port.


As hinted by chrisl in a comment, there are various criteria you may
want to optimize for: speed, size, readability... Judging from the
current state of this sketch, I would say that your first goal at this
point should be to optimize for readability.
The hardest think to make sense of are most of the plain numbers. When
setting registers that are bit fields, do not use decimal values: use
either hexadecimal or binary. Or, better yet, use the names of the bits.
The avr-libc defines those names, as well as the macro
_BV(bit_position), which expands to (1 << bit_position) and is meant
to be used with those names:
void Config() {
  DDRB   |= _BV(PB1) | _BV(PB3);  // PB1 and PB3 as output
  ICR1    =  416;        // timer period = 417 cycles
  OCR1A   = 9983;        // ???
  TCCR1A  = _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
  TCCR1B  = _BV(WGM12) | _BV(WGM13);  // ...ditto
  TCCR1B |= _BV(CS10);   // clock @ F_CPU
  TIMSK1  = _BV(TOIE1);  // enable TIMER1_OVF interrupt
}

Granted, the bit names are somewhat obscure, but they do make the
program easier to read if you have the datasheet nearby. I do like to
have comments that make the code understandable even without reading the
datasheet.
Note that evaluating those expressions does not make the program any
slower, as they are evaluated at compile time.
When a variable is used in a single function, it is better to define it
in that function. Keeping the definition close to where the variable is
used makes the code more “local” and thus easier to read. Since you want
some of those variables to remember their values across invocations of
the function, give them the static qualifier.
You may not need to optimize this program for speed. There is, however,
a low hanging fruit here: remove the volatile keywords. This keyword
is meant to explicitly disable some compiler optimizations that are
unsafe when a variable is shared between the interrupt and non-interrupt
contexts. None of the variable you use needs this.
If I understood correctly, the function SendIRCode() just toggles a
couple of bits in TCCR1A. You can simplify it to this:
void SendIRCode() {
  TCCR1A ^= _BV(COM1A0) | _BV(COM1A1);  // toggle PWM output on OC1A
}

Finally, there is I believe a bug in this sketch. The variable
Array_Seq is continuously incremented and never reset. The program
will then end up reading past the end of the IRCode array.


They're raw HID counts and as such don't have a unit. It is up to the OS to translate them from logical amounts to physical values.


Arduino TimerOne breaks the program when calling "digitalRead"

The time between 2 interrupt triggers is only 8us. Also digitalRead() is a quite big function, that needs some time to execute (I don't know how much). That way it is to short for the Serial print command to execute in the leftover time. Make the following change and you will see, that it works.

void loop(){
  noInterrupts();
  Serial.print("Program running \n");
  interrupts();
  delay(1000);
}

Now the interrupts are disabled during the execution of the Serial.print(), so that it can finish. After this the interrupts are enabled again and we wait for 1 second to give the interrupts some time before we are disabling them again.

The speed of the Arduino is limited, so you cannot do much, when constantly triggering interrupts in the pace of 8us. If you only want to check this digital input you can get the value directly with using the PINB registers (refer to this side), which works much faster.

Also you should consider making the variable val volatile, since it will can change everytime through your interrupt service routine.


Float to int conversion not working right in method using varargs

With some inspiration from timemage's comment, I decided in the long run to implement my own power function that takes two int arguments and returns an int. Rather than use the pow function in the <math.h> library which returns a double when I only need an int.
int power(int x, int y) {
  return y == 0 ? 1 : x * power(x, y - 1);
}

Now the program works as intended!


Yes you can.

The only difference between the 3.3 V and 5 V Pro Mini is the crystal and the voltage regulator.


You can't squeeze 100kHz out of an Arduino without a major software rewrite (at which point you will be using an AtMega chip rather than Arduino). analogWrite defaults to ~500Hz and can be boosted to 62.5kHz on some Arduino models, and only for 2 pins. Other PWM pins are capped at 31.4kHz.

You can achieve 100kHz PWM by toggling pins manually and busy-waiting, but you won't be able to do anything else during this. Or you can make use of interrupts, which is a big leap from Arduino ecosystem as I already said.


What is the lowest resistance pot that is useful with an analog input?

Assuming you wired it correctly (ie. you put the wiper to the analog input) your first setup looked like this:

Your big problem here is the current flow through the pot. Using Ohms Law the current would be:

I = V / R
I = 5 / 25
I = 0.2A  (200 mA)

That is too much to be drawing from the 5V pin and it could easily drag down the voltage to the rest of the board. Also the power would be:

W = I * V
W = 0.2 * 5
W = 1W

One watt is a lot to put through a pot, and you may well have burned the track inside it.

  So, if I included a 10k resistor on either side of the pot that should address the current issue but it leaves the question of whether the remaining 25-ohm range is too small for the ADC to register distinct values, ...

The 10k resistor will stop the current problem, but now the range in the voltage divider will be ridiculously small. The setup will now look like this:

Unfortunately the range you are going to read with the analog input is going to be (voltage divider formula):

Vout = Vin * (R2 / (R1 + R2))

With the wiper at one end R1 will be 10000 and R2 will be 10025 and with the wiper at the other end it will be vice-versa. So the voltage you get will be:

Vout = 5 * (10000 / (10025 + 10000))
Vout = 5 * 0.499
Vout = 2.497

Or:

Vout = 5 * (10025 / (10025 + 10000))
Vout = 5 * 0.501
Vout = 2.503

In other words you will always be reading about 2.5V and therefore your analog read will always return around 512, which won't be much use to you.

  I'm going with a larger value pot (10k or 25k) ...

That sounds like a sensible value. A 10k pot will only draw:

I = V / R
I = 5 / 10000
I = 0.5 mA

That is a reasonable current draw and the analog input will still read it fine.

As Majenko points out in his answer you don't want a whole lot more than that resistance because of the optimal input impedance of the ADC converter (10k). A very high resistance would mean only a small current would flow into the analog input pin.

How to use your 25 ohm pots

If you want to use your existing 25 ohms pots because of their physical appearance, then a  small resistor in series could reduce the current to a reasonable amount and still give a good reading range. For example, 330 ohms on the "high" side (and nothing between the low side and ground).

Vout = 5 * (330 / (355 + 330))
Vout = 5 * 0.193
Vout = 0.963

Or:

Vout = 5 * (355 / (355 + 330))
Vout = 5 * 0.581
Vout = 2.591

That is now going to give you a reading between 0.96V and 2.59V which, whilst not the full range of 0V to 5V should give you reasonable differentiation as you turn the pot. And the current through it would be:

I = V / R
I = 5 / 355
I = 0.014A (14 mA)

Thus the power would be:

W = I * V
W = 0.014 * 5
W = 0.070 (70 mW)

References

Voltage Dividers tutorial
Ohms Law


Best way to send text to ESP8266 remote display

Try the esp8266 UDP messages

With UDP you can send and receive messages quite easily and without consuming lots of resources.


Since you dont give the largest number your counter over flows at. You may want to look at libraries that implement arbitrary size integers. This means that there the integers can be bigger than usual - You would need to implement a counter, reset to 0 if the integer gets too big (just use a if statement if what youre doin is that simple-it sounds like it). So its entirely predictable for your purpose (whatever that is you didnt state). If you google around you will find libraries for arbitrary large integers for arduino e.g.

https://forum.arduino.cc/index.php?topic=85692.0

a library by Nick Gammon.


How to return a message when calling by a TCP connection?

I'm assuming that you are using an Ethernet shield, as nothing about this is stated. But solution is really similar between many network solution.

Once a TCP connection has been established, it can be used like you would use the Serial;

you'll probably end up having something similar to:

EthernetClient client = server.available(); //accept a new connection
if (client) { //if valid connection
  client.print(distanceValue);
  client.close(); //close connection
}

look at the official API reference for a more detailed list of available command.