text:
Unable to read data with 16 serial clock cycles
I am trying to read data from an AD7314 Temperature Sensor that is connected to an Arduino Uno and output that value onto 6 LEDs also connected to the Arduino Uno board. From the image below, the sensor is showing only an output of 0011111111111111 during the streams of 16 clock cycles even after the chip enable goes from low to high before conversion to initiate a new one (it seems that the conversion is stuck). The datasheet says:

A leading zero and 10 bits of data are transferred during a read operation. Read operations occur during streams of 16 clock pulses. Output data is updated on the rising edge of SCLK. The serial data is accessed in a number of bytes if 10 bits of data are being read. At the end of the read operation, the SDO line remains in the state of the last bit of data clocked out of the AD7314 until CE returns low

I am not sure where exactly I am going wrong during the read operation:
Note: for the Waveform image (Top to bottom):

waveform 1: Chip Enable
waveform 2: Serial Clock
waveform 3: MISO Line
waveform 4: MOSI Line

My code is below:
#include <SPI.h>

const int MOSI_PIN = 11;
const int MISO_PIN = 12;
const int SCK_PIN = 13;
const int Slave_PIN = A0;

// module data
uint16_t myValFromTempSensor = 0;

void setup () {
  SPI.begin ();
  SPI.beginTransaction(SPISettings(125000, MSBFIRST, SPI_MODE0));
  pinMode(5, OUTPUT); //LED 3
  pinMode(6, OUTPUT); //LED 4
  pinMode(7, OUTPUT); //LED 5
  pinMode(8, OUTPUT); //LED 6
  pinMode(9, OUTPUT); //LED 7
  pinMode(10, OUTPUT);//LED 8
  pinMode(MOSI_PIN, OUTPUT); // MOSI to SDI
  pinMode(MISO_PIN, INPUT); //MISO to SDO
  pinMode(SCK_PIN, OUTPUT); //CLOCK PIN to SCK
  pinMode(Slave_PIN,OUTPUT); //Slave pin

  digitalWrite(Slave_PIN, LOW);//Set slave low before communication
  for (int i = 5; i < 11; i++) {
    digitalWrite(i, LOW);
  }
  delay(100);
} // end of setup

void loop () {
  digitalWrite(Slave_PIN, HIGH);  //Set slave high to read data
  myValFromTempSensor = SPI.transfer(0x00); // Read Data from the device
  myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;// Bitshift to read next 8 bits
  digitalWrite(Slave_PIN, LOW);
  if(( myValFromTempSensor>=0) && ( myValFromTempSensor<=196)) {
    //Range 0C to 60C is  0 to 196
    digitalWrite(5, bitRead(myValFromTempSensor,0));
    digitalWrite(6, bitRead(myValFromTempSensor,1));
    digitalWrite(7, bitRead(myValFromTempSensor,2));
    digitalWrite(8, bitRead( myValFromTempSensor,3));
    digitalWrite(9, bitRead( myValFromTempSensor,4));
    digitalWrite(10, bitRead( myValFromTempSensor,5));
  } else {
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
    digitalWrite(9, 0);
    digitalWrite(10, 0);
  }
}

from the waveforms, it looks to me like the sensor is outputting 0b0011111111111111 = 0x3fff.

The first 0 is a leading zero according to the datasheet which does not add to the sensor reading

I know, I did read the datasheet. I am just saying that I disagree with your statement: “the sensor is showing only an output of 01000000000”.

I apologize, i corrected it.

I see several issues here.
Sensor output
According to the waveforms shown by your logical analyzer, the sensor is
outputting 0b0011111111111111. We have to discard the first (a padding
zero) and the last five bits (copies of DB0). We then end up with the
actual data bits being 0111111111. This has to be interpreted as a
signed fixed-point number in s.7.2 format, which gives 127.75 °C:
the maximum possible value the sensor can output, and well above its
maximum operating temperature.
I cannot tell what is going wrong here. It looks like the sensor is
either burning alive, or trying to tell you it's extremely unhappy.
SPI mode
You wrote:

SPISettings(125000, MSBFIRST, SPI_MODE0)

SPI mode 0 seems to be pretty common. In this mode, the data lines are
updated on the falling edge of the clock, and they are read on the
rising edge. However, according to your sensor's datasheet, it appears
this sensor works the other way around: it uses SPI mode 1. Your
setting should reflect this.
Decoding the data
You wrote:

myValFromTempSensor = SPI.transfer(0x00);
myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;

Here you are assuming the least significant byte is transmitted first.
This is not the case: you get a stream of 16 bits with the most
significant first. Thus, in terms of bytes, it's also MSB first.
Then, 6 of these 16 bits have to be discarded in order to get the actual
10 data bits. Since the Arduino has no 10-bit data type, and the
number is signed, it has to be sign-extended to 16-bits. All this can be
done in C/C++ by:

left-shifting one bit to the left (discarding the zero padding bit)
casting to a signed 16-bit integer
right-shifting (which gcc implements using sign
extension) six bits to the right

Or, in code:
digitalWrite(Slave_PIN, HIGH);
uint16_t raw_data = SPI.transfer16(0);
digitalWrite(Slave_PIN, LOW);
int temperature_reading = (int16_t)(raw_data << 1) >> 6;

Edit: Here are more details about the data representation, and about
the conversion to 16-bits done by the expression
(int16_t)(raw_data << 1) >> 6.
According to the datasheet, the sensor gives the temperature as a 10-bit
signed number in two's complement notation. If you fail to acknowledge
the fact that the result is signed, and you interpret the 10 bits
as an unsigned number, then a temperature of −1 °C will be
interpreted as +255 °C, which is obviously very wrong.
Since it's a signed number, increasing the bit width of the temperature
to 16 bits has to be done using sign extension, i.e. the
missing bit positions have to be filled with copies of the leftmost bit
(the “sign bit”).
The datasheet also shows that the sensor sends a stream of 16-bits as
follows:
0 db9 db8 db7 db6 db5 db4 db3 db2 db1 db0 db0 db0 db0 db0 db0

where the first bit is a padding zero, then come the ten data bits
db9 – db0, and then five extra copies of the last data bit.
These extra copies can  be seen in figure 3 (serial interface
digram), and can also be inferred from the sentence “the SDO line
remains in the state of the last bit of data clocked out of the AD7314”.
The line
uint16_t raw_data = SPI.transfer16(0);

puts this bit pattern into the variable raw_data, which is a 16-bit
unsigned integer. Then, the operation raw_data << 1 shifts this
pattern one bit position to the left, discarding the leftmost zero and
padding with another zero on the right, which gives:
db9 db8 db7 db6 db5 db4 db3 db2 db1 db0 db0 db0 db0 db0 db0 0

This is then cast to a signed number, which doesn't change the bit
pattern, but only the interpretation of the leftmost bit, which is now a
sign bit. Then, the number is shifted by 6 bit positions to the
right. Since this is an arithmetic shift, which does sign extension,
the leftmost bit (the “sign bit”) is replicated during the shift, which
yields:
db9 db9 db9 db9 db9 db9 db9 db8 db7 db6 db5 db4 db3 db2 db1 db0

And this is the expected result: the same numeric value that was
originally stored in the “temperature value register” of the sensor,
only represented as a 16-bit number.

I am not sure where you are getting 16 bits from rather than 11 bits (including leading zero) if i understood correctly. The datasheet mentions 11 bits being transferred during streams of 16 clock cycles.

@user7187418: At the hardware level, the SPI port can only handle multiples of 8 bits, and it reads an input bit on every clock cycle. At the library level, the transfer16() method sends 16 clocks pulses and returns an unsigned 16-bit number.

So at the line of code : int temperature_reading = (int16_t)(raw_data << 1) >> 6;  Does this mean i receive the 10 bit signed data, if so , i have 2 questions: 1) If i understood correctly, the transfer16() returns an unsigned 16 bit number does this mean that the 10 bit temperature data in the code mentioned above is an unsigned 10 bit reading ? (i need to read between 0 C and 60 C )  2) Should i output the temperature data on to the 6 leds by reading the only the first 6 bits by using the bitRead() function as i am currently doing or is there another way that i am currently unaware of ?

You seem confused bout binary number representations. See my extended answer. 2) Only you can know how you want to display the temperature to the end user. I would output through the serial port, at least during the debugging stage.

If anyone stumbled on this thread later like I did, it may be helpful to understand that the binary response is a decimal number, specifically with 0.25c resolution. Meaning that the integer value that Edgar Bonet's (excellent) response will give you needs to be multiplied by 0.25 to get the actual temperature in Celsius.
I suggest multiplying by 0.25 because it will give the same result as dividing by 4 but without the risk of a divide by zero error. Also division is extremely slow on Arduino since the underlying instruction set does not have a divide instruction.
I  hope this helpful to someone at some point; if not sorry for the annoyance.

This is not an answer to your question but I cannot add it as a remark since it involves code.
You can greatly reduce your code by using for loops, e.g.:
   pinMode(5, OUTPUT); //LED 3
   pinMode(6, OUTPUT); //LED 4
   pinMode(7, OUTPUT); //LED 5
   pinMode(8, OUTPUT); //LED 6
   pinMode(9, OUTPUT); //LED 7
   pinMode(10, OUTPUT);//LED 8

to
   int n;
   for (n = 5; n < 11; n++)
   {
      pinMode(n, OUTPUT);
   }

And
digitalWrite(5,bitRead( myValFromTempSensor,0));
digitalWrite(6,bitRead( myValFromTempSensor,1));
digitalWrite(7,bitRead( myValFromTempSensor,2));
digitalWrite(8,bitRead( myValFromTempSensor,3));
digitalWrite(9,bitRead( myValFromTempSensor,4));
digitalWrite(10,bitRead( myValFromTempSensor,5));

to
int n = 0;
for (n = 0; n < 6; n++)
{
    digitalWrite(n + 5,bitRead( myValFromTempSensor, n));
}

And
  digitalWrite(5,0);
  digitalWrite(6,0);
  digitalWrite(7,0);
  digitalWrite(8,0);
  digitalWrite(9,0);
  digitalWrite(10,0);

to
int n;
for (n = 5; n < 11; n++)
{
    digitalWrite(n, 0);
}

Instead of hardcoded values 5 and 11 you can use defines, e.g.
#define LED_MIN 5
#define LED_MAX 11

and change
for (n = 5; n < 11; n++)

to
for (n = LED_MIN; n < LED_MAX; n++)


text:
Arduino Cloud Editor doesn't work on ChromeOS
https://www.arduino.cc updated their web-based IDE this week, and now the IDE does not recognize my Pitsco PRIZM Robotic controllers on ChromeOS. I cannot find a generic "Board" device to use with the IDE.
Is there a way to get the new web-based Arduino IDE on ChromeOS to work with a clone such as PRIZM?

UPDATE May 25:
The Arduino Cloud developers have now restored support for uploading to 3rd party derivatives of the officially supported boards from Arduino Cloud Editor on ChromeOS machines.
So the workarounds I described in my prior answer are no longer required and you can now use these derivative boards with Cloud Editor by simply selecting the equivalent official board from the "Select a device type" dialog.

Original answer:
Arduino officially supports uploading to a specific list of official boards from Arduino Cloud Editor on ChromeOS machines: Boards compatible with the Cloud Editor - Cloud Editor on Chromebook
Up until recently, there was also incidental support for ChromeOS users to upload to 3rd party compatibles and derivatives of those official boards boards (such as your "Pitsco PRIZM Robotic Controller") that use a general purpose USB to serial bridge chip (e.g., FTDI FT232R, Silicon Labs CP2102, WCH CH340).
That incidental support for these 3rd party boards was lost during a recent rewrite of Cloud Editor.
At this time, I can suggest some possible solutions for affected users:

Use Cloud Editor on a Linux, macOS or Windows machine (the issue is specific to ChromeOS machines).
Use one of the officially supported Arduino boards (I understand this option is less reasonable in the case where the supported boards are not a drop-in hardware replacement, as is the case with @Ray Salemi's "PRIZM Robotic Controller", but wanted to mention it for the benefit of others who have a clone-ish derivative board).

The impact on ChromeOS users only emerged a matter of days before the time I write this answer so there is a chance the situation will evolve. If other options become known or available, I'll make an update as appropriate so stay tuned.

Thank you for the detailed answer!

One note: the cloud editor cannot find the PRIZM on a Mac using Chrome.    The MacOS IDE  (and Windows IDE) still support the PRIZM.

cloud editor cannot find the PRIZM on a Mac

I'm confident the problem has a different cause than the problem you experienced on the ChromeOS machine. So the new problem should be addressed separately.
You can make a new question here on SE if you like. However, I personally don't have an answer on hand as was the case with the ChromeOS question. In this case where a significant back and forth between user and support technician may be required, Arduino Forum might be a better platform. If you make a post over there I'll be sure to see it and help as I can.

source: Stack Exchange

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

sort: votes


text:
Program Arduino using Eclipse on Mac in 2022
I started experimenting with Arduino a few weeks ago. My host is Mac OS and I have used Eclipse for many years, so my first choice is to use an Eclipse plugin. The most recent discussion of the Eclipse/Arduino solution is years old and I have been unable to get anything working.
The marketplace has "Sloeber, the Arduino Plugin for Eclipse". When I try to install this I get these errors:
An error occurred while collecting items to be installed
session context was:(profile=_Applications_Eclipse_embedcpp-2022-12_Eclipse.app_Contents_Eclipse, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
No repository found containing: osgi.bundle,org.eclipse.nebula.cwt,1.1.0.202212191054
No repository found containing: osgi.bundle,org.eclipse.nebula.widgets.cdatetime,1.5.0.202212191054
No repository found containing: osgi.bundle,org.eclipse.nebula.widgets.oscilloscope,1.4.0.202212191054
No repository found containing: org.eclipse.update.feature,org.eclipse.nebula.widgets.oscilloscope.feature,1.4.0.202212191054
No repository found containing: osgi.bundle,org.eclipse.nebula.widgets.oscilloscope.source,1.4.0.202212191054

for Sloeber problem go to "Install New Software" and change the url for nebula repository to https (or http? I think you need both http and https url for successful install of that component.)

Thanks, I copied the nebula repository to a 'http' url and installed "Nebula Release all Widgets and Examples" manually from there. Then I installed Sloeber (trusting the certificate) and that seems to have worked. So it is now installed and I can try to figure out how to use it. This was a simple solution and much appreciated.

It is working!! I created a new sketch, implemented a version of 'Hello, World' for Eclipse and got this output in the console:
setup
Eclipse Hello

I am using the Sloeber plugin now. The installation required changing the nebula repository to url to "http" in the "Install New Software" as described by Juraj in the first comment.
However, connecting from Sloeber to the Arduino was unreliable at first. Following Juraj's suggestion, I've been deleting and rebuilding the serial connection after each upload or power cycle to form a connection reliably.
If I forget to reset the serial connection it sometimes forms a partial connection where the host can see serial output from the Arduino but not be able to send commands back.

what Arduino do you use? for Arduinos with native USB a reset always disconnects USB, then the bootloader connects, then the sketch connects. It is better to disconnect Serial Monitor before upload for Arduinos with native USB.

It is an Elegoo Mega 2560 R3. I've been doing software for a long time but this is my first attempt to work with hardware.

so a Mega shouldn't have this problem. I use Sloeber 5 years now and I never had problems with Mega

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


text:
I need a 10KHZ PWM signal from pin 3 and 11 using timer 2
The op of pin 11 should be inverse of pin 3. I used digitalreadfast and digitalwritefast and used simple if else. But the delay is high as 10us. What should i do?
I found this code in forum but its form timer 1. I need it for timer 2.
void setup()
  {
  // Defining PB1 and PB2 as outputs by setting PORTB1 and PORTB2
  // Setting DDB1 and DDB2
  DDRB |= bit (DDB1) | bit (DDB2);

  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A = bit (COM1B0) | bit (COM1B1)  // Set OC1B on Compare Match, clear
                                        // OC1B at BOTTOM (inverting mode)
         | bit (COM1A1)                 // Clear OC1A on Compare Match, set
                                        // OC1A at BOTTOM (non-inverting mode)
         | bit (WGM11);                 // Fast PWM, top at ICR1
  TCCR1B = bit (WGM12)  | bit (WGM13)   //       ditto
         | bit (CS11);                  // Start timer, prescaler of 8

  // Initialize OCR1A = 300 (pulse_width = 150us), OCR1B, and ICR1
  ICR1 = 0xFFFF;
  OCR1B = 299;
  OCR1A = ICR1 - OCR1B;

  }  // end of setup

void loop()
  {
  }

What should i do? ... use an inverter

With fast PWM mode on timer2, pin 11 cannot be used. Only pin 3. See : https://forum.arduino.cc/t/atmega328p-timer2-fastpwm-mode/499500 .
If you need the inverse of pin 3, then a simple inverter (say an transistor) can be used as @jsotola has suggested.

You can't do it with Timer 2 without external hardware. This code will generate a 10 kHz signal on pin 3, however it uses both of the timer's registers to do that:

OCR2A is used to set the period (ie. the frequency)
OCR2B is used to set the duty cycle

const byte OUTPUT_PIN = 3;  // Timer 2 "B" output: OC2B

const byte n = 199;  // 10 kHz

void setup()
 {
  pinMode (OUTPUT_PIN, OUTPUT);

  TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2A on compare
  TCCR2B = bit (WGM22) | bit (CS21);         // fast PWM, prescaler of 8
  OCR2A =  n;                                // period
  OCR2B = ((n + 1) / 2) - 1;                 // 50% duty cycle
  }  // end of setup

void loop() { }

Note that a 50% duty cycle signal could be generated in CTC mode, with the outputs set to “toggle on compare match”.

and here, to complete the picture, is an NPN transistor configured as an inverter (NOT gate) https://www.tutorialspoint.com/build-an-inverter-with-a-transistor

@EdgarBonet I tried at some length to get the inverted signal as well in various modes, but failed.

Did you try writing a “Force Output Compare” bit?

@EdgarBonet  That doesn't seem to affect anything. According to the datasheet the effect only occurs when writing to that bit, not on an ongoing basis. In my testing, in CTC to OCR2A mode (010) the two outputs are out of phase, but not inverses of each other. In fact, they seem to be 50% out of phase with each other (for some reason). In mode 101 (PWM to OCR2A) I get no output (ie. 0V) on output B (D3).

And with this: TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2A0) | bit (COM2B0)  | bit(COM2B1); and TCCR2B = bit (CS21) | bit (WGM22); the B output is in phase with the A output but twice the frequency.

As explained in Nick Gammon's answer, you cannot really generate two PWM
signals at 10 kHz from Timer 2: the register OCR2A will be
used to set the frequency, and you won't have independent control of the
duty cycle of the OC2A output.
You can, however, make two 10 kHz complementary signals at 50% duty
cycle. This is not really PWM (pulse width modulation), as you cannot
actually modulate the pulse width. If this fits your needs, the
solution is to configure the outputs in toggle mode. Writing the
“force output compare B” bit creates an extra toggle of OC2B, which
ensures that the outputs have then opposing phases. Here is the code to
do that:
void setup() {
    TCCR2B = 0;           // stop Timer 2
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2A0)  // toggle OC2A on compare match
           | _BV(COM2B0)  // toggle OC2B on compare match
           | _BV(WGM21);  // mode 2 = CTC, TOP = OCRA
    OCR2A  = 99;          // timer period = 100 * 2 * 8 / C_CPU
    OCR2B  = 99;          // toggle OC2A and OC2B simultaneously
    TCCR2B = _BV(CS21)    // clock @ F_CPU/8
           | _BV(FOC2B);  // force output compare B: invert OC2B signal
    DDRB  |= _BV(PB3);    // OC2A = PB3 = digital 11 as output
    DDRD  |= _BV(PD3);    // OC2B = PD3 = digital 3 as output
}

void loop(){}

Congratulations! You got it to work! As you say, you are limited to 50% duty cycle, still that is what the OP wanted - I think.

In case anyone is wondering, _BV and bit are virtually identical. In hardware/arduino/avr/cores/arduino/Arduino.h bit is defined as follows: #define bit(b) (1UL << (b)) and in hardware/tools/avr/avr/include/avr/sfr_defs.h _BV is defined as: #define _BV(bit) (1 << (bit)).


text:
STM8 Development Board with Arduino IDE
I got one of these cheap STM8 boards from China and was hoping to find a way to use this with arduino code.

Does anyone know of an arduino boot loader and board package that works with them ?

you get nothing with these links !!!!

Start the Arduino-IDE. In File->Preferences, Settings tab, enter
https://github.com/tenbaht/sduino/raw/master/package_sduino_stm8_index.json
Open Tools->Board:...->Boards Manager
Find Sduino by typing 'sd' into the search line
Click on the list entry
Click on Install.
This link is more comprehensive
https://tenbaht.github.io/sduino/

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.

Hi, thanks for your reply. So how would I get started with programming this in the arduino IDE? There is a whole community around the STM32 and it's use with the arduino IDE, I followed some simple instructions from stm32duino.com to get going with the stm32. Is there an equivalent with this STM8 board?

Not to my knowledge, unfortunately. The stm32duino site has links to my stm8duino port on GitHub if you wish to try. It does require the iar workbench however .

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


text:
arduino + mpu6050 + nrf24l01 >>>>>>>>>>>>nrf24l01 + arduino ( Not running fluently)
this is my setup: I have an arduino uno + mpu-6050 + nrf24l01 all attached together and am transmitting data from that mpu-6050 to another arduino with an nrf24l01 attached to it. I got the arduinos to communicate with each other and transmit data ( ypr) wirelessly but it's still laggy and jumpy. Before I was getting FIFO overfull messages but I managed to somewhat fix that. Yet the data being transferred is still not running to stable nor smoothly. PLEASE HELP ME find the problem why these arduinos aren't transferring data fluently and smoothly. I posted the Receiver and transmitter codes down below. Also, I am illustrating the code on Processing 3.2.3, hence the teapot parts. THANK YOU
**************************RECEIVER*****************************************
{
    #include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

// format used for the InvenSense teapot demo
#define OUTPUT_TEAPOT

RF24 radio(7, 8);//pin assignment
unsigned long t0;
unsigned long t1;
float ypr[3];
uint8_t teapotPacket[14] = { };

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

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

  radio.begin();
  radio.openReadingPipe(1, 0xF0F0F0F0A1LL);
  radio.openReadingPipe(2, 0xF0F0F0F0A2LL);

  radio.startListening();
  t0=0;
}
byte pipeNum=0; //variable to hold which reading pipe sent data
void loop()
{
  t1=millis();
  /*digitalWrite(13,HIGH);
  delay(500);
  digitalWrite(13,LOW);
  delay(500);
  */
  if (t1-t0>100){
  if (radio.available(&pipeNum))
  {

    typedef struct YPR_RX {
      int y;
      int p;
      int r;
    } YPR_RX;
    YPR_RX ypr_rx;

    //radio.read(&ypr_rx, sizeof(ypr_rx));
   // teapotPacket = new uint8_t teapoPacket(radio.getPayload)

    radio.read(&teapotPacket, sizeof(teapotPacket));
   // radio.read(&teapotPacket, sizeof(radio.getPayloadSize()));
//    radio.SetDatarate();
    uint8_t newTeapot[14] = {'$', 0x02, teapotPacket[2],teapotPacket[3],teapotPacket[4],teapotPacket[5],teapotPacket[6],
                                        teapotPacket[7],teapotPacket[8],teapotPacket[9], 0x00, 0x00, '\r', '\n' };
    Serial.write(newTeapot, 14);
    newTeapot[11]++;

            Serial.print(newTeapot[2]);
            Serial.print("\t");
            Serial.print(newTeapot[3]);
            Serial.print("\t");
            Serial.print(newTeapot[4]);
            Serial.print("\t");
            Serial.print(newTeapot[5]);
            Serial.print("\t");
            Serial.print(newTeapot[6]);
            Serial.print("\t");
            Serial.print(newTeapot[7]);
            Serial.print("\t");
            Serial.print(newTeapot[8]);
            Serial.print("\t");
            Serial.println(newTeapot[9]);

/*
    Serial.print(ypr_rx.y);
    Serial.print("\t");
    Serial.print(ypr_rx.p);
    Serial.print("\t");
    Serial.print(ypr_rx.r);
    Serial.print("\t");
    Serial.println();
    */

    t0=t1;

    //Serial.println("X-acceleration");
    //int number=atol(text);
    //Serial.println(number);
    //Serial.println((int)text);
    //Serial.println(value);
    //delay(100);

  }
  }

}
}

*********************************TRANSMITTER************************************
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

// format used for the InvenSense teapot demo
#define OUTPUT_TEAPOT

RF24 radio(7, 8);//pin assignment
unsigned long t0;
unsigned long t1;
float ypr[3];
uint8_t teapotPacket[14] = { };

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

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

  radio.begin();
  radio.openReadingPipe(1, 0xF0F0F0F0A1LL);
  radio.openReadingPipe(2, 0xF0F0F0F0A2LL);

  radio.startListening();
  t0=0;
}
byte pipeNum=0; //variable to hold which reading pipe sent data
void loop()
{
  t1=millis();
  /*digitalWrite(13,HIGH);
  delay(500);
  digitalWrite(13,LOW);
  delay(500);
  */
  if (t1-t0>100){
  if (radio.available(&pipeNum))
  {

    typedef struct YPR_RX {
      int y;
      int p;
      int r;
    } YPR_RX;
    YPR_RX ypr_rx;

    //radio.read(&ypr_rx, sizeof(ypr_rx));
   // teapotPacket = new uint8_t teapoPacket(radio.getPayload)

    radio.read(&teapotPacket, sizeof(teapotPacket));
   // radio.read(&teapotPacket, sizeof(radio.getPayloadSize()));
//    radio.SetDatarate();
    uint8_t newTeapot[14] = {'$', 0x02, teapotPacket[2],teapotPacket[3],teapotPacket[4],teapotPacket[5],teapotPacket[6],
                                        teapotPacket[7],teapotPacket[8],teapotPacket[9], 0x00, 0x00, '\r', '\n' };
    Serial.write(newTeapot, 14);
    newTeapot[11]++;

            Serial.print(newTeapot[2]);
            Serial.print("\t");
            Serial.print(newTeapot[3]);
            Serial.print("\t");
            Serial.print(newTeapot[4]);
            Serial.print("\t");
            Serial.print(newTeapot[5]);
            Serial.print("\t");
            Serial.print(newTeapot[6]);
            Serial.print("\t");
            Serial.print(newTeapot[7]);
            Serial.print("\t");
            Serial.print(newTeapot[8]);
            Serial.print("\t");
            Serial.println(newTeapot[9]);

/*
    Serial.print(ypr_rx.y);
    Serial.print("\t");
    Serial.print(ypr_rx.p);
    Serial.print("\t");
    Serial.print(ypr_rx.r);
    Serial.print("\t");
    Serial.println();
    */

    t0=t1;

    //Serial.println("X-acceleration");
    //int number=atol(text);
    //Serial.println(number);
    //Serial.println((int)text);
    //Serial.println(value);
    //delay(100);

  }
  }

}

Could you please describe a bit more, what's the exact issue you have? As "not stable and smooth" is rather generic.

Why does the receiver do a 100 ms wait?

@avamander The problem it doesn't have regular readings. Like when I have the mpu-6050 plugged directly into my computer the readings run smoothly and dont lag. When I make wirelessly, the information lags some and its all skippy along with some lag. Especially when I put it on Processing for visuals, it lags and randomly skips readings. I'm just not sure what the problem is, maybe something with the buffer?

As always with nRF24L01+, attach a 1000uF electrolytic capacitor to the GND and 3.3V on the module itself.

The possible problem could be with the hardware setup? Could it not be something with the code itself?

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


text:
Having trouble connect nrf24l01 to arduino micro and arduino uno!
I'm trying to connect a nRF24L01 with my Arduino Micro and Arduino Uno. The Arduino Uno works fine, but it doesn't talk with the Arduino Micro. CE is on pin 7 and CSN on pin 8. I posted the code down below into 2 Arduino IDE screens and changed one screen bool radioNumber = 1 and bool role = 1 and the other screen bool radioNumber = 0 and bool role = 0 so that they could communicate. However, the program with the Arduino Micro doesn't seem to work with pins 7 and 8. Is it code where something is wrong or do I need to change the pins and code? How do I make them both communicate with each other?
/*
* Getting Started example sketch for nRF24L01+ radios
* This is a very basic example of how to send data from one node to another
* Updated: Dec 2014 by TMRh20
*/

#include <SPI.h>
#include "RF24.h"

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 0;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);
/**********************************************************/

byte addresses[][6] = {"1Node","2Node"};

// Used to control whether this node is sending or receiving
bool role = 0;

void setup() {
  Serial.begin(115200);
  Serial.println(F("RF24/examples/GettingStarted"));
  Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));

  radio.begin();

  // Set the PA Level low to prevent power supply related issues since this is a
 // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  radio.setPALevel(RF24_PA_LOW);

  // Open a writing and reading pipe on each radio, with opposite addresses
  if(radioNumber){
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1,addresses[0]);
  }else{
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
  }

  // Start the radio listening for data
  radio.startListening();
}

void loop() {

/****************** Ping Out Role ***************************/
if (role == 1)  {

    radio.stopListening();                                    // First, stop listening so we can talk.

    Serial.println(F("Now sending"));

    unsigned long start_time = micros();                             // Take the time, and send it.  This will block until complete
     if (!radio.write( &start_time, sizeof(unsigned long) )){
       Serial.println(F("failed"));
     }

    radio.startListening();                                    // Now, continue listening

    unsigned long started_waiting_at = micros();               // Set up a timeout period, get the current microseconds
    boolean timeout = false;                                   // Set up a variable to indicate if a response was received or not

    while ( ! radio.available() ){                             // While nothing is received
      if (micros() - started_waiting_at > 200000 ){            // If waited longer than 200ms, indicate timeout and exit while loop
          timeout = true;
          break;
      }
    }

    if ( timeout ){                                             // Describe the results
        Serial.println(F("Failed, response timed out."));
    }else{
        unsigned long got_time;                                 // Grab the response, compare, and send to debugging spew
        radio.read( &got_time, sizeof(unsigned long) );
        unsigned long end_time = micros();

        // Spew it
        Serial.print(F("Sent "));
        Serial.print(start_time);
        Serial.print(F(", Got response "));
        Serial.print(got_time);
        Serial.print(F(", Round-trip delay "));
        Serial.print(end_time-start_time);
        Serial.println(F(" microseconds"));
    }

    // Try again 1s later
    delay(1000);
  }

/****************** Pong Back Role ***************************/

  if ( role == 0 )
  {
    unsigned long got_time;

    if( radio.available()){
                                                                    // Variable for the received timestamp
      while (radio.available()) {                                   // While there is data ready
        radio.read( &got_time, sizeof(unsigned long) );             // Get the payload
      }

      radio.stopListening();                                        // First, stop listening so we can talk
      radio.write( &got_time, sizeof(unsigned long) );              // Send the final one back.
      radio.startListening();                                       // Now, resume listening so we catch the next packets.
      Serial.print(F("Sent response "));
      Serial.println(got_time);
   }
 }

/****************** Change Roles via Serial Commands ***************************/

  if ( Serial.available() )
  {
    char c = toupper(Serial.read());
    if ( c == 'T' && role == 0 ){
      Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
      role = 1;                  // Become the primary transmitter (ping out)

   }else
    if ( c == 'R' && role == 1 ){
      Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
       role = 0;                // Become the primary receiver (pong back)
       radio.startListening();

    }
  }

} // Loop

What's the output of .printdetails() function that exists in the library (you may need to include printf.h and also init printf)?

Use millis() and 200 or 200000L in wait for radio.available() block. Statement micros() - started_waiting_at > 200000 is not what you might think.

The output for the transmitter says, " now sending" then after that says "failed, Failed response timed out". For the receiver it just says "sent response 23424332" and then it continues to say "sent reponse" but then with different numbers after that. When I use two arduino unos with same program it works fine. But when I add an arduino micro, it just keeps saying it failed. This what I'm trying to figure out, why it works on arduino uno and not micro


text:
What pin is the external interrupt #0 for an arduino micro?
I'm putting an MPU6050 on an arduino Micro but the interrupt is different than the arduino uno. The external interrupt #0 pin on an arduino uno is pin 2 but its not pin 2 on an arduino micro. So I'm trying to figure out what pin it is on an arduino micro

The ATmega32U4 pin mapping says 3.

But pin 3 is the SCL. I'm using that pin to communicate an nrf24l01

Well, you have the mapping now. Pick something.


text:
Is it possible to write URLs to RFID tags with the RC522? If so, how?
I've been trying to research to answer this question for a long time, but could not figure out the answer. I know how to code like bytes of information, but not URLs. More specifically, when you code information into a MiFare RFID tag with the RC522 device, each byte goes into separate byte blocks of a sector. They are not combined, meaning the link cannot be read. How do you overcome this and is this even possible?

http://asciitable.com/

that makes sense now ... why is it that your question does not say that? .... edit your question and delete the comments


text:
Connecting MPU6050 to Arduino Lilypad
To preface, I am very new to Arduino and I watched this video on YouTube.
It shows how you can build a motion controlled car with Arduino and I decided to make this for my school project.
One thing I am having difficulty with is connecting the MPU6050 to the Lilypad. In the video he doesn't really show much of it and just sticks it onto the board.
However, do I need to solder the MPU6050? Where do I solder the pins the underside or the top. Do I need to align the pins with that of the Lilypad?
Sorry if it's a stupid question I genuinely don't know.
The current condition of our lilypad:

What it's supposed to look like:

If you see the images, in addition to the yellow light of the MPU 6050 and the red light of the HC 05, the red light of the Lilypad is also supposed to light up like the second picture, however in ours, only the MPU 6050 and the HC 05 lights up and not the Lilypad.

In This tutorial explains how to connect MPU6050 to an Arduino.

Since you seem to need some orientation, I will explain a few things, to get you started.
The MPU6050 is a device, that communicates through the I2C interface. It uses 2 communication lines (SCL for the clock and SDA for the data). To use is with the Lilypad, you have to connect those two lines, Vcc (5V) and Ground. If you look at a pinout diagram, you can identify, which of the pads are SDA and SCL on the Lilypad.
It is up to you, if you connect the mentioned lines via soldering or by other means. Normally you would solder connecting wires between the MPU6050 and the Lilypad. If you want the MPU to be removable, you can solder a cable with a pin header (for example female) to the Lilypad and the according pins to the MPU (for example a male pin header). That way, you could also stick the MPU to the board and remove it again if necessary. How you are doing it is not important, as long as the electrical contact is good.

There are also a lot of tutorials and ready to use libraries for the MPU6050 on the net. newbie already posted a link to a tutorial. Also Adafruit has a library on github with examples, that explain how to use it. That way you should be able to get started with your project.
Good luck!

Thanks for the help but there is still a problem, can you please check the images that I uploaded above? The LED of the Lilypad is not lighting up even though the other two are and I'm very confused. I already connected the Lilypad and the MPU 6050 like you said with female jumpers and pin headers.

Edit: I briefly used a 9V battery, is that a problem? Also, I haven't uploaded the code into theLilypad

A 9V block battery is not a good choice, because it can only provide low current (it is only meant for low current applications). Better a series of AA batteries or a LiPo pack (though I don't have much experience with this)

You need to solder the pins of the MPU6050, making sure to solder the pins to the bottom of the module for easy connection to the LilyPad. When soldering, ensure that the pins are aligned with the pins on the LilyPad for proper connection.
As for the LilyPad not lighting up, one reason could be that your LilyPad is not receiving proper power. The LilyPad typically can be powered with 3.7V to 5V, so you might want to check your battery. It could also be that you haven't uploaded the code; if there is no part in the code that controls the LED, the LilyPad may not light up.


text:
What is the correct way to create large project files?
I am currently working on a 10x10 RGB LED screen (using Neopixels from Adafruit) and my project files are starting to get rather large.
I have several different devices used in this project:

The LED matrix
A DS3232 RTC
An MSGEQ7 DSP chip
7 push button switches

Currently i'm using separate classes for each of the devices (RTC, DSP & buttons) as well as the Adafruit GFX and Neopixel library.
What would be the best way to organize this project? Should I put the patterns for the screen in the main.ino file or should they have their own class.
Any help would be greatly appreciated, I can upload the source code if its needed.
Cheers
As a side note, I'm using "Sublime Text 3" along with Stino.

i throw the major parts in their own file/tab. these have names like "main", "server", "adc", "sdcard", "utils", etc

Good to hear you are splitting large amount of code, it will benefit you a lot in the long run.
It's very hard to say what is best, it depends on the interaction of those patterns with other classes. Normally it is best to put them in the location where they BEST belong to, i.e. where the least association with other classes exist.
If it has a lot of interactions, maybe you should put the patterns itself in a different class.
Normally what I keep as guidelines:
- Not more than a few hundred lines in a class
- Not more than 7 (class) variables in a class
- Not more than 7 functions/methods in a class
Of course these are guide lines. If you have a lot of simple (constant) pattern definitions the file will become larger without getting more hard to understand.
Also try to think of a class to have only ONE responsibility. If you want to be serious about splitting classes or how to organize them, read about SOLID.

Nice one cheers, i'll look in to SOLID.


text:
ESP8266 Library Method List
Is there a place that lists all the common methods used with the standard ESP8266 libraries in Arduino?

Look in the source.

The headers (.h files) specifically.

Is the source even stored locally on my computer or does the compiler grab it from the internet when it builds the project? I only ask because I cannot locate the source files.

Its held locally.

Looking at the GitHub page, there is a document explaining how everything works, https://arduino-esp8266.readthedocs.io/en/latest/


text:
I don't have "Process" header
I'd like to run an application on my system after pushing a button on an Arduino shield. I've read that I need to use the runShellCommand() function, which can be accessed from a Process header. However when I add the #include <Process.h> line to my program I'm getting this error:
.build/uno/src/sketch.cpp:2:21: fatal error: Process.h: No such file or directory
 #include <Process.h>

I'm using Ubuntu 14.04 and I've installed Arduino software from repositories.

Whatever unspecified guide you are following is at minimum incomplete, and probably outdated too.  Note that nothing you do in an Arduino sketch on an Uno is going to run commands on a Linux box, without help of software/configuration on the Linux box to accept them.  It may be better to come up with a program on the Linux box which waits for specific serial output from the Arduino sketch and then performs a preset command or operation.

"It may be better to come up with a program on the Linux box which waits for specific serial output from the Arduino sketch "  Can you suggest me how to do that or direct me to some guide about that ? I really need this functionality

Learn how to accomplish serial communication and subprocess execution in the programming language of your choice.

That only works on an Arduino Yún (as described in this tutorial).


text:
Detecting I2C transfer with LED
I am going to do a project with a lot of Arduinos connected via I2C, where like of them can became master for a moment to announce an event. So I would like to see how much is the bus used. As there will be a central point, I thought about putting a LED there, from +5V to clock line, so it would shine when the transfer occurs and be black when the line is free. And so I would be able to guess the utilisation level of the bus. (The clock is effectively PWM going to zero often while in transfer, while being plain +5V when no transfer is active).
Of course direct connection is not the best idea, as it would disrupt the pull-ups and mess with the protocol (as it would drain a lot of power to clock each time it went down), there should be some separator/amplifier.
The question is - does anybody know a simple setting, where the LED would be driven by a small current to zero (that is inverting amplifier as simple as possible with high enough input impedance to not disturb I2C communication)?
Thanks for all hints :)

Just get one of the modern high power blue leds. Those will light up with as little as 0.1mA, perhaps even lower. Calculate the appropriate high value resistor to get this very low current.

Thank you, I tried it and it worked even with clasical red LED (as I have no blue at hand just now) and 2K resistor (so approx 1mA), but it was bad visible, especially for short transmitions. Still it worked reliably with 30 cm long wires (and worked even with just 330R resistor, which was easy to spot - but I would not like to test it under noise on robot), so I finally set it with bipolar PNP with emitor on Vcc, base over 2K to clock and colector over 330R + red LED to GND. Shines nice too, drains just about 2mA from I2C. (If you want, make it answer and I will accept it)

It can be done with two N-channel MOSFETs or one P-channel MOSFET (depending on what you have locally / can get / is in your bits box):

simulate this circuit – Schematic created using CircuitLab
In the left schematic the first MOSFET acts like a NOT gate, and the second is a simple low-side switch. The pair together make an active-low low-side switch.
The right hand schematic, which is somewhat simpler, uses a single P channel MOSFET as a high-side switch. This is normally driven with an N-channel MOSFET to invert the logic, since it is naturally active-low. You don't want that, so you can just connect direct to the gate.
Note that all MOSFETs are "logic level" with a threshold voltage below 3V (or -3V in the case of the P-channel).

Thanks you too. I had not MOSFET at hands, so I used bipolar PNP and 2K resistor to its base (as 4k did not open it fully) in the second schema (inverted logic). Works like a charm :)


text:
How do I use interrupt service routines inside libraries and classes?
I'm trying to have a millis() timer run to emulate a hardware timer inside a library, but I'm having issues compiling the code. I want the callback (pseudo ISR) to be part of the class, and not use global variables.
I'm using Christensen's / Monk's Timer library, but I'm open to suggestions if there are other better/easier timer libraries out there.
This is what I have so far. It's just an example for me to understand how this might work. I'm sure there are better ways of making an LED blink, but this is just for illustrative purposes.
Compiling gives a bunch of "invalid use of member variables in static functions" errors.

error: invalid use of member 'Blink::_led_status' in static member function
           int _led_status;

EDIT
After trying to add glue routines as per your other answer I can seem to get one instance working, but adding another stops the first light from blinking, and the second one blinks on and off at the wrong times.
The test library is on github
Blink.h
#ifndef Blink_h
#define Blink_h

#include "Arduino.h"
#include <Timer.h> // https://github.com/JChristensen/Timer/master
    // Timer.h uses millis() instead of built in timers

class Blink {
public:
  Blink (int led_pin, int duration);
  void begin ();
  void updateTimer();

private:
  static void _callbackGlue();
  void _callback();

  static Blink *_instance;
  Timer *_blink_timer;
  int _led_pin;
  int _duration;
  int _led_status;
  int _blink_event;
};
#endif

blink.cpp
#include "Arduino.h"
#include "Blink.h"

Blink *Blink::_instance;

Blink::Blink (int led_pin, int duration) {
  _blink_timer = new Timer();
  _led_status = 0;
  _led_pin = led_pin;
  _duration = duration;
  pinMode(_led_pin, OUTPUT);
  digitalWrite(_led_pin, LOW);
}

void Blink::begin () {
  _blink_event = _blink_timer->every(_duration, _callbackGlue);
  _instance = this;
}

void Blink::_callbackGlue() {
  _instance->_callback();
}

void Blink::_callback() {
  if (_led_status == 0) {
    digitalWrite(_led_pin, HIGH);
    _led_status = 1;
  } else if (_led_status == 1) {
    digitalWrite(_led_pin, LOW);
    _led_status = 0;
  }
}

void Blink::updateTimer() {
  _blink_timer->update();
}

test/test.ino
#include "Blink.h"

Blink first_blink (13, 500);
//Blink second_blink (12, 1000);

void setup() {
  Serial.begin(9600);
  Serial.println("Starting...");
  first_blink.begin();
  //second_blink.begin();
}

void loop() {
  first_blink.updateTimer();
  //second_blink.updateTimer();
}

I think this is a duplicate of Pass class's public function as an argument to external command - see my answer there.

@NickGammon Thanks for pointing me to your other answer. After trying to follow your example from the other answer, I was seemingly able to get a single instance working, but adding another blink object stops the first one from working, and the second one blinks randomly.

Yes, well you only have one instance variable. You can't easily work around this. Classes (can) have multiple instances. For a static function to know which one to use you need to help it. The instance variable is static so there is only one copy of it.

Nick Gammon's answer is good for one Timer - but now you want two!
OK, then you can take advantage of the Timer Library's context parameter. What's that? If you take a look at the header for every(), you'll see as well as passing in the function to call, you can also pass in another value (called context) to pass back to that function when it fires*. So instead of you remembering just one copy of instance, get each Timer to remember it for you.

*If you can't see the context parameter in Timer.h, then make sure you're using the v2.1 branch, not master.

So:

Get rid of _instance everywhere.
Change:
static void _callbackGlue();
to
static void _callbackGlue(void *context);
Change:
void Blink::_callbackGlue()
{
_instance->_callback();
}
to
void Blink::_callbackGlue(void *context)
{
((Blink *)context)->_callback();
}
Change:
_blink_event = _blink_timer->every(_duration, _callbackGlue);
to
_blink_event = _blink_timer->every(_duration, _callbackGlue, this);

Note that I've submitted these changes as a Pull Request on your GitHub repo.

Incidentally:
You don't need _blink_timer to be a pointer. Get rid of the *, get rid of the line with new Timer() in it, and replace all your _blink_timer-> with _blink_timer.

Thanks, that worked great. Is the only downside to using pointers to objects that you have to manually delete the pointer when deleting its parent?

Sort of. Yes, that's a concern, but new also uses heap (which is inefficient in both memory and time). By having it as a sub-object it merely makes the parent larger. Plus with pointers you have to use -> everywhere. Once you program enough, you'll get into the habit of thinking "Wait! Is that pointer actually 0?" No pointer: no test.

You may add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.
More about this trick in this article here.


text:
Using internal voltage reference for sensor
i am using 3.7~4.2V lithium battery. I am using internal voltage reference to read constant battery voltage as we know that the battery voltage level depletes overtime. The problem is that my sensor (mini solar panel) reads max value under little light and does not go beyond that level no matter how much light falls onto it in the later stage.

Comments have been moved to chat; please do not continue the discussion here. Before posting a comment below this one, please review the purposes of comments. Comments that do not request clarification or suggest improvements usually belong as an answer, on [meta], or in [chat]. Comments continuing discussion may be removed.

The problem is that my sensor (mini solar panel) reads max value under little light and does not go beyond that level no matter how much light falls onto it in the later stage.

Open voltage is not a good way to read the light level hitting a solar panel in this situation. Much better is to measure the current generated by the solar cell by adding a resistor across it here...

The value of the resistor can be found using...
V=IR
... where ...
V=1.1 volts
I=the maximum current the solar cell can generate in full light
If you do this, then you can read the A1 pin using the 1.1V ref and you will be able to measure the full range of light conditions using the solar cell with simple Arduino code like this..
analogReference(INTERNAL);  // a built-in reference, equal to 1.1 volts
int v=analogRead(A1);       // Returns value 0-1023 representing light level

PS: Note if you measure the battery voltage with a divider as shown, you will be drawing current (about 0.8 milliamps when the battery reaches its minimum voltage) ALL THE TIME - even when the circuit is off. You do not want to do this with a lithium battery since under-voltaging it can potentially cause permanent damage to it. You really should heed my answer to your other question here.
PPS: It is usually best to ask your real question directly rather than asking a bunch of questions that are synthetic and reflect problems you think you have rather than the problems you actually do have. Your supplied code and drawings should match the thing you are asking and the thing you are actually working on (and each other!). It is often the case that the problem is not where you think it is, and so showing code and drawings that do not reflect what is really going on just wastes people's effort and does not ultimately help you solve your real problem. :)

"Then how do i reduce my battery voltage to Vref?" The best way to measure the voltage of your power source is by measuring the 1.1V ref against Vcc as suggested in my answer to your other question and the article linked there.

" If i connect resistor on the solar end, the current drawn would increase and it would result into slow battery charging which again is not a suitable option for the specific project. " You question is about using a solar cell as a sensor to measure the light level. This answer tells you a good way to do that. If you are using the solar cell to charge the battery, then this is not represented in the question, in the code, or in the drawing so it is hard for us to help you with that! :) And note that charging a battery is a very different thing than using it as a light sensor.

These are all very different things that what is asked in this question and your others. Do note that charging a lithium battery is non-trivial and is not as easy as just connecting a solar cell to it. Check out https://batteryuniversity.com/article/bu-409-charging-lithium-ion for some info.

Your code above has many problems and does not compile. Best way to solve this problem (or any problem) is to find the minimum code and circuit that reproduces the problem and post that, along with (1) what you want to have happen, (2) what actually happens with the supplied code and circuit. For me, very often just systematically following these steps will actually end up with me solving the problem myself - but if not then at least you make it easy for other people to help you when you post it.

For example, in printVolts(), you use the variable val even though it does not exist here.   My guess is that in your code you are unintentionally switching between the 5V and 1.1V references because you are sometimes using the Arduino functions sometimes changing the registers directly. Also note  that with your current resistor values that you can not measure the battery voltage with the 1.1V ref because the output voltage can be higher than 1.1V even at the lowest possible battery voltage.


text:
if statement with string comparison
Code Snippet:
String a;

const int red_led_pin = 13;

void setup()
{
  Serial.begin(115200);
  Serial.println("Hello, ESP32-S2!");
  pinMode(red_led_pin, OUTPUT);
}

void loop() {

    while (Serial.available())
    {
        a = Serial.readString();// read the incoming data as string
        Serial.print(" First: ");
        Serial.println(a);

        if (a.equals("on"))
        {
          Serial.println("LED ON");
          digitalWrite(red_led_pin, HIGH);

        }

        else  if (a == "off" || a == "OFF")
        {
          Serial.println("LED OFF");
          digitalWrite(red_led_pin, LOW);
        }

        Serial.print("Second: ");
        Serial.println(a);
    }
}

Serial.print out:

Circuitry:

Issue:
The code can't capture the on string or any other string (on, off or OFF) that I pass. However it does pick it up and Serial.print it.
What is going wrong?
Things I have tried:
I have tried as a comparison:

if (a.equals("on")){<>}
if (a == "on")){<>}
if (a.equalsIgnoreCase("on")){<>}

Due Diligence / Prior Research:

[ Documentation ] String Comparison Operators
[ Documentation ] String()
[ Forum ] Compare characters (or string) in “if” function

What line ending have you set in the Serial Monitor? My guess is, that the Serial Monitor sends a line ending after the actual data, which gets included by Serial.readString(), so that the string doesn't equal "on", but for example `"on\n".

@chrisl that was it... Serial.readStringUntil('\n')

Great, I've written a full answer to this question

@chrisl and all. this question is asked often. let's use this Q&A pair as canonical for future duplicates

I'm going to be cheeky and ask for some up votes from the community:)

Your problem is the line ending. The Serial Monitor has an option to send a line ending after the data, that you input. This line ending can be different depending on this setting, though mostly in the Arduino world a simple newline character '\n' is used.
This line ending will be in your string, when using Serial.readString(), so the string is not equal to "on", but to something like "on\n".
You can solve this issue by two ways:

Set the Serial Monitor to no line ending.
Or better: Use something like Serial.readStringUntil() and pass the line ending character to it as parameter (for example Serial.readStringUntil('\n')). This will read from the Serial interface until the specified character is reached. The specified character will be discarded and you are left with only the data, which you can then do comparisons on. This also has the advantage, that your code will react much faster, since it doesn't wait for 1s for new data (as long as you actually send the needed line ending).

if there is a \r too, trim() can help. but as always it is better not to use String


text:
How to wire an ESP32-S2 Dev KitM-1 for power?
I'm putting an Espressif ESP32-S2 Dev KitM-1 into a project box. The box will have 12VDC power and a 5V buck converter for the Dev Kit.
Do I need to use the USB port to power the Dev Kit or can I directly wire 5VDC to the 5V pin (and ground, of course) to power it?

The official documentation has

Power Supply Options
There are three mutually exclusive ways to provide power to the board:

Micro-USB Port, default power supply
5V and GND pin headers
3V3 and GND pin headers


text:
How can I send and receive data from an Arduino MEGA 2560 and Python?
Hello community I am relatively new to the Arduino world and I am facing some issues trying to establish serial communication between the MEGA 2560 and Python using my PC, the desired result is to print the variable 'cnt' after in the code below in Arduino after communicating with Python, below are the codes I am using for the Arduino and in Python. [Note: I am using a PIR sensor(pin 4) that does trigger when an object is nearby and print the first statement on the serial monitor, so the issue is not there.]
Arduino:
int pin = 4; //Output pin of sensor
int cnt = 0; //Count variable after processing in Python
int dat = 0; //Variable to ensure data is being transmitted from Python to Arduino

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT); //This output is here to ensure the code runs to the dat if statement and the data is received
}

void loop() {
    int pirsensor = digitalRead(pin);

    if (pirsensor == 1){
      Serial.println("Hello, there's data here in Arduino"); //String as an example bt you want to send the data of the ArduCAM using the serial port
         if (Serial.available()>0){
              dat = Serial.read() - '0';

              if (dat == '1'){
                    cnt = cnt + 1;
                    Serial.print("Count is equal to: ");
                    Serial.print(cnt);
                    digitalWrite(LED_BUILTIN, HIGH); //Turn on LED
                    }
              }

          }
}

Python code:
import serial

dat = serial.Serial('COM5',9600,timeout=1) #Serial object for communication
if (dat.in_waiting>0): #Conditional to verify if there is data in the serial port
    print('Hello')
    dat.write(1)
    print('Works')

if (dat == 1) would make more sense since you already converted the character to a corresponding digit

Your problem is that you aren't sending the values from python in bytes. A more reliable way is to send the data in bytes like dat.write(b'1') and then receive it on the Arduino using Serial.readString(). I also had many issues with this and this is the best solution. "https://roboticsbackend.com/raspberry-pi-arduino-serial-communication/#:~:text=The%20easiest%20way%20is%20to,Arduino%20IDE)"
If not, you can use the I2C interface. Just be careful, the logic level if your Python is running on a Raspberry Pi.

try with Firmata, it is a protocol that establishes serial communication between the computer with Arduino. All you have to do is have the Firmata on Arduino Board, and pyFirmata plugin available to talk with Arduino from Python on your machine.


text:
Reading input from digital pins 36, 37, 38 in Arduino Mega 2560 is giving a problem
I wrote a program to read digital input from pins 36, 37, 38 and print on LCD when they go HIGH.
I've connected those pins to a switch to test.
The program looks like this:
#include "LiquidCrystal.h"

// initialize the library by providing the nuber of pins to it
LiquidCrystal lcd(8,9,4,5,6,7);
int vswr,th,od,a;

void setup() {
  pinMode(36,INPUT);//SENSING VSWR
  pinMode(37,INPUT);//SENSING THERMAL
  pinMode(38,INPUT);//SENSING OVER DRIVE
  pinMode(35,OUTPUT);//BYTE_CTRL SIGNAL TO SHUTDOWN
  digitalWrite(35,LOW);
}

void loop() {
  vswr = digitalRead(36);
  th= digitalRead(37);
  od = digitalRead(38);
  lcd.begin(16,2);
  // set cursor position to start of first line on the LCD
  lcd.setCursor(0,0);
  if (vswr==1) {
    lcd.write("vswr");
    digitalWrite(35,HIGH);
    delay(2000);
  }
  if (th==1) {
    lcd.write("thermal");
    digitalWrite(35,HIGH);
    delay(2000);
  }
  if (od==1) {
    lcd.write("over drive");
    digitalWrite(35,HIGH);
    delay(2000);
  }
}

When I run this, the LCD continuously  displays:**

vswrthermaloverdrive

Even though none of the pins are high.
When I use Pins 11, 12, 13 instead of 36, 37, 38 it works fine. I already used pins 11,12,13 for some other purpose. Why is this happening? And how do I solve this problem?

Please edit your question to specify what you have connected to the input pins.

The pin needs to be pulled high or pulled low. Either with a pullup or pulldown resistor or a switch. When a input pin is not connected to something, the digitalRead can return HIGH or LOW, it can be anything. The digital pins 11, 12, 13, 36, 37, 38 are all the same: http://www.pighixxx.com/test/portfolio-items/mega/

I expect the problem is in the circuit. To be sure, put a serial print statement directly after reading the inputs, to be sure the input values are read correctly.
See the remark of using INPUT or INPUT_PULLUP from Jot below.
The following is just a more compact way of writing your loop (and does not fix your problem):
void process(int pin, char* text)
{
    if (digitalRead(pin) == HIGH) // Use HIGH instead of 1
    {
       lcd.write(text);
       digitalWrite(35, HIGH);
       delay(2000);
    }
}

void loop()
{
    lcd.begin(16,2);
    // set cursor position to start of first line on the LCD
    lcd.setCursor(0,0);

    process(36, "vswr");
    process(37, "thermal");
    process(38, "overdrive");
}

Also, I would add the delay at the end (after the three calls of process).
And instead of hard coded values 36, 37 and 38 use 3 constants/defines.

I will add it in the answer .. THAT will be the fix high likely

@Michel Keijzers: thanks for simplifying the program. I'm new to programming. Anyways I want to know why those input are not sensed properly.

@MichelKeijzers, don't write an input LOW. That was used many years ago for the internal pullup resistor, but now the INPUT is specifically a INPUT without a pullup resistor, and INPUT_PULLUP is with internal pullup resistor. Do you have a reference to that wrong use of writing LOW an input? You also can't reduce a pin as OUTPUT in a loop and make it INPUT.

@Jjot ... you are completely right ... I will change it according to your remark.

@Jot  So, using internal PULLUP can solve my problem?

I just found out that by pulling down my inputs i'm not getting the output like i have show in the question. is it possible to pull down internally?

Not that I know off, there is more info at https://www.arduino.cc/en/Tutorial/DigitalPins

@MichelKeijzers : pull down resistor solved my problem.

Another thing, only pin == HIGH writes something to the LCD, the message does not magically go away when pin == LOW
Also, about the logic for pin 35, what should happen when alarm goes away?
Maybe pin 35 should be low again?
Code suggestion:
void process(int pin, char* text)
{
    if (digitalRead(pin) == HIGH) // Use HIGH instead of 1
    {
       lcd.write(text);
       digitalWrite(35, HIGH);
    }
    else
    {
       lcd.write("      ");
    }
}

pin 35 should be low when alarm goes away and I tried your code. I still need to use pull down


text:
Convert String data To char Array in Arduino
I'm able to get json data and storing in String object, now i want to convert string into Char Array for parsing json data
I'm tried with this code, but it is not responding
      String data = http.getString();   //Get the request response payload
      Serial.println(data);                     //Print the response payload
      int len=data.length();
      Serial.println(len);

      char  buf[len + 1];
      data.toCharArray(buf, len + 1);
      int bufLength = sizeof(buf);
      Serial.println(bufLength);   //Printing nothing

Tried c_str()?

No, can you tell me how it converts String JSON data to char Array

Your code does work when I try it: all the Serial.println() do print their stuff. 2) It converts the String to a char array by giving you “direct access to the internal String buffer”. It's written in the doc I linked to.

for me, it is printing like this
Exception (9):
epc1=0x40203d9e epc2=0x00000000 epc3=0x00000000 excvaddr=0x64522072 depc=0x00000000
after len

There is no need for char array. It's possible to access elements inside of String by data[index]. Or you can use ArduinoJson library

One of your problems is you don't know what sizeof does. I think you wanted to use strlen.


text:
Multiple Slaves(Arduino Mega 2560) response over SPI
I have problem creating Setup which have :

A SPI Master (Arduino Mega 2560)
SPI slaves (Arduino Mega 2560) ,which responds to the Masters request by sending float data (or Rather a 2D float array ,but lets just go step by step).

So,I initially started with 3 Arduinos in total (going step by step):

Arduino_1 :Master
Arduino_2 :Slave_1
Arduino_3 :Slave_2

I used ICSP pins for connection and Digital pin 53 (as mentioned in Nick Gammon's page :http://www.gammon.com.au/spi or How do you use SPI on an Arduino?   ,they are  good resources to start with SPI) and 10 for SS.
MY Master codes looks like:
#include <SPI.h>
#define SS_Slave_2 10

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

 pinMode(SS,OUTPUT);
 pinMode(SS_Slave_2,OUTPUT);
 pinMode(MOSI,OUTPUT);
 pinMode(SCK,OUTPUT);

 digitalWrite(SS, HIGH);  // ensure SS stays high for now
 digitalWrite(SS_Slave_2, HIGH);

 digitalWrite(SCK,LOW);
 digitalWrite(MOSI,LOW);

 // Put SCK, MOSI, SS pins into output mode
 // also put SCK, MOSI into LOW state, and SS into HIGH state.
 // Then put SPI hardware into Master mode and turn SPI on
 SPI.begin ();

 // Slow down the master a bit
 SPI.setClockDivider(SPI_CLOCK_DIV8);
}

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (100);
  return a;
}

union first_union
{
 float f;
 byte b[4];
}data;

float yaw, pitch, roll, alt, temp;
float yaw_2, pitch_2, roll_2, alt_2, temp_2;

void loop (void)
{
 digitalWrite(SS_Slave_2, HIGH);
 digitalWrite(SS, LOW);

 //YAW
 transferAndWait ('Y');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 yaw = data.f;

 //PITCH
 transferAndWait ('P');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 pitch = data.f;

 //ROLL
 transferAndWait ('R');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 roll = data.f;

 //TEMP
 transferAndWait ('T');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 temp = data.f;

 //ALT
 transferAndWait ('A');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 alt = data.f;

 digitalWrite(SS, HIGH);
 digitalWrite(53, HIGH);
 digitalWrite(SS_Slave_2, HIGH);
 Serial.println("Slave_01: Start");
 Serial.print("yaw:");
 Serial.println(yaw, 4);
 Serial.print("pitch: ");
 Serial.println(pitch,4);
 Serial.print("roll:");
 Serial.println(roll,4);
 Serial.print("alt: ");
 Serial.println(alt,4);
 Serial.print("temp: ");
 Serial.println(temp,4);
 Serial.println("Slave_01: End");

 digitalWrite(SS, HIGH);
 digitalWrite(53, HIGH);
 digitalWrite(SS_Slave_2, LOW);

 //YAW
 transferAndWait ('Y');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 yaw_2 = data.f;

 //PITCH
 transferAndWait ('P');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 pitch_2 = data.f;

 //ROLL
 transferAndWait ('R');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 roll_2 = data.f;

 //TEMP
 transferAndWait ('T');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 temp_2 = data.f;

 //ALT
 transferAndWait ('A');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 alt_2 = data.f;

 digitalWrite(SS_Slave_2, HIGH);
 digitalWrite(SS, HIGH);
 digitalWrite(53, HIGH);
 Serial.println("Slave_02: Start");
 Serial.print("yaw_2:");
 Serial.println(yaw_2, 4);
 Serial.print("pitch_2: ");
 Serial.println(pitch_2,4);
 Serial.print("roll_2:");
 Serial.println(roll_2,4);
 Serial.print("alt_2: ");
 Serial.println(alt_2,4);
 Serial.print("temp_2: ");
 Serial.println(temp_2,4);
 Serial.println("Slave_02: End");

 delay(500);
}

And Slave Code goes like:
#include <SPI.h>

volatile byte command;
//Set the default object
float ypr[3];
float alt = 0;
float temp = 0;

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

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  pinMode(MOSI,INPUT);
  pinMode(SCK,INPUT);
  pinMode(SS,INPUT);

  // turn on interrupts
  SPCR |= _BV(SPIE);

}

union first_union
{
    float f;
    byte b[4];
 }data;

ISR (SPI_STC_vect)
{
  byte c = SPDR;

  command = c;

  switch (command)
  {
   case 'Z':
   data.f = 0;
   SPDR = 0;
   break;
   case 'Y':
   data.f = ypr[0];
   SPDR = data.b[0];
   break;
   case 'P':
   data.f = ypr[2];
   SPDR = data.b[0];
   break;
   case 'R':
   data.f = ypr[1];
   SPDR = data.b[0];
   break;
   case 'A':
   data.f = alt;
   SPDR = data.b[0];
   break;
   case 'T':
   data.f = temp;
   SPDR = data.b[0];
   break;
   case '1':
   SPDR = data.b[1];
   break;
   case '2':
   SPDR = data.b[2];
   break;
   case '3':
   SPDR = data.b[3];
   break;
  }
}

void loop()
{
  Serial.println("loop() starts");
  ypr[0] = -1.1111;
  ypr[1] = -2.2222;
  ypr[2] = -3.3333;

  alt = -4.4444;
  temp = -5.5555;
  Serial.println("loop() ends");
}

The above codes (Master and Slave) are basically modified and adopted from Joseph Roberts' Question on https://stackoverflow.com/questions/20409799/sending-floats-from-an-arduino-to-another-arduino-over-spi-using-a-union
 , purely for learning purpose only.
(I modified it a bit and now similar codes works well for 1 SPI Master and 1 SPI slave Arduino setup).
//Note:Same Slave code uploaded to both the slaves.
OUTPUT:
Slave_01: Start
yaw:-1.1111
pitch: -3.3333
roll:-2.2222
alt: -4.4444
temp: -5.5555
Slave_01: End
Slave_02: Start
yaw:0.0000
pitch: 0.0000
roll:-2.2222
alt: 0.0000
temp: 0.0000
Slave_02: End
Slave_01: Start
yaw:-1.1111
pitch: -3.3333
roll:-2.2222
alt: -4.4444
temp: -5.5555
Slave_01: End
Slave_02: Start
yaw:0.0000
pitch: 0.0000
roll:0.0000
alt: 0.0000
temp: 0.0000
Slave_02: End
Slave_01: Start
yaw:-1.1111
pitch: -3.3333
roll:-2.2222
alt: -4.4444
temp: -5.5555
Slave_01: End
Slave_02: Start
yaw:0.0000
pitch: 0.0000
roll:0.0000
alt: ovf
temp: 0.0000
Slave_02: End
Slave_01: Start
yaw:-1.1111
pitch: -3.3333
roll:-2.2222
alt: -4.4444
temp: -5.5555
Slave_01: End
Slave_02: Start
yaw:0.0000
pitch: 0.0000
roll:0.0000
alt: 0.0000
temp: ovf
Slave_02: End

As we can see from output ,I got output from one of the slave only (Arduino_2:Slave_1) ,the other gave unreliable/garbage output .That is the problem ,I don't get it where the zeros for 2nd Slave comes from ?And how to correct it.Did I missed something ?
Even the page(http://www.gammon.com.au/spi) by Nick Gammon on SPI ,lacks details on Multiple Slave Arduino SPI connection (Although It is really a good place to start with SPI on Arduino, no offense  ).I know my Question is similar to Slaving multiple Arduinos via SPI ,but still the answer there doesn't helps much. I almost spend entire Night searching for the solution.
I even tried things like changing the SS for the Slaves ,but still only   Arduino_2 gave the correct results and Arduino_3 does not.
And yes ,Arduino_3 is not damaged (It works well in 1master_1slave setup). And all the Arduinos has common GND .
Any constructive criticisms are also welcomed.
Warm Regards
SV

Hi , this is my first  post/question to the forum ,so please bear with me If I lacked some important details(if any) in the Above Question.

why don't you get the setup to reliably transfer a single byte before you try sending an array?

Please can you show your wiring of the two slave setup?

I know this item is quite old, and I'm also trying to implement multiple Arduino SPI slaves, and looking at all documentations, my understanding is that the SS is not automatically managed in the slave Arduinos. From that, unsure about the wiring of your 1 master/2 slaves Arduinos that can alter the results as shown above, it looks to me your slave code does not manage the SS from two aspects :
1 - I don't see when you identify in your ISR reception procedure if the applicable slave is enabled ( aren't both modules processing the message all the time in this configuration, I suspect they both do  )
2 - Also about the SS event management in the slave module, pinMode(MISO, OUTPUT); should only be set when SS is low, otherwise you may have faulty signal with two slaves having MISO as outputs. My understanding is that only one slave at a time should have it as an output ( hence my question about wiring )
Hope it helps,


text:
Arduino uno - Ethernet Shield enc28j60 hangs after some time
I am using Ethernet Shield enc28j60 for retrieve data from web server, but Ethernet Shield enc28j60 hangs after some time and it only works after restarting power supply (router usb port).
My sketch : https://github.com/shyamjos/Arduino_ServerMon

I have fixed it myself by increasing Ethernet::buffersize, I have also heard that sometimes it is caused due to power issues so providing external 3.3V for enc28j60 may help.

Increasing a buffer size doesn't normally fix a hang that occurs after some time, it just delays it.  It might be worth checking your code sending data to see how long this buffer is going to last.

In my case it is working fine for last 48 hours after adjusting buffer size , before it was getting stuck within few minutes.

Are you sure your ethernet connection works? Try to debug with Serial.println(F("message")) to find out where it hangs.
I used the same Ethernet Shield and EtherCard library, and I had to change
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) {

on line 152 to
if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {

because the ENC28j60 uses a different default CS pin (10 instead of 8).

I am already using CS pin as 10 and it is working fine


text:
How to tell Arduino Uno that I pressed or released a key on PC keyboard over serial?
I want to implement a simple musical keyboard with Arduino using tone() and noTone() functions, etc.
The desired behavior is:

While PC and Arduino are connected via USB/Serial...
...when I press a key, a corresponding note starts playing...
...and if I release that key that note stops playing...
...or if I press another key, another note replaces the former one.

So, basically, instead of "while key is pressed" logic, I would like to just write a byte to serial when a key is pressed, write nothing while the key is held pressed, and write another byte when that key is released.
I will be using a Python script in the PC, but examples in other languages, or just using a plain serial monitor, are fine.

PCs' keyboards send key-down and key-up signals to the PC so that much is available already. But that gets translated into letters including generating key-repeats at a fairly low level - BIOS, I think. Getting that deep from a higher level language like Python may be a challenge. A search for "windows keydown" returned a few hits that looked promising.

UPDATE: When I posted this answer I had not yet any knowledge of the Processing Language. If you came to this answer with the same intention I had (the question title), I strongly suggest you to use Processing instead, which has much more straightforward keyboard event capturing and serial communication working out of the box with minimal code.
A question showing this in action is here: https://stackoverflow.com/questions/18366482/processing-to-arduino-with-keyboard

After realizing that what I actually wanted was to "capture keyboard events", I ended up using PyGame due to its minimalistic setup. Now I can send whatever I want to the Arduino using PySerial.
PS.: Don't be fooled by the lame aesthetics of PyGame website, it is a very mature gaming platform.
Full code here: https://github.com/heltonbiker/Experiments/tree/master/SerialMusicKeyboard
#/usr/bin/env python

import pygame
import serial
import glob
import time

def pygameSetup():
    pygame.init()
    screen = pygame.display.set_mode((468, 60))

    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((250, 250, 250))

    if pygame.font:
        font = pygame.font.Font(None, 36)
        text = font.render("Shut up 'n play yer keyboard!", 1, (10, 10, 10))
        textpos = text.get_rect(centerx=background.get_width()/2)
        background.blit(text, textpos)

    screen.blit(background, (0, 0))
    pygame.display.flip()

def main():

    pygameSetup()

    initialized = False

    while not initialized:
        try:
            serialpath = glob.glob('/dev/ttyACM*')[0]
            ser = serial.Serial(serialpath, 9600)
            initialized = True
            print "serial up"
        except:
            time.sleep(500)
            print "waiting for serial"

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN:
                print event
                ser.write(chr(event.key))
            elif event.type == pygame.KEYUP:
                ser.write(chr(0))

if __name__ == '__main__':
    main()

@heltonbiker consider accepting any of the answers as "the answer" as currently, the question seems "unanswered". While you actually have found something usefull. By accepting an answer, no-one with the intention of giving an answer will waste time on this question.

As mentioned by Spiked3 there are a few ways to hit the ground running with C#.
Firstly, as detailed by Majenko, you will need an application running on your PC and some code on the Arduino to interact with this. For the desktop application, the two easiest ways to get started with C# are with WinForms, or XNA/MonoGame. WinForms is targeted at Desktop application development; think legacy desktop apps. Although it is not the current defacto standard (replaced largely by WPF) it is very simple and akin to Swing in Java to use. MonoGame and XNA are targeted at video game development. The latter would be my preference as it lends itself more towards real time applications, and has a game loop much like the Arduino so it is very easy to start using. The caveat is that there is more setup involved, but you will probably find this the friendliest and best supported.
Firstly, The Code! So for the Winforms Route, We have something like this:
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            Debug.WriteLine(" Key Up! ({0})", e.KeyCode);

            // TODO: Talk with Arduino
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            Debug.WriteLine(" Key Press! ({0})", e.KeyChar);

            // TODO: Talk With Arduino
        }
    }
}

To get to this point, fire up a new winforms project, and open up the 'Form1' code (the default window which is added to the project) add the methods as outlined above. You will need to go to the designer afterwards and add events for on KeyPressand on KeyUp to tie these functions to the Window. You can do this by clicking the Window, then opening the Properties Panel, and then clicking the lightening bolt. You will see a list of event names; find the corresponding events (Key Press and Key Up) and associate them with these methods.
From here, you can perform some logic when a button is either pressed or released.
The monogame or XNA approach is a bit simpler to follow as there is no hidden magic; but may be more intimidating if you're not familiar with C# and the project type.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Diagnostics;

namespace GameName1
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;

        KeyboardState currentState;
        KeyboardState previousState;

        public Game1() : base()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            // Get state management started
            currentState = Keyboard.GetState();

            base.Initialize();
        }

        protected override void Update(GameTime gameTime)
        {
            // Listen for exit command
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // Update the state of your keyboard object
            previousState = currentState;
            currentState = Keyboard.GetState();

            // Detect Keypress of key 'F'
            if (currentState.IsKeyDown(Keys.F) && previousState.IsKeyUp(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Pressed! ({0})", 'F');
                //TODO Talk to Arduino
            }

            // Detect Keyrelease of key 'F'
            if (currentState.IsKeyUp(Keys.F) && previousState.IsKeyDown(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Released! ({0})", 'F');
                //TODO Talk to Arduino
            }

            base.Update(gameTime);
        }
    }
}

In either case, you will need to get yourself set up first. Get a compy of Visual Studio Community from the link below, and install MonoGame if desired. Then do some C# tutorials to get comfortable in your new environment.

Visual Studio Community Edition
Mono Game
C# Tutorial
C# Mono Game Tutorial
C# WinForms Tutorial

Lastly, you will want to talk with your Arduino. This can be done by implementing a compatible Serial interface between your desktop application and your Arduino. See the tutorial below to get started!

Arduino C# Serial Tutorial

I hope this information is useful. There is a very broad range of topics mentioned here, and it may seem overwhelming at first - but C# is a very idiosyncratic language in that it permits rapid development in many different scenarios, and I think that you will find it rewarding to conquer the learning curve.

Incidentally, my current job is C#/WPF developer, so creating a GUI app is something I am quite familiar with. The greatest "paradigm change" here was to realize that everything I wanted to do regarding "capturing keyboard events" is already implemented in any GUI toolkit (I ended up using PyGame), while most examples use command-line tools and/or serial monitors on a terminal.

Don't get me wrong - I love WPF, and strongly dislike WinForms in contrast, however I generally find myself strictly following the MVVM design pattern with WPF and consequently I find it difficult to get in that 'single dirty file with a blocking UI thread' mindset. :)

I just took a quick look at SlimDX - it appears that it more or less just wraps DirectX, which isn't a bad thing. I think MonoGame and XNA will still be simpler for most use cases where you would use managed code, as there is a lot of automation that I am sceptical would be included with SlimDX, especially the content pipeline. I get the impression SlimDX is related to SharpDX, and that it's best equivalent to XNA would be MXA. https://mxa.codeplex.com/

You need to come up with a protocol.  Then you need to write the PC software.  The PC software will monitor the keyboard, and when you press a key it will send a certain signal through the serial port. When you release the key it will send a different signal.
How you arrange that is entirely up to you.
You might implement a protocol that sends something like:
b4
c4
d3
off
c3
f3
off
g4
off

Where the first letter is the note, the second letter is the octave to play that note in, and the word "off" is to stop playing.
I don't have a clue (and probably few people here do) how you'd program the PC end in Python.  It most likely depends on what platform you're working on as to what kind of interface you can build.


text:
Unable to upload to Arduino Due using version 1.6.8 of SAM tools; bossac.exe throwing an error
I can successfully see the Arduino Due when I plug it in. I can compile the code, but when I attempt to upload it to the board I get the following error:
C:\Users\user\AppData\Roaming\Arduino15\packages\arduino\tools\bossac\1.6.1-arduino/bossac.exe
        -i -d --port=COM4 -U false -e
        -w true
        -b C:\Users\user\AppData\Local\Temp\build6683778295083335366.tmp/_50key_driver.cpp.bin
        -R bossac.exe: extra arguments found
    Try 'bossac.exe -h' or 'bossac.exe --help' for more information

I finally figured out the problem. This occurred on both a Mac and PC (Windows 10).
This error occurred because of the true after the -w switch. To fix it I modified the package to tell the IDE not to use that switch.

Go to: %USER_PROFILE%\AppData\Roaming\Arduino15\packages\arduino\hardware\sam\1.6.8 (where %USER_PROFILE% is your windows user directory, for me it was C:\Users\user) in Windows Explorer.
Make a copy of the platform.txt file (I called it platform_backup.txt).
Open the file platform.txt with Word Pad (it had Unix line endings in my environment), search for the string:
tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w {upload.verify} -b "{build.path}/{build.project_name}.bin" -R
This was 3rd line from the bottom for me, and remove the text between the quotes "{upload.verify}". It should now look like this:
tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w -b "{build.path}/{build.project_name}.bin" -R
Restart the IDE so it can re-read the file you just edited. You'll now be able to upload to the Due.

On my Windows 10 system, the path to platform.txt contained AppData\Local instead of AppData\Roaming.
Full path: %USER_PROFILE%\AppData\Roaming\Arduino15\packages\arduino\hardware\sam\1.6.8
Uploads fine to my Due now!

Tim's solution is also applicable to Version 1.6.9 of the SAM tools. I just installed it in my Arduino IDE V1.6.8 and had the same parameter problem as originally reported. Following Tim's solution fixed the problem right away. As this is clearly a configuration issue on the Arduino IDE side, it should happen on any supported Windows platform, mine was Windows 7.
The only difference I encountered was the path to the SAM tools directory. On my Enterprise version of Win7, the path was not in AppData\Roaming but in AppData\Local , so
%USER_PROFILE%\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\ for the full pathname.

There's a better option:
(For Windows)
1/ Download the latest IDE release.
2/ Uninstall the IDE completely.
3/ Reboot PC
4/ Go to %USER_PROFILE%\AppData\Local\Arduino15 and delete it (the entire folder). If the path doesn't match then find it in AppData folder, it's in there somewhere.
5/ Reinstall the IDE, problem fixed.

I tried this solution in linux Fedora, it worked fine, but the location of the file "platform.txt" was
/home/{user}/.arduinoxx/packages/arduino/hardware/sam
It is a hidden folder, so make it visible so you can handle it. No sudo access was necessary.

From the question, it is obvious the OP uses Windows, not Linux. Providing a linux-based answer may not really help.


text:
Serial ports grayed out when Arduino plugged in (MS Surface Pro X, Windows 10 Pro 21H2). How do I get Arduino IDE to recognize them?
I am helping a Windows user program an Arduino application. The computer is a Surface Pro X running Windows 10 Pro 21H2. It only has USB-C ports (which cannot be used to power or program Arduinos) so he's using this USB-C hub and a USB-type A to USB-C cable to program it. The Arduino is a Sparkfun Artemis Redboard (Cortex M4).
When he connects the Arduino to the Surface Pro, the Arduino powers up as normal, but no serial ports are visible in the Arduino IDE, and the serial port line remains grayed out.
By contrast, the same USB-C hub, cable, and Arduino can be programmed by a Mac. I run Linux and don't know anything about USB port access on either Mac or Windows, but I got the impression that manually installing drivers should not be necessary on either.
Any advice on how to get the Arduino IDE to recognize this as a serial port when plugged in to a Surface Pro?

A Mac is based on Unix/Linux.  I believe you can open a console on a Mac and type the Linux command lsusb to list the attached USB devices just like you do on a Linux box.  On the Win10 box ... I would consult the Sparkfun web site and discover if there is any special drivers that need to be installed to prompt Win10 to create a serial port.  Also, you may try to connect A USB device that you know will generate a serial port to test if the HUB you are using on the Sur/Pro/10 is actually working as expected.

Do you get the typical USB chime when you insert the device? Because if you don't, if it doesn't list at all in Device Manager, even temporarily, even as an unrecognized USB device, then the drivers are not a problem to worry about (yet anyway).  USB devices have to work well for the operating system in order to get USB device descriptor for it to even know what driver it should be trying to load.

Consider running through this Sparkfun Hookup Guide for the SparkFun RedBoard Artemis.  There is a section dealing with this problem:

My Nano is not showing up as a COM port?!
Most Artemis carrier boards use the CH340C IC which is not affected by
this issue. This issue is only for the Nano that uses the much smaller
CH340E.


text:
Can't upload in Platformio and board is suddenly not detected in STM32CubeProgrammer
I'm using a Nucleo-H755ZI-Q. I used it together with Platformio and Arduino framework. In order to get Arduino to work I'm using this setup:
    [env:nucleo_h743zi]
    platform = ststm32
    board = nucleo_h743zi
    framework = arduino
    monitor_speed = 115200

This works fine using this board but suddenly it stopped working. I am getting this upload error:
Error: init mode failed (unable to connect to the target)

As well as the board is not connected STM32CubeProgrammer.
It is however discovered at port 13 but cannot upload. The COM LED is also red indicating there is a problem with the communication with the computer. I got a brand new USB cable and have tried others so it is not the cable.
I have two possible scenarios what has happened.

Since I have soldered the headers I have burned some component on the board. But maybe not so likely since it first worked and then stopped working.

Something has happened with the communication after using "wrong" but working board for uploading nucleo_h743zi.

Are there any way of factory reset my board Nucleo-H755ZI-Q in order to try to resolve what is wrong or any other recommendation? I have of course tried to reset with the reset button. But still the LED is red.
Thanks.

Not sure that nucleo_h743zi works with an H755...

Check your platformio.ini file. It should be correctly set up for the Nucleo-H755ZI-Q. The board field should match the exact board you are using. For the Nucleo-H755ZI-Q, the configuration should be:
[env:nucleo_h755zi_q]
platform = ststm32
board = nucleo_h755zi_q
framework = arduino
monitor_speed = 115200

I know that. That board has however no arduino support so I hacked it a bit using nucleo_h743zi  instead. That worked to begin with. But maybe that what eventually made it corrupt


text:
Arduino code does not function when relays are powered
I have a mega arduino, which is supposed to to power 4 relays using 4 touch sensors TTP 223, the relays are 5V coil and 220V. the arduino is powered by a 5 V adapter "mobile phone charger" and it powers the relay module, the problem when the relays are not connected to the 220 V the arduino and code work well; the Arduino triggers the relays, when the 220V circuit is connected and the relays are supposed to operate solenoids the relays start to work differently and sometimes shuts off, some times just blink,the relay module has 8 only 4 are used, 1, 2, 3 and 8 all are NO wired. the module is powered from the 5V  port of arduino, (https://i.sstatic.net/o 30IA.jpg) the charger's output is 5V 2A. jd-vcc is jumped with vcc

this is caused by EMI from relays. add relay (module) model and wiring to question

Does the phone charger put out enough current to drive the relays? Looks like each relay pulls more than 1/3 of a watt.

first try to wire the Ground pin next to jd-vcc and Vcc


text:
Global array doesn't get assigned the space it would take up in memory
I have this sketch:
const uint32_t len = 65536;
uint8_t arr[len];

void setup() {}

void loop() {}

The length of the array should fit into the dynamic memory. However, when I compile the sketch it says this in the output window:
Sketch uses 10528 bytes (0%) of program storage space. Maximum is 2031616 bytes.
Global variables use 13504 bytes (1%) of dynamic memory, leaving 1034224 bytes for local variables. Maximum is 1048576 bytes.

If I change len to 10, that doesn't change. The compiler is set to "Debug", so it should not get optimized away. This indicates, that the memory isn't actually being allocated. What seems to be the problem here?
I am compiling for the Teensy 4.0, but the output is the same in essence for the Arduino Uno and other boards (with lower memory sizes).

How are you compiling it? If you're not actually using the array it may just be optimized away.

My guess would be this is due to not putting any data in it.

There is no problem here. Only the compiler is a bit smarter than you anticipated. It sees, that you are not using arr anywhere, so it just optimizes it out.
There are two ways to prevent that, if you really want to:

I think you can use flags to tell the compiler, that this shouldn't be optimized out. I'm no expert in this, others might know more about this and add their own answer
You can just start using it.

That is a good point, however I had already thought of that. See the updated question.

Nevermind, apparently this setting still leads to the compiler optimizing it away. Once there is a line that writes data to the array, the proper memory usage for global variables gets displayed.

The only thing that remains after this is that malloc() doesn't seem to work this way.

@LukasFun Correct--malloc does precisely what it's supposed to, allocate the memory, at the time it's called. Whether or not that memory is used is irrelevant.