Id
stringlengths
1
5
Tags
stringlengths
3
75
Title
stringlengths
15
150
CreationDate
stringlengths
23
23
Body
stringlengths
51
27.6k
Answer
stringlengths
42
31k
92329
|arduino-uno|analogread|attiny|voltage-level|digital-analog-conversion|
Reading constant battery voltage and using the obtained value in sensor formula
2023-02-20T09:07:15.987
<p>there i am working on a project in which my system is connected to 3.7v~4.2V lithium battery, I have to read constant battery voltage irrespective of the current battery voltage and to do that I am using internal voltage reference (1.1V). My issue is that before adding sensor code my program was reading constant voltage irrespective of any battery level but the moment I add sensor code to it, the battery voltage readings fluctuate.</p>
<p>If you set the Vref with the internal reference of 1.1v, then the voltage presented at analog pin A1 is simply as:</p> <pre><code>const float Vref = 1.1; // according to datasheet there is a +/-10% variance, need calibration to confirm the actual value analogReference(INTERNAL); float VA1 = Vref / 1023.0 * analogRead(A1); // voltage at analog pin A1 float Vbat = VA1 * 5.7; // battery voltage </code></pre>
92345
|atmega328|timers|avr|
Timer 1 "Set on Compare Match" in Normal Mode - Not working
2023-02-22T03:42:14.853
<p>I'm using the hardware timers on the 328 for phase angle control of a triac with zero-crossing detection. I am encountering some strange behavior with the &quot;Set on Compare Match&quot; feature not working as expected on Timer1. I am attempting to replicate the red &quot;gate&quot; trace here: <a href="https://playground.arduino.cc/Main/ACPhaseControl/" rel="nofollow noreferrer">https://playground.arduino.cc/Main/ACPhaseControl/</a>, but with my own implementation in code.</p> <p>Before building the triac and zero-cross detection circuit, I am using another timer (Timer0) to simulate a 120Hz AC square wave (2x the 60Hz frequency because the double crossing pulse will arrive twice a cycle).</p> <p>The output of the synthesized AC square wave is fed into an external interrupt pin (INT0) with a jumper. The correct functionality of the program is a short pulse to fire the triac at some phase delay relative to the zero crossing interrupt event (another example: <a href="https://www.homemade-circuits.com/wp-content/uploads/2020/07/half-phase-control.jpg" rel="nofollow noreferrer">https://www.homemade-circuits.com/wp-content/uploads/2020/07/half-phase-control.jpg</a>)</p> <p>I configure Timer 1 in normal mode, and define compare levels for both OCR1A and OCR1B. OCR1A is the &quot;phase delay&quot; from zero crossing at which to fire the triac, and OCR1B sets the duration of the pulse used to fire the triac. In my code, Method 1 is working and producing the intended output, while Method 2 is not working (output is always ON). For brevity, I am highlighting the differences between the two methods below, and the rest of the code is the same.</p> <p>Method 1:</p> <ul> <li>Set OC1A to do nothing on compare (normal port operation) <code>TCCR1A=0;</code></li> <li>&quot;Manually&quot; turn on the pin inside of the interrupt handler for output compare A. It will later be turned off in the interrupt handler for output compare B: <code>PORTB=(1&lt;&lt;PORTB1);</code></li> </ul> <p>This produces the following (correct) output. In the oscilloscope screenshot, the yellow trace is the simulated AC square wave, and the green trace is to be the gate voltage on the triac. <a href="https://i.stack.imgur.com/tpSAw.png" rel="nofollow noreferrer">https://i.stack.imgur.com/tpSAw.png</a></p> <p>Method 2:</p> <ul> <li>Enable the OC1A &quot;Set at compare match&quot; bit in the TCCR1A register: <code>TCCR1A |= (1 &lt;&lt; COM1A1) | (1 &lt;&lt; COM1A0);</code></li> <li>In theory, this means that I don't have to manually turn on the pin inside the interrupt handler for compare A, because it's already been turned on for us by the Compare Match Output Unit.</li> </ul> <p><a href="https://i.stack.imgur.com/45tFA.png" rel="nofollow noreferrer">https://i.stack.imgur.com/45tFA.png</a></p> <p>Note that in both methods, I still need to &quot;manually&quot; turn off the pin inside the output compare B interrupt handler because OC1A and OC1B are not the same physical pin: <code>PORTB=0;</code></p> <p>In Method 2, the pin is held ON, with no indication that the interrupt handler for output compare B is doing anything. My mental model of the port is that <em>as long as the bit in the data direction register is set for that port, both the output compare unit and CPU can write to the pin</em>. It appears that the pin is always being held ON, even after it is turned OFF by the CPU. Does the compare unit lock/latch the pin until the next clock cycle, or am I missing something else? Some tips here would be much appreciated.</p> <p>I can prove that the output is indeed connected to OC1A because OC1A is PB1 which is connected to the oscilloscope and is being toggled in Method 1. I have vertically scaled OC1A (green) for readability against OC0A.</p> <p>I have been referencing Section 13 of <a href="https://www.sparkfun.com/datasheets/Components/SMD/ATMega328.pdf" rel="nofollow noreferrer">https://www.sparkfun.com/datasheets/Components/SMD/ATMega328.pdf</a> for most of this task.</p> <p>My code below for Method 1 is presented. To get Method 2, toggle the comments on the indicated lines.</p> <pre><code> #define F_CPU 16000000L #include &lt;avr/io.h&gt; #include &lt;avr/interrupt.h&gt; /* For reference: OCR1A = turn_on_timer_level OCR1B = turn_on_timer_level + pulse_width */ int timer0_ac_sim_val = 64; // Measured in clock ticks with prescale=1024 int turn_on_timer_level = 500; // Measured in clock ticks with prescale=64 int pulse_width = 200; // Measured in clock ticks with prescale=64 ISR(INT0_vect){ // ISR at output compare A of timer 0 turns on timer 1 - simulates what happens when a zero crossing rising edge is detected on a 120Hz AC sine wave TCCR1B |= (1&lt;&lt;CS11) | (1&lt;&lt;CS10); TCNT1 = 0; } ISR(TIMER1_COMPA_vect){ // ISR at output compare A of timer 1 turns on the pin PORTB = (1&lt;&lt;PORTB1); // Turn on the pin COMMENT FOR METHOD 2 } ISR(TIMER1_COMPB_vect){ TCCR1B = 0; // Turn off the timer PORTB = 0; // Turn off the pin } int main(){ // Timer 0 setup for a 120Hz square wave on OC0A DDRD |= (1&lt;&lt;PD6); TCCR0A = 0x0; TCCR0A |= (1&lt;&lt;COM0A0) | (1&lt;&lt;WGM01); // Set the output to toggle on compare TCCR0B = 0x0; TCCR0B |= (1&lt;&lt;CS02) | (1&lt;&lt;CS00); // Configure with a prescale of 1024 and start clock OCR0A = timer0_ac_sim_val; // Calculate this value for a 120Hz square wave, doesn't change. // Enable external interrupt 0 to trigger on a rising edge - set the External Interrupt Control Register EICRA |= (1&lt;&lt;ISC01) | (1&lt;&lt;ISC00); EIMSK |= (1&lt;&lt;INT0); // Global interrupt enable sei(); // Timer 1 setup DDRB |= (1&lt;&lt;PORTB1); TCCR1A = 0x0; // No pin action on output compare // TCCR1A |= (1 &lt;&lt; COM1A1) | (1 &lt;&lt; COM1A0); // Set OC1A on compare match UNCOMMENT FOR METHOD 2 TCCR1B = 0x0; // Disable clock OCR1A = turn_on_timer_level; // Delay between OC0A rise and OCR1A trigger OCR1B = turn_on_timer_level + pulse_width; // Delay between OC0A rise and OCR1B trigger // Enable timer 1 interrupts TIMSK1 |= (1&lt;&lt;OCIE1A) | (1&lt;&lt;OCIE1B); while(1){ }; } </code></pre>
<p>For those who might be interested, after fixing the problem I decided to implement the same functionality using Fast PWM mode instead of CTC mode. In trying to debug my original issue, I came across a similar post, to which one of the answers was:</p> <p><a href="https://arduino.stackexchange.com/a/30529/89096">https://arduino.stackexchange.com/a/30529/89096</a></p> <blockquote> <p>The PWM modes manage pin at both ends of the cycle.</p> <p>The point of the CTC modes is that they manage the pin only at one end of the &gt;count, but allow you to manage the other end explicitly.</p> <p>To manage both ends explicitly, you use normal mode.</p> </blockquote> <p>I didn't fully realize what that meant until now, but it clicked. In PWM mode, the hardware timer takes care of the pin toggling for us, on both sides of the waveform. We would use Normal or CTC modes if we wanted to do manage one or both sides of the waveform differently. But my application fits perfectly in the Fast PWM category, so I decided to implement that as well. This saves an ISR by not making the CPU &quot;manually&quot; toggle the pin on and off each time. The only difference is that the output is on OC1B (PORTB2) now instead of OC1A (PORTB1).</p> <pre><code>#define F_CPU 16000000L #include &lt;avr/io.h&gt; #include &lt;avr/interrupt.h&gt; int timer0_ac_sim_val = 64; // Measured in clock ticks with prescale=1024 int turn_on_timer_level = 400; // Measured in clock ticks with prescale=64 int pulse_width = 100; // Measured in clock ticks with prescale=64 ISR(INT0_vect){ // ISR at output compare A of timer 0 turns on timer 1 - simulates what happens when a pulse is received from the zero crossing detector TCCR1B |= (1&lt;&lt;CS11) | (1&lt;&lt;CS10) | (1&lt;&lt;WGM13) | (1&lt;&lt;WGM12); TCNT1 = 0; } ISR(TIMER1_COMPA_vect){ // ISR at output compare A of timer 1 turns on the pin TCCR1B = 0; // Turn off the timer } int main(){ // Timer 0 setup for a 120Hz square wave on OC0A DDRD |= (1&lt;&lt;PD6); TCCR0A = 0x0; TCCR0A |= (1&lt;&lt;COM0A0) | (1&lt;&lt;WGM01); // Toggle mode - non-PWM TCCR0B = 0x0; TCCR0B |= (1&lt;&lt;CS02) | (1&lt;&lt;CS00); // Configure with a prescale of 1024, start clock OCR0A = timer0_ac_sim_val; // Enable external interrupt 0 to trigger on a rising edge - set the External Interrupt Control Register EICRA |= (1&lt;&lt;ISC01) | (1&lt;&lt;ISC00); EIMSK |= (1&lt;&lt;INT0); // Enable interrupts sei(); // Timer 1 setup - 16 bit resolution with a prescale of 8 gives a max period of 1/(16e6/8/65536) = 32.78ms DDRB |= (1&lt;&lt;PORTB2); // Set WGM12 (CTC) to 1 and start the timer with a prescaler of 1024 -&gt; This starts the timer in CTC mode TCCR1A = (1&lt;&lt;COM1B1) | (1&lt;&lt;COM1B0) | (1&lt;&lt;WGM11) | (1&lt;&lt;WGM10); // Set COM1B1 and COM1B0 to 1 for inverting mode. For fast PWM set WGM11 and WGM10 TCCR1B = 0x0; // Start with clock disabled OCR1A = turn_on_timer_level + pulse_width; OCR1B = turn_on_timer_level; // Enable timer 1 interrupts TIMSK1 |= (1&lt;&lt;OCIE1A); while(1){ } </code></pre>
92349
|library|rf|attiny85|
1MHZ Attiny85 RF with MANCHESTER library
2023-02-22T11:13:22.107
<p>I'm trying to set up a transmitter made by the following components :</p> <ul> <li><strong>Attiny85 (I need 1MHZ speed)</strong></li> <li><strong>Cheap 433mhz transmitter (FS1000A)</strong></li> </ul> <p>The library I am using is the Manchester library <a href="https://github.com/mchr3k/arduino-libs-manchester" rel="nofollow noreferrer">GitHub</a>. The attiny85 and the transmitter are powered with <strong>regulated 5V</strong>. I set up <strong>1MHZ when burning the bootloader</strong> for the tiny.</p> <p>I am <strong>successful at transmitting with 8 AND 16MHZ with my Attiny85</strong>, however, 1MHZ seems to malfunction. For 1MHZ on the tiny, this line need to be added in order to adjust timings :</p> <pre><code>man.workAround1MhzTinyCore(); </code></pre> <p>Here is the complete code :</p> <pre><code>#include &lt;Manchester.h&gt; /* Manchester Transmitter example In this example transmitter will send one 16 bit number per transmission. Try different speeds using these constants, your maximum possible speed will depend on various factors like transmitter type, distance, microcontroller speed, ... MAN_300 0 MAN_600 1 MAN_1200 2 MAN_2400 3 MAN_4800 4 MAN_9600 5 MAN_19200 6 MAN_38400 7 */ #define TX 2 //pin where your transmitter is connected uint8_t transmit_data = 11; void setup() { man.workAround1MhzTinyCore(); //pinMode(RX, OUTPUT); man.setupTransmit(TX, MAN_300); pinMode(1, OUTPUT); } void loop() { digitalWrite(1, HIGH); man.transmit(transmit_data); delay(100); digitalWrite(1, LOW); delay(200); } </code></pre> <p><strong>Someone else has/had this issue</strong> <a href="https://github.com/mchr3k/arduino-libs-manchester/issues/53" rel="nofollow noreferrer">Can't transmit on @1MHZ attiny85</a>, and i don't know if it has been fixed or not. I am unsure if the library is still updated, and if this issue isn't with the library itself.</p> <p>Does anyone have any leads or fix for that issue ? That would greatly help, Thanks</p>
<p>Ok funny story, I think I found a solution, not sure why, but : My setup (the same) :</p> <ul> <li>Attiny85 (1MHZ (set on bootloader))</li> <li>Cheap 433mhz transmitter (FS1000A)</li> <li>Attiny microcontrollers library</li> </ul> <p>When burning the bootloader with 1MHZ, and uploading sketch, it would seem that <strong>removing the line <code>man.workAround1MhzTinyCore();</code> makes it work.</strong></p> <p><strong>Without the line it's working, and with the work around it is NOT</strong></p> <p>Voila !</p>
92354
|arduino-nano|rotary-encoder|
Change Interrupts on the ATTiny 88
2023-02-22T23:56:59.230
<p>I am working on a project that requires a number of I/O pins for various purposes. I chose the ATTiny88 because it has plenty of GPIO pins, and is relatively inexpensive.</p> <p>Here is the updated code per timemage, with many thanks!</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;TM1637Display.h&gt; #include &quot;PinChangeInterrupt.h&quot; int counter = 0; bool Update = false; int currentStatePhase_B; int lastStatePhase_B; // Shutdown Output #define SW 11 // Rotary Encoder Inputs #define Phase_A 13 #define Phase_B 12 #define DIO 3 #define CLK 4 TM1637Display display(CLK, DIO); void setup() { // Set encoder pins as inputs pinMode(Phase_A,INPUT); pinMode(Phase_B,INPUT); pinMode(SW, OUTPUT); // Read the initial state of Phase_B lastStatePhase_B = digitalRead(Phase_B); // Call updateEncoder() when any high/low changed seen // on interrupt 0 (pin 2), or interrupt 1 (pin 3) attachPCINT(digitalPinToPCINT(Phase_A), updateEncoder, CHANGE); attachPCINT(digitalPinToPCINT(Phase_B), updateEncoder, CHANGE); display.setBrightness(0x0f); display.clear(); } void loop() { delay(100); if (Update){ // Show decimal numbers with/without leading zeros display.showNumberDec(counter, false); // Expect: ___0 Update = false; } } void updateEncoder(){ delay (4); // Read the current state of Phase_B currentStatePhase_B = digitalRead(Phase_B); // If last and current state of Phase_B are different, then pulse occurred // React to only 1 state change to avoid double count if (currentStatePhase_B != lastStatePhase_B &amp;&amp; currentStatePhase_B == 1){ // If the Phase_A state is different than the Phase_B state then // the encoder is rotating CCW so decrement if (digitalRead(Phase_A) != currentStatePhase_B) { counter --; } else { // Encoder is rotating CW so increment counter ++; } if (counter &gt; 1023){ counter = 1023; } if (counter &lt; 0){ counter = 0; } delay(15); } // Remember last CLK state lastStatePhase_B = currentStatePhase_B; Update = true; } </code></pre> <p>It is now capturing most, but not by any means all, interrupts, but the direction is highly unreliable. More often than not, it counts up regardless of which way the encoder is turned,and often counts down when the encoder is turned clockwise.</p> <p>Here is what seems to be a good reference: <a href="https://components101.com/microcontrollers/attiny88-pinout-specs-datasheet" rel="nofollow noreferrer">ATtiny88 8-bit Microcontroller</a></p>
<h3>Interrupt types</h3> <blockquote> <p>One source says there are only two interrupt pins, ...</p> </blockquote> <p>There are two &quot;<em>external</em> interrupt&quot; pins; that is the term you'll find in the chip's datasheet. This is the term that refers to the kind of pins that <code>attachInterupt</code> uses. These are the ones in the pinout labeled INT0,INT1,INTn. The &quot;external&quot; term may be confusing for a couple of reasons. Lots of external things cause interrupts, but this name is applied to when you're not talking about events tied to particular peripherals, like USART (serial peripheral) receiving a character. The special function of &quot;external interrupt&quot; is <em>dedicated</em> to dispatching interrupts based on signals on these INT0/INT1/INT# pins. There's one interrupt vector for each of these signals (two in your case). As you've probably seen in the documentation they can be configured to trigger on rising or falling edges, both edges, and low levels. So, they're right about that to the extent that they're talking about the &quot;external interrupt&quot; pins.</p> <p>The &quot;external&quot; name is also confusing because of what else you've found:</p> <blockquote> <p>Another source says there are quite a few Change Interrupt pins</p> </blockquote> <p>This is also true. These are the &quot;PCINT#&quot; signal names listed in the chip pinout. These &quot;<em>pin change</em> interrupts&quot; are newer; not new, but new<em>er</em>. There exist(ed) AVR that had/have &quot;external interrupts&quot; but no &quot;pin change interrupts&quot;. I'd like to think that if they were created at the same time they wouldn't have simply called the former ones &quot;external&quot;, because these are no less external although they're less dedicated. There's only a single ISR/interrupt for each group of 8 PCINT pins. And unlike the others they only naturally detect that a pin has changed and nothing about the nature of that change (rising vs falling). But a lot of AVR support them and those that do have a significant number of them. In the case of your ATTiny88, all of the GPIO (Arduino &quot;digital&quot;) pins are capable of dispatching a pin change interrupt. However, the Arduino AVR core doesn't provide a function for using them.</p> <h3>Modifying NicoHood's PinChangeInterrupt library</h3> <p>One of the people that used to be in my circle was NicoHood, who created <a href="https://github.com/NicoHood/PinChangeInterrupt/" rel="nofollow noreferrer">this PinChangeInterrupt library</a>. I have a foggy memory of helping with bits of it.</p> <p>What he did was model it after the normal <code>attachInterrupt</code> function. So, you can use it almost as though you have the <code>RISING</code>/<code>FALLING</code>/<code>CHANGE</code> &quot;external interrupt&quot; capability on all of your PCINT# pins; in your case all of your pins. Underneath it is tracking the state of each port pin to determine what has changed and in what direction. In other words, using an interrupt that fires given a change on any of 8 pins together with variables to synthesize per-pin callbacks for not just change but also specifically rising and falling if you want. This is not perfect it is possible to lose short lived events and it takes longer to dispatch your handler function. But it's probably fine for what you're doing.</p> <p>It does not support your chip out of the box. However you can modify to support the ATTiny88; partially if you're not picky. You should find it in the library manager as &quot;PinChangeInterrupt&quot; by NicoHood, currently at version 1.2.9. If you install that it should show up under your sketchbook/libraries directory. You will need to edit the file at path:</p> <p>&lt;sketchbook-directory&gt;<code>/libraries/PinChangeInterrupt/src/PinChangeInterruptBoards.h</code></p> <p>That's your local copy of <a href="https://github.com/NicoHood/PinChangeInterrupt/blob/1.2.9/src/PinChangeInterruptBoards.h" rel="nofollow noreferrer">this file</a>.</p> <p>Your ATTiny88's handling of PCINT is going to be nearly the same as the ATMega328P that's in the UNO. Or rather nearly a superset of it. The chips are closely related in a way. However, you have extra PCINT capable pins on the ATTiny88 that aren't available on the ATMega328P. So you can crudely hack in a line into <a href="https://github.com/NicoHood/PinChangeInterrupt/blob/1.2.9/src/PinChangeInterruptBoards.h" rel="nofollow noreferrer">this section</a> to read:</p> <pre class="lang-cpp prettyprint-override"><code>#if defined(__AVR_ATmega328__) || defined(__AVR_ATmega328A__) || defined(__AVR_ATmega328PA__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328PB__) \ || defined(__AVR_ATmega168__) || defined(__AVR_ATmega168A__) || defined(__AVR_ATmega168PA__) || defined(__AVR_ATmega168P__) || defined(__AVR_ATmega168PB__) \ || defined(__AVR_ATmega88__) || defined(__AVR_ATmega88A__) || defined(__AVR_ATmega88PA__) || defined(__AVR_ATmega88P__) || defined(__AVR_ATmega88PB__) \ || defined(__AVR_ATtiny88__) \ || defined(__AVR_ATmega48__) || defined(__AVR_ATmega48A__) || defined(__AVR_ATmega48PA__) || defined(__AVR_ATmega48P__) || defined(__AVR_ATmega48PB__) </code></pre> <p>The addition of that second to last line above should make the library treat the ATTiny88 you have as though it were an ATMega328P. This compiles under ATTinyCore. I am not set up to test it on a real ATTiny88. But, I expect it will work if you try some examples.</p> <p>Having done that, the library should be work on any of the pins that carry a PCINT0 through PCINT23 label. If you want it to work with PCINT24-PCINT27, that can be done, but requires more work. But given what you've said you probably don't need one of those four and they're not available on the DIP package which I'm guessing you have anyway.</p> <h3>Updating your code</h3> <p>You would to <code>#include &quot;PinChangeInterrupt.h&quot;</code> at the top of your code, and then your current code:</p> <pre class="lang-cpp prettyprint-override"><code> attachInterrupt(digitalPinToInterrupt(Phase_A), updateEncoder, CHANGE); attachInterrupt(digitalPinToInterrupt(Phase_B), updateEncoder, CHANGE); </code></pre> <p>then becomes:</p> <pre class="lang-cpp prettyprint-override"><code> attachPCINT(digitalPinToPCINT(Phase_A), updateEncoder, CHANGE); attachPCINT(digitalPinToPCINT(Phase_B), updateEncoder, CHANGE); </code></pre> <p>With luck, that should do it provided <code>Phase_A</code> and <code>Phase_B</code> under your core (e.g. ATTinyCore) map to GPIO/Arduino &quot;digital&quot; pins that carry a PCINT# signal where the number less than 24.</p> <p>As I said, I have no way of testing it on real hardware right now. But I expect it will work. If not, it is the sort of direction you need to go in.</p> <h3>Doing PCINT yourself</h3> <p>You can also take a more direct approach with reading the datasheet and sorting out how to do what the library does for you, only manually. <a href="https://github.com/NicoHood/PinChangeInterrupt/blob/1.2.9/examples/PinChangeInterrupt_HowItWorks/PinChangeInterrupt_HowItWorks.ino" rel="nofollow noreferrer">One of the examples</a> NicoHood provided with the library is not really an example of using the library but rather an explanation as to what the library does in the form of code. Notice it doesn't actually include the library; it would operate stand alone. So if you want to understand the guts yourself by following the ATtiny88 datasheet, that's a place to start.</p> <p>One reason you might want to do it yourself anyway is if your encoders are being operated quickly, to the point where you can't afford some of the extra effective dispatch time imposed by what the PinChangeInterrupt library is doing in sorting out which pin changed and how. If you handle PCINT yourself, you can make a point of putting your two encoder pins in completely different groups of 8 such that there is only one source of pin change interrupt for each ISR and so there is no need to check which pin caused the interrupt and to route that to another function.</p>
92372
|arduino-uno|arduino-nano|c|bootloader|atmega|
How does the compiler/assembler work wrt bootloader?
2023-02-24T05:41:03.703
<p>I realized that on the atmega boards the bootloader is programmed into the chip.</p> <p>I'm curious, when compiling a sketch how does the compiler/assembler differ from compiling a standard C program for a chip without a bootloader?</p> <p>Is there still a main? Does the linker put the startup code in a different area? Obviously with the bootloader you're no longer compiling a program which places code at the reset address.</p>
<p>On the Uno and similar AVR-based boards, the compiler and assembler are not aware of the bootloader. The compiled program starts at address zero. There you have the interrupt vector table, starting with the reset vector. That vector is a jump to the C runtime startup code, which does some low-level initialization, then calls <code>main()</code> from the Arduino core library, which calls <code>setup()</code> and <code>loop()</code> from your sketch.</p> <p>The bootloader lives at the end of the flash. The AVR chip has a few bytes of non-volatile configuration memory called “fuses”. These bytes are configured by the Arduino board maker to dedicate the last 512 bytes of flash to the bootloader, and to start executing the code at the start of the bootloader on power up and on reset events. It is then the bootloader's responsibility to jump to address zero in order to start the user's program.</p>
92377
|power|esp32|bootloader|
Wemos C3 Mini (ESP32-C3) does not run firmware unless connected to pc
2023-02-24T17:42:46.610
<p>I've been using ESP32s and ESP8266 for a few years now and I thought I'd give <a href="https://www.wemos.cc/en/latest/c3/c3_mini.html" rel="nofollow noreferrer">these little boards</a> a shot, they were cheaper for Bluetooth/WiFi combo, and I don't need all the bells and whistles of a full ESP32.</p> <p>I have my firmware all debugged and working, it's been stable for a few months now. All it does is read a temperature from an Inkbird Bluetooth temperature sensor and log that info into a spreadsheet online for me via WiFi.</p> <p>Up until this point I had the board connected via usb cable to my PC. Well I got a new PC and wanted to save a usb port so I moved it to a usb cable with an Apple AC wall adapter (5V 500mA). The board now never powers on.</p> <p>Does anyone know what's happening here? It seems to not like booting unless it has a serial connection with the PC??? It doesn't like to power on if the PC is off either even though the usb port has power still.</p> <p>I thought maybe this weird usb C port doesn't like 5V. So, I got it 3.3V via a breadboard power adapter rig. Nothing...</p>
<p>Your program could be busy, waiting for the com port to open.</p>
92378
|class|
Cannot instantiate a parameterized object inside of another class
2023-02-24T18:01:54.050
<p>I'm having troubles understanding the inner workings of classes and such.</p> <p>I have a class called <code>Attributes</code> that contains parameters. In my .ino, I can simply instantiate an object with <code>Attributes greenBark(1, 2);</code> and everything is hunkey dorey.</p> <p><em><strong>Problem:</strong></em> Now I need to create a Attributes object in my other class, called Tree. I figured out if my constructor doesn't have parameters, I can create an object within another class just fine. However, my attributes class constructor has parameters. When I try to create an parameterized object within another class, the compiler tosses an error. <strong>How can I create an attributes object within my tree class?</strong> I'm sorry if I got some of these terms mixed up, I'm trying to keep up!</p> <p>Here are my current files (made for this example:)</p> <p><strong>The .ino file</strong></p> <pre><code>#include &quot;attributes.h&quot; #include &quot;tree.h&quot; Attributes greenBark(1, 2); void setup() { Serial.begin(9600); } void loop() { greenBark.printAttributes(); } </code></pre> <p><strong>attributes.cpp</strong></p> <p>#include &quot;attributes.h&quot;</p> <pre><code>Attributes::Attributes(int size, int texture) { _size = size; _texture = texture; } void Attributes::printAttributes() { Serial.print(&quot;GreenBark Attributes: &quot;); Serial.print(&quot;Size = &quot;); Serial.print(_size); Serial.print(&quot; Texure = &quot;); Serial.print(_texture); Serial.println(); } </code></pre> <p><strong>attributes.h</strong></p> <pre><code>#pragma once #include &lt;Arduino.h&gt; class Attributes { public: Attributes(int size, int texture); // constructor void printAttributes(); // method private: int _size = 0; int _texture = 0; }; </code></pre> <p><strong>tree.cpp</strong></p> <pre><code>#include &quot;attributes.h&quot; #include &quot;tree.h&quot; Tree::Tree() { } </code></pre> <p><strong>tree.h</strong></p> <pre><code>#pragma once #include &lt;Arduino.h&gt; #include &quot;attributes.h&quot; class Tree { public: Tree(); // constructor void makeTree(); // method // I want to create an attributes class object in my current class, so naturally I'd try to // create the object just like I did in my .ino sketch, but the below line doesn't work. //Attributes redBark(1, 2); private: }; </code></pre> <p>The error provided is this:</p> <pre><code>In file included from C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\ParameterizedConstructor.ino:2:0: C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected identifier before numeric constant Attributes redBark(1, 2); ^ C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected ',' or '...' before numeric constant In file included from C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.cpp:2:0: C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected identifier before numeric constant Attributes redBark(1, 2); ^ C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected ',' or '...' before numeric constant exit status 1 Compilation error: expected identifier before numeric constant </code></pre>
<p>I see two options here:</p> <p>You might follow jsotola's comment and initialize <code>redBark</code> with braces:</p> <pre class="lang-cpp prettyprint-override"><code>Attributes redBark{1, 2}; </code></pre> <p>For some reason, the syntax with parentheses is not allowed when initializing an object in a class declaration, but the syntax with braces is OK.</p> <p>The other option is to initialize redBark in the <code>Tree</code>'s constructor (and not in the class declaration) using an initializer list:</p> <pre class="lang-cpp prettyprint-override"><code>// In the class declaration: Attributes redBark; // The constructor: Tree::Tree() : redBark(1, 2) {} </code></pre>
92396
|arduino-uno|interrupt|atmega328|attiny|rotary-encoder|
ATTiny88 missing pulses - maybe
2023-02-26T21:36:01.877
<p>I have been given to understand the ATTiny88 is very similar to the Arduino Uno / ATMega328 MCU. There does not seem to be a tag for the ATTiny88, so that is why I chose the tags I did. I do not have a high enough reputation to create a tag, yet. Thanks to the generous help of timemage, Edgar Bonet, and others, my MCU board is now responding, albeit very erratically, to pulses on pins 12 and 13, designated Phase_B and Phase_A, respectively, in the code below. I have not yet entirely ruled out a hardware issue (I will do so), but a software issue is still likely. I don't quite know what. The MCU is registering pulses, but it very often misses large numbers of turns in either direction. What's more, it frequently reports the wrong direction, strongly favoring a CW rotation, but sometimes reporting a CCW rotation when the knob is turned CW. It is definitely not an overflow issue, as the anomalous effects are seen in abundance when in the mid range of the variables.</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;TM1637Display.h&gt; #include &quot;PinChangeInterrupt.h&quot; volatile uint8_t counter = 0; volatile bool Update = false; volatile int currentStatePhase_B; volatile int lastStatePhase_B; volatile int pulses = 0; // Shutdown Output #define SW 11 // Rotary Encoder Inputs #define Phase_A 13 #define Phase_B 12 // TM1637 I/O ports #define DIO 3 #define CLK 4 TM1637Display display(CLK, DIO); void setup() { // Set encoder pins as inputs pinMode(Phase_A,INPUT); pinMode(Phase_B,INPUT); pinMode(SW, OUTPUT); // Read the initial state of Phase_B lastStatePhase_B = digitalRead(Phase_B); // Call updateEncoder() when any high/low changed seen // on interrupt 0 (pin 2), or interrupt 1 (pin 3) attachPCINT(digitalPinToPCINT(Phase_A), updateEncoder, RISING); attachPCINT(digitalPinToPCINT(Phase_B), updateEncoder, RISING); display.setBrightness(0x0f); display.clear(); display.showNumberDec(0, false); } void loop() { if (Update){ // Show decimal numbers with/without leading zeros display.showNumberDec(pulses, false); delay(1000); display.showNumberDec(counter, false); Update = false; } } void updateEncoder(){ // Read the current state of Phase_B currentStatePhase_B = digitalRead(Phase_B); // If last and current state of Phase_B are different, then pulse occurred // React to only 1 state change to avoid double count if (currentStatePhase_B != lastStatePhase_B &amp;&amp; currentStatePhase_B == 1){ // If the Phase_A state is different than the Phase_B state then // the encoder is rotating CCW so decrement if (digitalRead(Phase_A) != currentStatePhase_B) { counter --; } else { // Encoder is rotating CW so increment counter ++; } } if (counter &gt; 1023){ counter = 1023; } if (counter &lt; 0){ counter = 0; } pulses ++; // Remember last Phase_B state lastStatePhase_B = currentStatePhase_B; Update = true; } </code></pre>
<p>OK, I have an answer. The MCU is still missing a lot of pulses, but I am fairly certain this is a hardware issue, or at least mostly so. I found some code by Ralph S. Bacon and Marko Pinteric. The YouTube video can be found <a href="https://www.youtube.com/watch?v=sQNPAsZKnDw" rel="nofollow noreferrer">here</a></p> <p>As should always be the case, the ISR is brief. Here it is a single line that merely sets a Boolean variable true. In the loop section, the code repeatedly checks to see if the interrupt has occurred. The checkRotaryEncoder function then verifies the pin values to make sure the encoder is in a valid state (not bouncing). If so, then the counter value is updated with the result.</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;TM1637Display.h&gt; #include &quot;PinChangeInterrupt.h&quot; uint8_t lrmem = 3; int lrsum = 0; int num = 0; unsigned int counter = 0; // Shutdown Output #define SW 11 // Rotary Encoder Inputs #define Phase_A 12 #define Phase_B 13 // TM1637 Display I/O #define DIO 3 #define CLK 4 TM1637Display display(CLK, DIO); // A turn counter for the rotary encoder (negative = anti-clockwise) int rotationCounter = 200; // Flag from interrupt routine (moved=true) volatile bool rotaryEncoder = false; // Rotary encoder has moved (interrupt tells us) but what happened? // See https://www.pinteric.com/rotary.html int8_t checkRotaryEncoder() { // Reset the flag that brought us here (from ISR) rotaryEncoder = false; static uint8_t lrmem = 3; static int lrsum = 0; static int8_t TRANS[] = {0, -1, 1, 14, 1, 0, 14, -1, -1, 14, 0, 1, 14, 1, -1, 0}; // Read BOTH pin states to deterimine validity of rotation (ie not just switch bounce) int8_t l = digitalRead(Phase_A); int8_t r = digitalRead(Phase_B); // Move previous value 2 bits to the left and add in our new values lrmem = ((lrmem &amp; 0x03) &lt;&lt; 2) + 2 * l + r; // Convert the bit pattern to a movement indicator (14 = impossible, ie switch bounce) lrsum += TRANS[lrmem]; /* encoder not in the neutral (detent) state */ if (lrsum % 4 != 0) { return 0; } /* encoder in the neutral state - clockwise rotation*/ if (lrsum == 4) { lrsum = 0; return 1; } /* encoder in the neutral state - anti-clockwise rotation*/ if (lrsum == -4) { lrsum = 0; return -1; } // An impossible rotation has been detected - ignore the movement lrsum = 0; return 0; } void setup() { // Set encoder pins as inputs pinMode(Phase_A,INPUT); pinMode(Phase_B,INPUT); // Set Power Switch as output pinMode(SW, OUTPUT); // Initialize display display.setBrightness(0x0f); display.clear(); display.showNumberDec(0, false); // Set up interrupt pins and vector attachPCINT(digitalPinToPCINT(Phase_A), rotary, CHANGE); attachPCINT(digitalPinToPCINT(Phase_B), rotary, CHANGE); } void loop() { // Has rotary encoder moved? if (rotaryEncoder) { // Get the movement (if valid) int8_t rotationValue = checkRotaryEncoder(); // If valid movement, do something if (rotationValue != 0) { counter += rotationValue; if (counter &gt; 1023){ counter = 1023; } else if (counter &lt; 0){ counter = 0; } display.showNumberDec(counter, false); } } } // Interrupt routine just sets a flag when rotation is detected void rotary() { rotaryEncoder = true; } </code></pre> <p>Any comments are welcom. In addition, Ralph Bacon used the IRAM_ATTR directive to create the rotary() ISR. My understanding of this directive is it is not necessary in most cases. On the other hand, presumably the code will execute faster if it is pushed into flash RAM. I could not make this work. The compiler complains, &quot;expected initializer before 'rotary'&quot; Is this by chance because the ATTiny88 does not have flash RAM? If not, then what?</p>
92406
|adafruit|python|
CircuitPython - how to connect Adafruit esp32 AirLift with Adafuit HttpServer - incompatible socket object
2023-02-27T10:15:24.913
<p>I am building a CircuitPython weather station based on Adafruit M4 board stacked with Adafruit ESP32 AirLift module. Both work fine together when it comes to making http calls (via Adafruit_requests library). However I would like to build a HTTP server serving weather measures instead. And here is a problem: all Adafuit examples are based on ESP32 or Raspberry Pico boards natively fitted with WIFI. Adafuit M4 board doesn't have the same core python packages since it doesn't sport WIFI. So example written for Pico doesn't work on M4 with ESP AirLift, there are a number of packages missing to do so (like wifi and socket), adafuit_esp package has to be used instead. This package however seems to be incompatible with Adafuit HTTPServer: <a href="https://docs.circuitpython.org/projects/httpserver/en/stable/index.html" rel="nofollow noreferrer">https://docs.circuitpython.org/projects/httpserver/en/stable/index.html</a> HttpServer requires socket object as a parameter to be initialized:</p> <pre><code>esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) socket.set_interface(esp) server = HTTPServer(socket) </code></pre> <p>this code fails when I'm trying to start the server:</p> <pre><code>try: server.start(esp.pretty_ip(esp.ip_address)) print(&quot;Listening on http://%s:80&quot; % esp.pretty_ip(esp.ip_address)) # if the server fails to begin, restart the pico w except OSError: time.sleep(5) print(&quot;restarting..&quot;) microcontroller.reset() </code></pre> <p>and the error is:</p> <pre><code>&gt;&gt;&gt; %Run -c $EDITOR_CONTENT Creating display Creating server socket ESP32 found and in idle mode Firmware vers. bytearray(b'1.2.2\x00') MAC addr: ... ... Connecting to AP... Connected to jama RSSI: -27 My IP address is 192.168.0.24 Creating HTTP Server... starting server.. Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 175, in &lt;module&gt; File &quot;adafruit_httpserver/server.py&quot;, line 91, in start AttributeError: 'socket' object has no attribute 'bind' &gt;&gt;&gt; </code></pre> <p>So it looks like that's not the right socket ? it works for ESP and Requests libs but not for HTTPServer.</p> <p>Here are imports:</p> <pre><code>from adafruit_esp32spi import adafruit_esp32spi import adafruit_esp32spi.adafruit_esp32spi_socket as socket </code></pre> <p>My question then (or two) is if anyone know a workaround for this issue and/or a different socket or server packages I can use instead ?</p> <p>Here is the full code for the reference, it is not finished and contains more stuff that described here but unrelated to the issue:</p> <pre><code>import os import time import busio import board import microcontroller from digitalio import DigitalInOut, Direction import adafruit_bh1750 # import adafruit_requests as requests from adafruit_bme280 import basic as adafruit_bme280 from adafruit_httpserver.server import HTTPServer from adafruit_httpserver.request import HTTPRequest from adafruit_httpserver.response import HTTPResponse from adafruit_httpserver.methods import HTTPMethod from adafruit_httpserver.mime_type import MIMEType from adafruit_epd.epd import Adafruit_EPD from adafruit_epd.il0373 import Adafruit_IL0373 from adafruit_esp32spi import adafruit_esp32spi import adafruit_esp32spi.adafruit_esp32spi_socket as socket try: from secrets import secrets except ImportError: print(&quot;WiFi secrets are kept in secrets.py, please add them there!&quot;) raise # onboard LED setup # led = DigitalInOut(board.LED) # led.direction = Direction.OUTPUT # led.value = False i2c = board.I2C() # uses board.SCL and board.SDA bh1750 = adafruit_bh1750.BH1750(i2c) bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, 0x76) bme280.sea_level_pressure = 1012.50 spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) ecs = DigitalInOut(board.D9) dc = DigitalInOut(board.D10) srcs = DigitalInOut(board.D6) # can be None to use internal memory rst = None #DigitalInOut(board.D1) # can be None to not use this pin busy = None #DigitalInOut(board.D5) # can be None to not use this pin esp32_cs = DigitalInOut(board.D13) esp32_ready = DigitalInOut(board.D11) esp32_reset = DigitalInOut(board.D12) print(&quot;Creating display&quot;) display = Adafruit_IL0373( 128, 296, # 2.9&quot; Tri-color display spi, cs_pin=ecs, dc_pin=dc, sramcs_pin=srcs, rst_pin=rst, busy_pin=busy, ) display.set_black_buffer(1, True) display.set_color_buffer(1, True) display.rotation = 1 display.fill(Adafruit_EPD.WHITE) # display.display() # display.text(splash, 12, 12, Adafruit_EPD.BLACK, size=1) # connect to network print(&quot;Creating server socket&quot;) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) socket.set_interface(esp) if esp.status == adafruit_esp32spi.WL_IDLE_STATUS: print(&quot;ESP32 found and in idle mode&quot;) print(&quot;Firmware vers.&quot;, esp.firmware_version) print(&quot;MAC addr:&quot;, [hex(i) for i in esp.MAC_address]) for ap in esp.scan_networks(): print(&quot;\t%s\t\tRSSI: %d&quot; % (str(ap[&quot;ssid&quot;], &quot;utf-8&quot;), ap[&quot;rssi&quot;])) print(&quot;Connecting to AP...&quot;) while not esp.is_connected: try: esp.connect_AP(secrets[&quot;ssid&quot;], secrets[&quot;password&quot;]) except OSError as e: print(&quot;could not connect to AP, retrying: &quot;, e) continue print(&quot;Connected to&quot;, str(esp.ssid, &quot;utf-8&quot;), &quot;\tRSSI:&quot;, esp.rssi) print(&quot;My IP address is&quot;, esp.pretty_ip(esp.ip_address)) print(&quot;Creating HTTP Server...&quot;) server = HTTPServer(socket) # font for HTML font_family = &quot;monospace&quot; # the HTML script # setup as an f string # this way, can insert string variables from code.py directly # of note, use {{ and }} if something from html *actually* needs to be in brackets # i.e. CSS style formatting def webpage(): html = f&quot;&quot;&quot; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv=&quot;Content-type&quot; content=&quot;text/html;charset=utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;style&gt; html{{font-family: {font_family}; background-color: lightgrey; display:inline-block; margin: 0px auto; text-align: center;}} h1{{color: deeppink; width: 200; word-wrap: break-word; padding: 2vh; font-size: 35px;}} p{{font-size: 1.5rem; width: 200; word-wrap: break-word;}} .button{{font-family: {font_family};display: inline-block; background-color: black; border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}} p.dotted {{margin: auto; width: 75%; font-size: 25px; text-align: center;}} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;title&gt;Pico W HTTP Server&lt;/title&gt; &lt;h1&gt;Pico W HTTP Server&lt;/h1&gt; &lt;br&gt; &lt;p class=&quot;dotted&quot;&gt;This is a Pico W running an HTTP server with CircuitPython.&lt;/p&gt; &lt;br&gt; &lt;p class=&quot;dotted&quot;&gt;The current ambient temperature near the Pico W is &lt;span style=&quot;color: deeppink;&quot;&gt;{temp_test}°{unit}&lt;/span&gt;&lt;/p&gt;&lt;br&gt; &lt;h1&gt;Control the LED on the Pico W with these buttons:&lt;/h1&gt;&lt;br&gt; &lt;form accept-charset=&quot;utf-8&quot; method=&quot;POST&quot;&gt; &lt;button class=&quot;button&quot; name=&quot;LED ON&quot; value=&quot;ON&quot; type=&quot;submit&quot;&gt;LED ON&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&lt;/form&gt; &lt;p&gt;&lt;form accept-charset=&quot;utf-8&quot; method=&quot;POST&quot;&gt; &lt;button class=&quot;button&quot; name=&quot;LED OFF&quot; value=&quot;OFF&quot; type=&quot;submit&quot;&gt;LED OFF&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&lt;/form&gt; &lt;h1&gt;Party?&lt;/h&gt; &lt;p&gt;&lt;form accept-charset=&quot;utf-8&quot; method=&quot;POST&quot;&gt; &lt;button class=&quot;button&quot; name=&quot;party&quot; value=&quot;party&quot; type=&quot;submit&quot;&gt;PARTY!&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&lt;/form&gt; &lt;/body&gt;&lt;/html&gt; &quot;&quot;&quot; return html # route default static IP @server.route(&quot;/&quot;) def base(request: HTTPRequest): # pylint: disable=unused-argument # serve the HTML f string # with content type text/html with HTTPResponse(request, content_type=MIMEType.TYPE_HTML) as response: response.send(f&quot;{webpage()}&quot;) # if a button is pressed on the site @server.route(&quot;/&quot;, method=HTTPMethod.POST) def buttonpress(request: HTTPRequest): # get the raw text raw_text = request.raw_request.decode(&quot;utf8&quot;) print(raw_text) # if the led on button was pressed if &quot;ON&quot; in raw_text: # turn on the onboard LED led.value = True # if the led off button was pressed if &quot;OFF&quot; in raw_text: # turn the onboard LED off led.value = False # reload site with HTTPResponse(request, content_type=MIMEType.TYPE_HTML) as response: response.send(f&quot;{webpage()}&quot;) print(&quot;starting server..&quot;) # startup the server try: server.start(esp.pretty_ip(esp.ip_address)) print(&quot;Listening on http://%s:80&quot; % esp.pretty_ip(esp.ip_address)) # if the server fails to begin, restart the pico w except OSError: time.sleep(5) print(&quot;restarting..&quot;) microcontroller.reset() # text objects for screen # connected to SSID text connect_text_area.text = &quot;Connected to:&quot; ssid_text = &quot;%s&quot; % secrets('ssid') # ssid_text_area = label.Label(terminalio.FONT, text=ssid_text, color=0xFFFFFF, x=0, y=offset_y+15) #splash.append(ssid_text_area) # display ip address ip_text = &quot;IP: %s&quot; % wifi.radio.ipv4_address # ip_text_area = label.Label(terminalio.FONT, text=ip_text, color=0xFFFFFF, x=0, y=offset_y+30) #splash.append(ip_text_area) # display temp reading temp_text = &quot;Temperature: %.02f F&quot; % float(temp_test) # temp_text_area = label.Label(terminalio.FONT, text=temp_text, color=0xFFFFFF, x=0, y=offset_y+45) #splash.append(temp_text_area) def get_weather_conditions(): temp = bme280.temperature print(&quot;\nTemperature: %0.1f C&quot; % temp) hum = bme280.relative_humidity print(&quot;Humidity: %0.1f %%&quot; % hum) pres = bme280.pressure print(&quot;Pressure: %0.1f hPa&quot; % pres) alt = bme280.altitude print(&quot;Altitude: %0.2f meters&quot; % alt) light = bh1750.lux print(&quot;Light: %.2f Lux&quot; % light) return [temp, hum, pres, alt, light] clock = time.monotonic() # time.monotonic() holder for server ping while True: try: # every 30 seconds, ping server &amp; update temp reading if (clock + 30) &lt; time.monotonic(): if wifi.radio.ping(ping_address) is None: connect_text_area.text = &quot;Disconnected!&quot; ssid_text_area.text = None print(&quot;lost connection&quot;) else: connect_text_area.text = &quot;Connected to:&quot; ssid_text_area.text = &quot;%s&quot; % secrets('ssid') print(&quot;connected&quot;) clock = time.monotonic() # comment/uncomment for desired units # temp_test = str(ds18.temperature) temp_test = str(c_to_f(19.45)) temp_text_area.text = &quot;Temperature: %s F&quot; % temp_test # display.show(splash) # poll the server for incoming/outgoing requests server.poll() # pylint: disable=broad-except except Exception as e: print(e) continue </code></pre>
<p>Official answer from Adafuit for this question is that HTTPServer lib is created for Raspeberry PICO and do not work on other boards like Feather M4 express indeed. Different set of libraries needs to be used instead, here is the relevant example: <a href="https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/tree/main/examples/server" rel="nofollow noreferrer">https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/tree/main/examples/server</a></p>
92424
|arduino-ide|
Arduino IDE 1 interfering with Arduino IDE 2?
2023-02-28T15:13:04.827
<p>In our electronics tinker club, we had installed Arduino IDE 1.8 including drivers + the Holtek UART bridge (vendor ID 04D9, product ID B534) for the Elegoo Smart Car Kit 3.0 Plus (<a href="https://www.elegoo.com/en-de/products/elegoo-smart-robot-car-kit-v-3-0-plus" rel="nofollow noreferrer">product link</a>). The board is an Arduino Uno clone.</p> <p>We now installed Arduino IDE 2.0.3 in parallel and tried that one, because its features looked promising.</p> <p>However, in Arduino IDE 2.0.3, we had problems uploading the compiled sketch to the Smart Car Board. When I checked, it reported a different vendor ID and product ID (sorry, I didn't record which one).</p> <p>I reinstalled the Holtek UART bridge driver (<a href="https://roboter-basteln.de/downloads/arduino/USB%20Seriell%20Treiber%20Elegoo%20Smart%20Car%203+%20(Holtek%20UART%20Bridge).exe" rel="nofollow noreferrer">direct download executable</a>) and tried again. The vendor ID and product ID were correct this time, but uploading was still not going well in Arduino IDE 2.0.3.</p> <p>Switching back to Arduino IDE 1.8 doesn't help. While the code still compiles (I expected it to), the upload problems now affect Arduino 1.8 as well, which was totally fine before we installed Arduino IDE 2.0.3.</p> <p>How could I fix this issue?</p> <p>I'll try to uninstall and reinstall everything, but I'm not sure it will be possible to uninstall all drivers.</p>
<p>I spent more time (almost 20 working hours) to isolate this problem by</p> <ul> <li>testing the behavior with all of our 9 robot hardware in the club</li> <li>testing the behavior with all of our 8 notebooks in the club</li> <li>testing with the 6 different implementations we had, bricking and not bricking our robot hardware</li> <li>testing with an additional notebook that didn't seem affected</li> <li>combinations thereof</li> </ul> <p>Finally I had a reproducible procedure with which I could &quot;brick&quot; a robot hardware and another procedure which would &quot;unbrick&quot; it.</p> <p>That way I was able to a) minimize the code that was needed to &quot;brick&quot; the robot and b) compare that to the other codes that didn't have the issue. Finally I could ask <a href="https://arduino.stackexchange.com/questions/92513/where-does-this-sketch-have-undefined-behavior">this new question</a> and get valuable feedback.</p> <p>It turned out that this was <strong>not related to the new Arduino 2.0.3 or 2.0.4 IDE. It was just a timely coincidence</strong> that we wrote a new sketch we never wrote before in this way for this hardware.</p> <p>That code used <code>Serial.begin()</code> with a &quot;high&quot; baud rate and obviously less delays than we ever used on this hardware before. And it <a href="https://arduino.stackexchange.com/a/92523/35430">turned out</a> our hardware can't handle speeds higher than 19200 baud (!) without <code>delay()</code> statements. That's so slow!</p>
92436
|string|
if statement with string comparison
2023-03-01T08:05:22.127
<p><strong>Code Snippet:</strong></p> <pre><code>String a; const int red_led_pin = 13; void setup() { Serial.begin(115200); Serial.println(&quot;Hello, ESP32-S2!&quot;); pinMode(red_led_pin, OUTPUT); } void loop() { while (Serial.available()) { a = Serial.readString();// read the incoming data as string Serial.print(&quot; First: &quot;); Serial.println(a); if (a.equals(&quot;on&quot;)) { Serial.println(&quot;LED ON&quot;); digitalWrite(red_led_pin, HIGH); } else if (a == &quot;off&quot; || a == &quot;OFF&quot;) { Serial.println(&quot;LED OFF&quot;); digitalWrite(red_led_pin, LOW); } Serial.print(&quot;Second: &quot;); Serial.println(a); } } </code></pre> <p><strong><code>Serial.print</code> out:</strong></p> <p><a href="https://i.stack.imgur.com/kJPdF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kJPdF.png" alt="enter image description here" /></a></p> <p><strong>Circuitry:</strong></p> <p><a href="https://i.stack.imgur.com/x3e3r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x3e3r.png" alt="enter image description here" /></a></p> <p><strong>Issue:</strong></p> <p>The code can't capture the <code>on</code> string or any other string (<code>on</code>, <code>off</code> or <code>OFF</code>) that I pass. However it does pick it up and <code>Serial.print</code> it.</p> <p>What is going wrong?</p> <p><strong>Things I have tried:</strong></p> <p>I have tried as a comparison:</p> <ul> <li><code>if (a.equals(&quot;on&quot;)){&lt;&gt;}</code></li> <li><code>if (a == &quot;on&quot;)){&lt;&gt;}</code></li> <li><code>if (a.equalsIgnoreCase(&quot;on&quot;)){&lt;&gt;}</code></li> </ul> <p><strong>Due Diligence / Prior Research:</strong></p> <ul> <li><a href="https://docs.arduino.cc/built-in-examples/strings/StringComparisonOperators" rel="nofollow noreferrer">[ Documentation ] String Comparison Operators</a></li> <li><a href="https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/" rel="nofollow noreferrer">[ Documentation ] String()</a></li> <li><a href="https://forum.arduino.cc/t/compare-characters-or-string-in-if-function/692192/20" rel="nofollow noreferrer">[ Forum ] Compare characters (or string) in “if” function</a></li> </ul>
<p>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 <code>'\n'</code> is used.</p> <p>This line ending will be in your string, when using <code>Serial.readString()</code>, so the string is not equal to <code>&quot;on&quot;</code>, but to something like <code>&quot;on\n&quot;</code>.</p> <p>You can solve this issue by two ways:</p> <ul> <li>Set the Serial Monitor to no line ending.</li> <li>Or better: Use something like <code>Serial.readStringUntil()</code> and pass the line ending character to it as parameter (for example <code>Serial.readStringUntil('\n')</code>). 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).</li> </ul>
92441
|library|c-preprocessor|
Unable to get my created library to work - while it compiles
2023-03-01T15:33:51.053
<p>I am experimenting with creating my own Arduino libraries. Unfortunately, while the program compiles, the end result does not work.</p> <p>For purposes of experimentation, I have broken down the library in two parts. One that will handle blinking by controlling the <code>LED_BUILDIN</code> pin and one that will talk to the serial input.</p> <p>Thus two <code>.h</code> and two <code>.cpp</code> files. Plus there is another file for the configuration that handles preprocessor directives that the library reads.</p> <p>This is the code:</p> <p>FILE 1</p> <pre><code>//header_config.h #ifndef MY_CONFIGURATION #define MY_CONFIGURATION #include &lt;Arduino.h&gt; #define SERIAL_DEBUG #define LED_BLINK #include &lt;led_functions.h&gt; #include &lt;serial_functions.h&gt; void my_setup() { my_setup_led(); } void my_loop() { led_blinker(); serial_transmit(&quot;Hello&quot;); } #endif </code></pre> <p>FILE 2</p> <pre><code>//led_functions.h #ifndef MY_LED_LIBRARY #define MY_LED_LIBRARY #include &lt;Arduino.h&gt; #include &quot;header_config.h&quot; #include &quot;serial_functions.h&quot; extern void led_blinker(); extern void my_setup_led(); #endif </code></pre> <p>FILE 3</p> <pre><code>//led_functions.cpp void led_blinker() { #ifdef LED_BLINK digitalWrite(LED_BUILTIN, HIGH); serial_transmit(&quot;LED ON&quot;); delay(1000); digitalWrite(LED_BUILTIN, LOW); serial_transmit(&quot;LED OFF&quot;); delay(1000); #endif } void my_setup_led() { #ifdef LED_BLINK pinMode(LED_BUILTIN, OUTPUT); #endif } </code></pre> <p>FILE 4</p> <pre><code>//serial_functions.h #ifndef MY_SERIAL_LIBRARY #define MY_SERIAL_LIBRARY #include &lt;Arduino.h&gt; #include &quot;header_config.h&quot; #ifdef SERIAL_DEBUG #include &lt;SoftwareSerial.h&gt; #define rxPin 2 #define txPin 3 SoftwareSerial mySerial(rxPin, txPin); #endif extern void serial_transmit(char*); #endif </code></pre> <p>FILE 5</p> <pre><code>//serial_functions.cpp void serial_transmit(char *str) { #ifdef SERIAL_DEBUG //mySerial.begin(9600); //mySerial.println(str); //mySerial.end(); Serial.begin(9600); Serial.println(str); Serial.end(); #endif } </code></pre> <p>Please note that while the serial code creates a <code>SoftwareSerial</code> object (in <code>serial_functions.h</code>), I do not use that (in <code>serial_functions.cpp</code>) and instead I make use of hardware Serial. The reason is debugging, so that I can see communication on the PC. I left the <code>SoftwareSerial</code> object inside, because that is what I ultimately want.</p> <p>Finally, outside the library, in it's separate folder, is the <code>.ino</code> file that makes use of this library.</p> <pre><code>#include &lt;header_config.h&gt; #include &lt;led_functions.h&gt; #include &lt;serial_functions.h&gt; void setup() { my_setup(); } void loop() { my_loop(); } </code></pre> <p>As I said, the program compiles fine, but it does not work in the real world. Neither the blinking, nor the serial communication.</p>
<p>Your cpp files don't include the header_config.h file, so they don't have SERIAL_DEBUG and LED_BLINK defined.</p> <p>The content of included file replaces the include directive so if you now include header_config.h into both cpp, there will be 3 functions named my_setup() and 3 functions named my_loop() and the linker will complain. So you can't put functions definitions into an include file. And for the same reason you can't have variable definitions in .h file so the SoftwareSerial instance will cause problems too if used.</p>
92451
|arduino-mega|
How to prevent an Arduino connected to the Internet from being hacked?
2023-03-02T14:25:09.563
<p>I have an Arduino (with environmental sensors doing measurements) connected to the Internet via ethernet. Can it be hacked? Can someone access it via Internet and upload his own C/C++ code? If, yes how can I prevent this?</p> <p><strong>Update (03/03/2023):</strong> One final thought: Supposing that I have secured USB plug and nobody can access it. However, I am using the Serial interface of the Arduino MEGA 2560. So, Serial_1 is continuously reading. Can someone with <em><strong>physical access</strong></em> to the Arduino inject malicious code via the Serial_1 so that can alter the code inside my Arduino and have access to information?</p>
<p>This depends on what you consider &quot;hacked&quot;.</p> <p>Do you care about someone reading the data, or changing it on its way to the target? Or do you provide endpoints to trigger something in your project from the internet, that only you should be able to do? Then you need to think about authentication and encryption. Though I guess that this data will be published either way, so that is not a big problem. But you should write down every endpoint, that you expose to the internet, and every request you are making. Then decide what level of security you need them to have individually. Exposed endpoints can easily be found and you have to decide yourself, if it is OK for others to use them.</p> <p>If you mean getting into the device and executing malicious code from there: IOT devices are often vulnerable because of two reasons. They often have an OS (like a small linux OS), that is badly secured (often using standard password). And they often get updates via the internet. If someone can hijack the update process, malicious code might be delivered. An Arduino doesn't have an OS, so that isn't a problem. And hijacking the update process won't be possible, if you don't provide the possibility to update through the network. This makes updating your code a bit more complicated (since you need to connect the Arduino via USB or similar to program it), but more secure. That way no one (not even you) can inject malicious code into your project without physical access to the Arduino. To take up Jurajs comment: Updating through network is normally done by the Ethernet bootloader or the ArduinoOTA library (Over The Air updates). If you are not using those or similar projects, then you will be safe in that regard.</p> <hr /> <p>With strangers having physical access to the device it is a different story. To reprogram the Arduino one would need access to Serial (RX0 and TX0) and a possibility to reset the Arduino (either Reset pin or a way for power cycling it), or access to the ISP pins and the reset pin.</p> <p>If you can secure the Arduino itself from physical access and only expose the Serial1 interface and ground/5V, then you will be safe, since the bootloader is only listening on Serial (RX0 and TX0). But keep in mind, that someone might still break into your project with brute force - depending on how you secured it physically. At that point nothing can stop them from overwriting your code. Only you can assess how big the chance for that is and how bad it would be.</p> <p>Another point: If someone manages to break into your project, he can read out the program and push it through a deassembler. That doesn't give them the C++ code - they are not seeing C++ code, only assembler, and no meaningful variable names - but if they are determined enough they can read out credentials, that you might have hard coded or saved in EEPROM. Though especially for environmental sensors I would say the chance is very low, that someone would go to such lengths. If you think the danger to be big enough for some inconvenience, you can have a look at code protection (protecting the program memory from being read), though that still doesn't completely block reprogramming.</p> <p>All in all: Preventing physical access is a big step in security. You yourself need to assess how much security you really need for your project.</p>
92463
|arduino-ide|attiny|
Sudden Error: File does not exist
2023-03-04T01:26:36.910
<p>I am suddenly getting an error every time I try to compile code in the IDE, even though every one of the sketches previously compiled just fine:</p> <pre><code>Arduino: 1.8.13 (Windows 7), Board: &quot;MH-ET LIVE Tiny88(16.0MHz)&quot; C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\lrhorer\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\lrhorer\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\lrhorer\Documents\Arduino\libraries -fqbn=mhetlive:avr:MHETtiny88 -ide-version=10813 -build-path C:\Users\lrhorer\AppData\Local\Temp\arduino_build_609285 -warnings=all -build-cache C:\Users\lrhorer\AppData\Local\Temp\arduino_cache_521731 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\tools\micronucleus\2.0a4 -prefs=runtime.tools.micronucleus-2.0a4.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\tools\micronucleus\2.0a4 -prefs=runtime.tools.avr-gcc.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.8.1-arduino5 -prefs=runtime.tools.avr-gcc-4.8.1-arduino5.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.8.1-arduino5 -verbose C:\Users\lrhorer\Documents\Arduino\sketch_feb27a\sketch_feb27a.ino C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\lrhorer\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\lrhorer\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\lrhorer\Documents\Arduino\libraries -fqbn=mhetlive:avr:MHETtiny88 -ide-version=10813 -build-path C:\Users\lrhorer\AppData\Local\Temp\arduino_build_609285 -warnings=all -build-cache C:\Users\lrhorer\AppData\Local\Temp\arduino_cache_521731 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\tools\micronucleus\2.0a4 -prefs=runtime.tools.micronucleus-2.0a4.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\tools\micronucleus\2.0a4 -prefs=runtime.tools.avr-gcc.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.8.1-arduino5 -prefs=runtime.tools.avr-gcc-4.8.1-arduino5.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.8.1-arduino5 -verbose C:\Users\lrhorer\Documents\Arduino\sketch_feb27a\sketch_feb27a.ino Using board 'MHETtiny88' from platform in folder: C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\hardware\avr\1.0.0 Using core 'tiny88' from platform in folder: C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\hardware\avr\1.0.0 Detecting libraries used... &quot;C:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\4.8.1-arduino5/bin/avr-g++&quot; -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -w -x c++ -E -CC -mmcu=attiny88 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DIGISPARKPRO -DARDUINO_ARCH_AVR &quot;-IC:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\mhetlive\\hardware\\avr\\1.0.0\\cores\\tiny88&quot; &quot;-IC:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\mhetlive\\hardware\\avr\\1.0.0\\variants\\tiny88&quot; &quot;C:\\Users\\lrhorer\\AppData\\Local\\Temp\\arduino_build_609285\\sketch\\sketch_feb27a.ino.cpp&quot; -o nul -DARDUINO_LIB_DISCOVERY_PHASE exec: &quot;C:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\4.8.1-arduino5/bin/avr-g++&quot;: file does not exist Error compiling for board MH-ET LIVE Tiny88(16.0MHz). </code></pre> <p>The file indeed does not exist in that location. What now?</p> <p>Update: Under the ATTinyCore compiler the missing file name is the same, but the directory is different:</p> <pre><code>exec: &quot;C:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++&quot;: file does not exist </code></pre> <p>The latest version of the DigiStump compiler does not even have the MH-ET Live Tiny88 board compiler included.</p> <p>I can get the code to compile under Linux, but I am having trouble uploading the binary to the board. How can I take the binary code and upload it to the ATTiny88 board under either Linux or Windows 7?</p> <p>Update: I found three files quarantined by my anti-virus. I restored the files, and now avr-g++.exe seems to be back where it belongs, and the compiler no longer claims the file is missing. Now, however, it s complaining about not finding the stdlib.h library called from the Arduino.h library.</p> <p>Update: After I removed three files apparently related to the IDE from quarantine by my virus scanner, I deleted everything, and re-installed the IDE. Now it compiles without error, but I cannot upload to the board in either Windows or Linux. Of course I tried more than once to reinstall the Windows USB drivers, and they install without error, but the virtual device does not show up like it is supposed to, and the upload processor times out.</p>
<p>Deleting / uninstalling the entire IDE and completely reinstalling allowed the code to compile, so I am closing this question. It will not upload, so I will open another question.</p>
92471
|digital|digitalwrite|digital-in|
Fast digital IO
2023-03-04T20:34:43.560
<p>I have a device programmable via an 8 bit digital parallel bus. I would like an Arduino to translate from a parallel 4 bit output of an existing device to 8 bit by intentionally reducing the resuloution. Unfortunately, I can't just use the most significant bits as I want to change the step size. The idea is to use an Arduino that ready the 4 digital input bits and then computs the necessary 8 bit output which it output to the 8 bit bus. However, this need to be as fast as 1 us. Is this possible with an Arduino? If so which board would you recommend? I guess I can't use the digitalWrite command as this will be too slow though. Any suggestions?</p>
<p>You can do this with an Uno, provided it has nothing else to do. I would program it low-level, skipping the Arduino core since, as you said, <code>digitalWrite()</code> would be too slow for this application.</p> <p>Here is my proposed approach: read the 4-bit input from one port, use a look-up table to translate it to an 8-bit output, and write that output to another port. I would use PORTD (pins 0–7) for the output, as it is the only full 8-bit port on the Uno, then the first bits of PORTB (pins 8–11) for the input:</p> <pre class="lang-cpp prettyprint-override"><code>/* Translation look-up table (dummy example). */ const uint8_t lut[16] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; int main() { DDRB = 0x00; // set port B as input DDRD = 0xff; // set port D as output for (;;) { uint8_t input = PINB &amp; 0x0f; // grab the lowest 4 bits PORTD = lut[input]; // set the output } } </code></pre> <p>I compiled and disassembled this code to count the CPU cycles: the main loop takes 10 cycles per iteration. Given that the Uno is clocked at 16 MHz, this is one update of the output every 0.625 µs.</p> <p><strong>Edit</strong>: This is a straightforward approach. At the cost of some extra complexity, it could be optimized down to 7 cycles per iteration (0.438 µs), or even 6 cycles (0.375 µs) in assembly.</p>
92484
|time|
localtime - executing one after the other- different time_t, but getting same results
2023-03-06T18:34:31.377
<p>When I try to comapre 2 <code>time_t</code> values I get unexplained behavour</p> <pre><code>time_t t = 12345; time_t T = 67890; struct tm *tm = localtime(&amp;t); struct tm *Tm = localtime(&amp;T); char timeStamp[40]; sprintf(timeStamp, &quot;(1) %04d-%02d-%02d %02d:%02d:%02d&quot;, tm-&gt;tm_year + 1900, tm-&gt;tm_mon + 1, tm-&gt;tm_mday, tm-&gt;tm_hour, tm-&gt;tm_min, tm-&gt;tm_sec); Serial.println(timeStamp); sprintf(timeStamp, &quot;(2) %04d-%02d-%02d %02d:%02d:%02d&quot;, Tm-&gt;tm_year + 1900, Tm-&gt;tm_mon + 1, Tm-&gt;tm_mday, Tm-&gt;tm_hour, Tm-&gt;tm_min, Tm-&gt;tm_sec); Serial.println(timeStamp); </code></pre> <p>I get the exact same date.</p> <p>When commenting out one of each set, I get the correct answer for each one.</p> <p>Workaround I did was, but i'm sure there is an elegant way to overcome:</p> <pre><code> time_t t = 12345; time_t T = 12345; struct tm *tm = localtime(&amp;t); uint8_t now_month = tm-&gt;tm_mon; uint8_t now_day = tm-&gt;tm_mday; struct tm *Tm = localtime(&amp;T); uint8_t save_month = Tm-&gt;tm_mon; uint8_t save_day = Tm-&gt;tm_mday; if (now_month == save_month &amp;&amp; now_day == save_day) { } </code></pre>
<p>From <a href="https://man7.org/linux/man-pages/man3/localtime.3p.html" rel="nofollow noreferrer">the manual page of <code>localtime()</code></a> (emphasis mine):</p> <blockquote> <p>The <code>asctime()</code>, <code>ctime()</code>, <code>gmtime()</code>, and <code>localtime()</code> functions shall return values in one of two static objects: a broken-down time structure and an array of type <code>char</code>. <strong>Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.</strong></p> </blockquote> <p>As a solution, I suggest you take a copy of the <code>struct tm</code> used by <code>localtime()</code> to store its result, rather than keeping a pointer to it:</p> <pre class="lang-cpp prettyprint-override"><code>struct tm tm = *localtime(&amp;t); struct tm Tm = *localtime(&amp;T); </code></pre>
92494
|pointer|stm32|
Difference between (*(volatile unsigned int *) and (volatile unsigned int)?
2023-03-07T07:55:04.803
<p>I have been watching tutorials on <strong>STM32 bare metal programming</strong>. I couldn't understand the purpose of the below code</p> <pre><code> #define RCC_AHB1EN_R (*(volatile unsigned int *)(RCC_BASE + AHB1EN_R_OFFSET)) </code></pre> <p>and why it's different from</p> <pre><code>#define RCC_AHB1EN_R (volatile unsigned int)(RCC_BASE + AHB1EN_R_OFFSET)) </code></pre> <p>I understand <code>(volatile unsigned int *)</code> is used to typecast any data, so it code will get its address value, not the data itself, then adding <code>(*)</code> will pick the data value of the address. I know why volatile is used to tell not to optimize this code for this data.</p> <p>That's my basic knowledge of pointers, if I wasn't right till now please correct me.</p> <p><strong>So my question are</strong></p> <ol> <li><p>Why and what's the purpose of typecasting the data to address(pointer) and then use its value?</p> </li> <li><p>Why not we directly use the value itself (of course with volatile typecasting) like</p> </li> </ol> <p><code>#define RCC_AHB1EN_R (volatile unsigned int)(RCC_BASE + AHB1EN_R_OFFSET))</code></p> <ol start="3"> <li>If we can use whichever we can, are there any benefits of one over the other?</li> </ol>
<p>In the first line, RCC_AHB1EN_R is a pointer to location. you got that from the casting.</p> <p>#define RCC_AHB1EN_R (*(volatile unsigned int *)(RCC_BASE + AHB1EN_R_OFFSET))</p> <p>In the second line, RCC_AHB1EN_R holds a base address which is an integer.</p> <p>#define RCC_AHB1EN_R (volatile unsigned int)(RCC_BASE + AHB1EN_R_OFFSET))</p> <p>hope this give you clarity?</p>
92503
|c++|esp32|sleep|integer|
integer overflow in expression of type 'int' results
2023-03-08T03:31:48.647
<p>i need to wake up my ESP every 60 min to read some data and post it to server, all process working fine when i use numbers of minute below 60 (converted in microsecond x 1000000) but when i use 60 min above i get the following message:</p> <blockquote> <p>src/main.cpp:137:49: warning: integer overflow in expression of type 'int' results in '-694967296' [-Woverflow] esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);// set up next wake up after 30 sec</p> </blockquote> <p>How can i make my ESP wake up every 60 min or above?</p> <p>simplify code:</p> <pre><code>// for awake and sleep #define uS_TO_S_FACTOR 1000000 #define TIME_TO_SLEEP 60 // minute void setup(){ esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * 60 * uS_TO_S_FACTOR);// error if time to sleep more than 60 min } </code></pre>
<p>Change that line to:</p> <pre><code>esp_sleep_enable_timer_wakeup((uint64_t) TIME_TO_SLEEP * 60 * uS_TO_S_FACTOR); </code></pre> <p>That forces the compiler to do 64-bit arithmetic on the constant rather than defaulting to &quot;int&quot; arithmetic.</p>
92513
|arduino-uno|c++|
Where does this sketch have Undefined Behavior?
2023-03-08T17:51:37.383
<p>Simple sketch and simple question: where does this sketch have undefined behavior?</p> <p>Note: I don't need a solution to fix the code. I already have code that works. I really need to understand where my thinking is wrong.</p> <p>Background: some kids were writing a program for a line follower robot which has 3 digital sensors. Many of them bricked their Arduino. I reduced the affected sketches to quite a minimum so that it still reproduces the problem. The sketch is pretty self-explanatory I hope.</p> <p>It gives no warnings in Arduino IDE 1.8.9, 1.8.15 and 2.0.4 even with all warnings enabled.</p> <p>Still, this code bricks all the Arduino clones (9 instances of Elegoo Smart Robot Car Kit 3.0 Plus) and I spent several hours to find a reliable procedure to unbrick them. Therefore I have strong belief that this code must have undefined behavior - except that I can't see it.</p> <p>The unbrick procedure is:</p> <ol> <li>Remove the shield, if not removed yet</li> <li>Disconnect Arduino from USB</li> <li>Connect Arduino to USB</li> <li>Press Reset button on the Arduino board</li> <li>Disconnect Arduino from USB again (!)</li> <li>Connect Arduino to USB</li> <li>Compile and upload an empty sketch</li> </ol> <pre class="lang-cpp prettyprint-override"><code>long PIN_LINE_LEFT = 10; long PIN_LINE_MID = 4; long PIN_LINE_RIGHT = 2; long DATARATE = 115200; void setup() { pinMode(PIN_LINE_LEFT, INPUT); pinMode(PIN_LINE_MID, INPUT); pinMode(PIN_LINE_RIGHT, INPUT); Serial.begin(DATARATE); } void loop() { byte leftValue = digitalRead(PIN_LINE_LEFT); Serial.println(leftValue); } </code></pre> <p>Here's my analysis:</p> <p>IMHO, the sketch is unusual just in one way: instead of <code>#define</code>ing the pin numbers and other stuff, it declares them as global variables of type <code>long</code>.</p> <p>According to <a href="https://www.arduino.cc/reference/en/language/variables/data-types/long/" rel="nofollow noreferrer">the Arduino reference about data types</a> a <code>long</code> is 32 bit. Printing <code>sizeof(long)</code> confirms that. Therefore, 115200 will not overflow at 65536 (16 Bit).</p> <p>For <code>Serial.begin()</code>, the <code>DATARATE</code> will be converted into an <code>unsigned long</code>, which IMHO should not be a problem here, since the number is positive.</p> <p>Sure enough, the pin numbers needn't be <code>long</code> and should be declared as <code>uint8_t</code> to better match the <code>pinMode()</code> and <code>digitalRead()</code> function. But I still think the implicit conversion down to <code>uint8_t</code> should be fine, since there is no overflow either.</p> <p>Next, <code>digitalRead()</code> officially returns an <code>int</code>. The result is assigned to a <code>byte</code> which is an alias for <code>uint8_t</code>. It seems that this also gets converted implicitly. However, the values should only be <code>HIGH</code> or <code>LOW</code>, i.e. 1 or 0, which does not generate a signed overflow either.</p> <p>What I tried:</p> <p>Changing <code>DATARATE</code> to the more appropriate <code>unsigned long DATARATE = 115200UL;</code> doesn't change anything.</p> <p>Changing <code>byte leftValue = digitalRead(PIN_LINE_LEFT);</code> to the more appropriate <code>int leftValue = digitalRead(PIN_LINE_LEFT);</code> also didn't change anything.</p> <p>Changing <code>long PIN_LINE_MID = 4;</code> and all others to the more appropriate <code>uint8_t PIN_LINE_xxx = xxx;</code> also doesn't change anything.</p> <p>IMHO with these changes, there's basically nothing left to fix and this should be a super valid C/C++ program without any implicit dangerous casts.</p> <p>A <code>Serial.flush();</code> in the loop is not needed according to the <a href="https://www.arduino.cc/reference/en/language/functions/communication/serial/write/" rel="nofollow noreferrer">documentation of <code>Serial.write()</code></a>. So there will not be a buffer overflow.</p>
<p>With some USB to TTL Serial chips it is a problem to start the upload if there is too much input from the MCU on the Serial side. In this case it is the Holtek UART Bridge which is not common for Arduino boards.</p> <p>To stop the sketch, hold the reset button until the upload from IDE starts. When the reset button is released, the bootloader starts and receives the upload.</p>
92525
|arduino-ide|avrdude|atmega32u4|
How does Arduino IDE reset a board before flashing? Why doesn't avrdude do it?
2023-03-09T15:31:58.113
<p>I have the beetle board, a Leonardo clone same as in this <a href="https://arduino.stackexchange.com/q/69433/89339">question</a>.</p> <p><a href="https://i.stack.imgur.com/07oIh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/07oIh.jpg" alt="Arduino Leonardo Beetle mini board" /></a></p> <p>Using the reset pin and quick hands on the keyboard, I am able to flash with avrdude and get also the board info with a command line like this:</p> <pre><code>$ avrdude -c avr109 -p atmega32u4 -P /dev/ttyACM1 </code></pre> <p>And get the output:</p> <pre><code>Connecting to programmer: . Found programmer: Id = &quot;CATERIN&quot;; type = S Software Version = 1.0; No Hardware Version given. Programmer supports auto addr increment. Programmer supports buffered memory access with buffersize=128 bytes. Programmer supports the following devices: Device code: 0x44 avrdude: AVR device initialized and ready to accept instructions Reading | ################################################## | 100% 0.00s avrdude: Device signature = 0x1e9587 (probably m32u4) avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF) avrdude done. Thank you. </code></pre> <p>This is good but when I flash something from the ArduinoIDE I noticed I don't have to reset the board manually by grounding the reset pins, the boot loader starts automatically</p> <p>How does ArduinoIDE reset the bootloader, some kind of communication on <code>/dev/ttyACM1</code>?</p>
<p>The uploaded Arduino sketch has in the part provided by core a code which waits for a 1200 baud connection on USB. If a 1200 baud connection is established it resets the board to bootloader. The bootloader then starts the com port and waits for the upload.</p> <p>To reset a board which has in boards.txt <code>upload.use_1200bps_touch=true</code> Arduino IDE opens a 1200 baud connection to the board, then detects the new com port and start avrdude for the upload.</p>
92547
|attiny85|fuses|arduino-ide-2|
How to burn fuses in Digistump ATTiny85 with the Arduino IDE
2023-03-10T19:59:11.800
<p>I have a Digispark / digistump Attiny85. Working with Windows 11 and the Arduino IDE 2.0.4 I would like this guy to have Brown Out Detection set to 101 (2.7V)</p> <p>For this, I'd need to set the BOD fuses.</p> <p>How can I do this with the USB interface of the Arduino IDE? To use the USB programming, I have to set the Board to &quot;Digispark (Default 16.5Mhz)&quot;.</p> <p>I have seen that in normal ATTiny85 operation, under the Tools-Menu I could choose the fuses I like. In the Digispark Default setting this is not available.</p>
<p>The first thing to say (already mentionened by @timemage) is that there is a large variety of &quot;Digispark / Digistump&quot; devices, both original, clones using the Micronucleus bootloader, even when considering only the ATTiny85 variants. Those variants, where the reset pin has not been re-configured as a GPIO pin, are easier to use. Otherwise, you firstly need a high voltage programmer to reset the ATTiny85 to its factory state, to restore the reset pin for configuring fuses etc.</p> <p>The second thing is that the last post here: digistump.com/board/index.php/topic,2257.msg10556.html#msg10556 implies that 2.7v brown out, which you appear to need, is anyway already enabled (at least with the variant described by the author) That is, the fuse settings are: lfuse 0xE1 hfuse 0x5D efuse 0xFE.</p> <p>Anyway, to change the fuses (or load the &quot;Digispark / Digistump&quot; (Micronucleus) bootloader) you need an ISP programmer (an Arduino or even another digispark can be configured as such). See: digistump.com/wiki/digispark/tutorials/programming. With the ISP programmer connected, you can then use AVRDUDE also to set the fuses.</p> <p>In the worst case, you have to start with a factory condition ATtiny85 and go through the entire process of loading the &quot;Digispark / Digistump&quot; firmware onto it and configuring the appropriate fuse settings. See <a href="https://circuitdigest.com/microcontroller-projects/attiny85-ic-programming-through-usb-using-digispark-bootloader" rel="nofollow noreferrer">https://circuitdigest.com/microcontroller-projects/attiny85-ic-programming-through-usb-using-digispark-bootloader</a></p>
92549
|servo|pwm|analog|
Controlling a servo without the servo library
2023-03-10T21:34:01.853
<p>I am trying to control a servo without the &quot;Servo.h&quot; library.I am sending using <code>analogWrite()</code> some values to the servo.I know the servo takes input a continuous time signal however I dont know the necessary frequency of that signal so I am not producing any sensible movement.What else should I consider when trying to control the servo using <code>analogWrite()</code>s?</p>
<p>It can be done using <code>digitalWrite()</code> and <code>delayMicroseconds()</code>.</p> <p>A servo is driven by a pulse. The pulse is between 1 ms (0°) over 1.5 ms (90°) to 2 ms (180°), followed by a pause that makes the total duration of a cycle 20 ms.</p> <p>The 20 ms correspond to a 50 Hz signal. <code>analogWrite()</code> uses frequencies from 490 to 1000 Hz (depending on your hardware), which is why that won't work unless you figure out how to change the frequency.</p>
92557
|arduino-uno|arduino-nano|interrupt|avr|
Checking a thing about interrupts
2023-03-11T15:16:50.980
<p>If I disable interrupts (for example <code>noInterrupts</code> or <code>cli</code>) and enable them (<code>interrupts</code> or <code>sei</code> for example) later, would interrupts which would have executed in the window in between fire by the execution of the latter? I guess not, and haven't confirmed or denied it. If not it is always an option to manually disable timers or components with similar concerns with respect to the interrupt status? It makes sense that AVR-based Arduino boards would behave similarly. It seems plausible that the bits for the force interrupt execution will turn on and turned off when the jump occurs. Thanks for reaching out.</p>
<p>See <a href="https://arduino.stackexchange.com/questions/30968/how-do-interrupts-work-on-the-arduino-uno-and-similar-boards/30969#30969">How do interrupts work on the Arduino Uno and similar boards?</a></p> <p>Yes, most interrupts will be remembered and the ISR will be executed when interrupts are enabled again, plus one more instruction has been executed. If that didn't happen it would be very bad, as you may turn off interrupts briefly and you wouldn't want to miss the thing that the interrupt was for (eg. incoming serial data).</p> <p>To stop that happening you need to clear the &quot;interrupt has happened&quot; bit for the individual interrupts. This is documented in the datasheet for each interrupt.</p> <p>The order in which outstanding interrupts will be serviced is the interrupt priority, that is lower-numbered interrupts will be serviced first. The call to the ISR causes the processor to clear the &quot;interrupt has happened&quot; bit for that interrupt.</p>
92558
|power|esp32|battery|
AA alkaline batteries on firebeetle?
2023-03-11T16:22:07.073
<p>I would like to power a dfrobot firebeetle 2 using 3 alkaline batteries. I tried connecting the battery pack to the GND and VCC, but the board does not seem to react. What pins should i connect the leads to?</p> <p>The firebeetle 2 info page: <a href="https://www.dfrobot.com/product-2195.html" rel="nofollow noreferrer">https://www.dfrobot.com/product-2195.html</a></p>
<p>The following is based purely on the small amount of information in your question. You haven't described your code or your setup, which would allow this answer to be more specific.</p> <p>According to the FireBeetle ESP32 schematics <a href="https://dfimg.dfrobot.com/nobody/wiki/fd28d987619c16281bdc4f40990e5a1c.PDF" rel="nofollow noreferrer">here</a>, you should be able to connect an external power supply between VCC(+) and GND(-).</p> <p><a href="https://i.stack.imgur.com/NtgWv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NtgWv.png" alt="enter image description here" /></a></p> <p>The voltage regulator on the FireBeetle ESP32 is a low-dropout RT9080 regulator, which, according to its <a href="https://www.farnell.com/datasheets/2183318.pdf" rel="nofollow noreferrer">datasheet</a> has a maximum voltage drop of about 0.5 V when outputting the 3.3 V needed by your board and a maximum input voltage of 5.5 V.</p> <p>That means the voltage supplied at VCC should be between 3.8 V and 5.5 V, and the ~4.5 V supplied by your 3 x AA batteries (assuming they're connected in series), falls nicely into this range.</p> <p>The fact that your board does not seem to run your code might be caused by a number of things.</p> <ol> <li>Does your program expect a Serial port connection which, of course, is not available when it's not connected to a PC by USB?</li> <li>The power demanded by your board might be too high for the batteries. Are there other things connected to the board that that could cause that?</li> </ol> <p>If you have a multimeter, you should be able to measure a stable 3.3 V on the 3.3 V pin of the FireBeetle.</p>
92577
|arduino-zero|debug|
Does Arduino Zero need to be switched between USB EDBG and JTAG port debug use?
2023-03-13T11:42:57.650
<p>I wanted to compare the debug output of the Arduino Zero when connecting via two different debug paths.</p> <ol> <li>Via the embedded debugger (EDBG) connected to Arduino IDE via USB</li> <li>Via the JTAG hardware connector J100 to a Black Magic Probe and GDB</li> </ol> <p>The two paths being compared are shown on the <a href="https://cdn-shop.adafruit.com/product-files/2843/Arduino-Zero-schematic.pdf" rel="nofollow noreferrer">Zero Schematic</a>: <a href="https://i.stack.imgur.com/uLQ1w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uLQ1w.png" alt="Snipped image of the JTAG related part of the schematic" /></a></p> <p>Using the Blink.ino compiled for debug, the EDBG works as expected into the Arduino IDE 2.0.4 debugger via USB.</p> <p>However using the same sketch with the JTAG hardware port to a black magic probe fails to connect, reporting &quot;Target voltage: 1.0V&quot;.</p> <pre><code>rowan@rowan-ThinkPad-X1-Carbon-4th:/tmp/arduino/sketches/1EBCACBEAD6C08902D692E87F523B56E$ arm-none-eabi-gdb Blink.ino.elf GNU gdb (GNU Arm Embedded Toolchain 10.3-2021.10) 10.2.90.20210621-git Copyright (C) 2021 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt; This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type &quot;show copying&quot; and &quot;show warranty&quot; for details. This GDB was configured as &quot;--host=x86_64-linux-gnu --target=arm-none-eabi&quot;. Type &quot;show configuration&quot; for configuration details. For bug reporting instructions, please see: &lt;https://www.gnu.org/software/gdb/bugs/&gt;. Find the GDB manual and other documentation resources online at: &lt;http://www.gnu.org/software/gdb/documentation/&gt;. For help, type &quot;help&quot;. Type &quot;apropos word&quot; to search for commands related to &quot;word&quot;... Reading symbols from Blink.ino.elf... (gdb) target extended-remote /dev/ttyACM1 Remote debugging using /dev/ttyACM1 (gdb) monitor jtag_scan Target voltage: 1.0V JTAG device scan failed! Failed (gdb) </code></pre> <p><a href="https://i.stack.imgur.com/EfOAb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EfOAb.jpg" alt="Photo of JTAG connection to Zero" /></a></p> <p>The same probe and setup successfully debugs an Arduino Due. Acknowledging different processors on the two boards.</p> <p>The JTAG connector is correctly oriented.</p> <p>Is a switching action needed to enable one debug path or the other, or is something else wrong?</p> <p><strong>Update 2023-04-01:</strong> I bought an SWD breakout board so I could get some test leads on without risking bent pins (it took a couple of weeks to arrive). The VREF pin on the Zero is 0V when running the debug version of Blink.ino. In comparison the same test rig connected to Due running debug Blink.ino VREF is 3.3V as expected.</p> <p>Tracing back the Zero JTAG VREF pin connection on the PCB, the connection is as expected compared to the <a href="https://docs.arduino.cc/hardware/zero" rel="nofollow noreferrer">published PCB Layout</a>. It connects to a pin on the Atmel EDBG chip (IC3). <a href="https://i.stack.imgur.com/0kObT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0kObT.png" alt="PCB Layout Snippet" /></a></p> <p>At J100 the schematic (snippet above) labels this connection VCC_P3V3. However it seems to connect to VCC_EDBG_P3V3.</p> <p>I'm going to spend some time with the <a href="http://ww1.microchip.com/downloads/en/devicedoc/atmel-42096-microcontrollers-embedded-debugger_user-guide.pdf" rel="nofollow noreferrer">Atmel EDBG User Guide</a></p> <p><strong>Update 2023-04-01 #2:</strong> During successful debugging using the USB EDBG to Arduino IDE method, the JTAG (J100) VREF pin remains at 0V.</p> <p><strong>Update 2023-04-01 #3:</strong> Refering to the <a href="https://mil.ufl.edu/4744/docs/XMEGA/EDBG_Embedded_Debugger_Datasheet.pdf" rel="nofollow noreferrer">EDBG datasheet</a> section 5. The pin on the EDBG chip (IC3) to which the JTAG Vref pin is connected is (K9) EDBG_TCK. Noting the orientation is inverted compared to the PCB image. <a href="https://i.stack.imgur.com/kjlxy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kjlxy.png" alt="EDBG VBGA Package Pinout" /></a> EDBG_TCK is described as &quot;JTAG Test Clock pin for EDBG device&quot;, and is in the EDBG manufacturing programming group of pins.</p> <p><strong>OK, it's clear to me now, that this isn't the JTAG I was looking for, I'll write it up as an answer.</strong></p>
<p>I believe the problem occured because I assumed that J100 on the schematic is the populated JTAG interface. Tracing through the schematics and PCB layout indicate that J100 on the schematic is CN2 on the PCB layout (the JTAG interface with no headers populated). J301 on the schematic is the JTAG interface with headers installed, called CN1 on the PCB layout <a href="https://i.stack.imgur.com/veBfQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/veBfQ.jpg" alt="Zero PCB Layout" /></a></p> <p>J301 (CN1) is for programming the EDBG chip. <a href="https://i.stack.imgur.com/ZiTdg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZiTdg.png" alt="J301 CN1 Schematic snippet" /></a></p> <p>J100 (CN2) breaks out JTAG target interface pins, but does not have header installed. <a href="https://i.stack.imgur.com/KhdcI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KhdcI.png" alt="J100 CN2" /></a></p> <p><a href="https://i.stack.imgur.com/KDSAn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KDSAn.jpg" alt="Arduino Zero Image" /></a></p> <p>Contrary to the schematic, looking at J100 (CN2) on the PCB laypout and also by visual inspection of the physical PCB VREF pin 1 does not seem to have any connection to +3V3.</p> <p>Top View: <a href="https://i.stack.imgur.com/158fD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/158fD.jpg" alt="J100 (CN2) VREF pin detail - top" /></a> Bottom View: <a href="https://i.stack.imgur.com/8gNZi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8gNZi.jpg" alt="J100 (CN2) VREF pin detail - bottom" /></a></p> <p>Counter to the microscope photo evidence, I do read 3.3V (using multimeter) on the square solder pad of the VREF pin, which matches the schematic. I'm having trouble explaining it though. This is a two layer PCB right?</p> <p><strong>Updated 2/4/2023: My conclusion is that the EDBG JTAG port is not useful with the Black Magic Probe as an alternative to EDBG. The J100 (CN2) port seems like it would be usable if it had headers.</strong></p>
92611
|esp32|
LVGL v8.2 on ESP32-S3 colour issue ILI9341 TFT LCD Arduino IDE
2023-03-17T17:33:46.903
<p>I have <a href="https://de.aliexpress.com/item/1005003943508410.html?spm=a2g0o.order_list.order_list_main.145.21ef5c5fPSOh1Q&amp;gatewayAdapt=glo2deu" rel="nofollow noreferrer">ILI9341 320x240px TFT LCD screen</a> which I am using with ESP32-S3-wroom-1 module.</p> <p>I have tested with TFT_eSPI and works fine, but when using LVGL, I am seeing weird artefacts on the edges. <a href="https://i.stack.imgur.com/3TBsv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3TBsv.jpg" alt="enter image description here" /></a></p> <p>I am using Arduino IDE</p> <p>Started off the sketch from</p> <p><a href="https://github.com/lvgl/lvgl/blob/master/examples/arduino/LVGL_Arduino/LVGL_Arduino.ino" rel="nofollow noreferrer">https://github.com/lvgl/lvgl/blob/master/examples/arduino/LVGL_Arduino/LVGL_Arduino.ino</a></p> <p>Havent changed sketch file much.</p> <p>I am using LVGL latest v8.2.0</p> <pre class="lang-c prettyprint-override"><code>/*==================== COLOR SETTINGS *====================*/ /*Color depth: 1 (1 byte per pixel), 8 (RGB332), 16 (RGB565), 32 (ARGB8888)*/ #define LV_COLOR_DEPTH 16 /*Swap the 2 bytes of RGB565 color. Useful if the display has an 8-bit interface (e.g. SPI)*/ #define LV_COLOR_16_SWAP 1 /*Enable features to draw on transparent background. *It's required if opa, and transform_* style properties are used. *Can be also used if the UI is above another layer, e.g. an OSD menu or video player.*/ #define LV_COLOR_SCREEN_TRANSP 1 /* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently. * 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */ #define LV_COLOR_MIX_ROUND_OFS 0 /*Images pixels with this color will not be drawn if they are chroma keyed)*/ #define LV_COLOR_CHROMA_KEY lv_color_hex(0x00ff00) /*pure green*/ </code></pre> <p><code>LV_COLOR_SCREEN_TRANSP 1</code> was originally 0 changing it did not change anything.</p> <p>I am following the FAQ which mentions</p> <blockquote> <p>1.6.7 Why I see nonsense colors on the screen? Probably LVGL's color format is not compatible with your displays color format. Check LV_COLOR_DEPTH in lv_conf.h. If you are using 16 bit colors with SPI (or other byte-oriented interface) probably you need to set LV_COLOR_16_SWAP 1 in lv_conf.h. It swaps the upper and lower bytes of the pixels.</p> </blockquote> <p>as you can see above in the config, the values are as recommended.</p> <p>Any help will be greatly appreciated.</p>
<p>Turns out, I had to disable <code>LV_COLOR_16_SWAP</code> I had been trying with different colour depths and everything else, I still cannot see gradients drawn properly, but the colours seem to be correct now.<a href="https://i.stack.imgur.com/i4Xff.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i4Xff.jpg" alt="enter image description here" /></a></p>
92650
|arduino-nano|
Have I ruined my Arduino Nano with my terrible soldering (technique and tools!)
2023-03-24T02:23:51.603
<p>So I bought a Arduino Nano and a <em>very</em> cheap soldering iron and solder from Alibaba. I was attempting to solder in some connections and failing pretty hard. A small resister popped off when trying to solder a wire to ground. I was pretty good when soldering in high school...but it's been a while since then.</p> <p>By just plugging it into my computer, I was able to upload a simple program which switches the LED on and off - and that still works.</p> <p>I'm not clearly not competent enough and I don't have a good enough soldering iron to do surface mount soldering to repair it. So I'm wondering if it'll still do what I want it to do.</p> <p>My overall aim is to build a <a href="https://blog.arduino.cc/2020/08/01/juuke-is-an-arduino-powered-rfid-music-player-for-the-elderly/" rel="nofollow noreferrer">simple music player</a> for my 3 year old.</p> <p>My question is, what does that resistor do? Have I ruined the board?</p> <p><a href="https://i.stack.imgur.com/jqjWY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jqjWY.jpg" alt="Arduino Nano with missing resistor" /></a></p>
<p>You haven't answered either of my questions in the comments (where is the component?, what colour is it?) but judging by the position I think it is on the board it is the 0.1 µF capacitor which is part of the reset circuitry. It is designed to briefly pull /RESET low on power-up, or when DTR is asserted.</p> <blockquote> <p>If I know what function doesn't work, then I know whether I can still do my project.</p> </blockquote> <p>Either the board works or it doesn't. There won't be &quot;some function&quot; that won't work. You may have problems resetting it but simply pressing the reset button on the other side (if there is one) should have the same effect.</p> <p>I suggest you get a better soldering iron with a smaller tip. Also practice soldering a bit. The wire you show in the photo should have a blob of solder around it, not going &quot;raw&quot; into the hole as you have it. I also don't see how you can somehow unsolder a capacitor which is a couple of millimetres away from the pins on the edge of the board. Definitely more practice required.</p> <p>A common technique with boards like the Nano is to solder a line of pins down each side like this:</p> <p><a href="https://i.stack.imgur.com/rLdBM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rLdBM.jpg" alt="Nano underneath" /></a></p> <p>Then plug the whole thing into a breadboard and wire up your project on the breadboard. Then you don't need to worry about your soldering technique so much (once you have soldered on the pins, and you can get a friend to help you).</p>
92666
|arduino-mega|c++|platformio|vscode|
Why is sensitivity (threshold) parameter ignored
2023-03-25T06:31:03.477
<p>Analog pontentiometer connected to an Arduino. simplest possible setup. The goal is to send a message over <code>Serial</code> whenever the value changes.</p> <p>I do not want to spam the Serial connection to much, so the value has to change by at least <code>20</code> (sensitivty threshold) before a message Packet is sent.</p> <p>However, in reality a message Packet is sent even if the value changed only by <code>1</code>. <strong>Why is sensitivity parameter ignored?</strong></p> <p><strong>edit:</strong> After debugging I can see that it enters the first IF-statement in <code>read()</code>. The IF statement evaluates to <code>0</code> which is super weird. It shouldn't have entered that IF statement!</p> <p><strong>MagicPot.h:</strong></p> <pre><code>#define MAGIC_POT_MAX_RAW_VALUE_10B 1023 #define MAGIC_POT_MAX_RAW_VALUE_12B 4095 #define MAX_RAW_VALUE_DEFAULT (MAGIC_POT_MAX_RAW_VALUE_10B) class MagicPot { public: typedef void (*callback_fn)(); MagicPot(uint8_t pin, uint16_t minRead = 0, uint16_t maxRead = MAX_RAW_VALUE_DEFAULT, uint16_t maxRawRead = MAX_RAW_VALUE_DEFAULT): pin(pin), minRead(minRead), maxRead(maxRead), maxRawRead(maxRawRead) {}; void begin(); bool read(uint8_t sensitivity = 5); uint16_t getValue(); uint16_t getRawValue(); uint8_t pin; private: uint16_t minRead; uint16_t maxRead; uint16_t maxRawRead; callback_fn onChangeCallback; uint16_t value; uint16_t rawValue; }; </code></pre> <p><strong>MagicPot.cpp:</strong></p> <pre><code>void MagicPot::begin() { this-&gt;onChangeCallback = nullptr; this-&gt;value = 0; this-&gt;rawValue = 0; pinMode(this-&gt;pin, INPUT); this-&gt;read(0); } bool MagicPot::read(uint8_t sensitivity) { this-&gt;rawValue = analogRead(this-&gt;pin); uint16_t value = map(this-&gt;rawValue, 0, this-&gt;maxRawRead, this-&gt;minRead, this-&gt;maxRead); if (abs(value - this-&gt;value) &gt; sensitivity) { this-&gt;value = value; return true; } else if (value &lt; sensitivity &amp;&amp; this-&gt;value != this-&gt;minRead) { this-&gt;value = minRead; return true; } else if (value + sensitivity &gt; maxRead &amp;&amp; this-&gt;value != this-&gt;maxRead) { this-&gt;value = this-&gt;maxRead; return true; } return false; } </code></pre> <p><strong>Arduino code:</strong></p> <pre><code>MagicPot analogPots[] = { MagicPot(A0), } void setup() { for (MagicPot&amp; x : analogPots) //arr only contains 1 element x.begin(); } void loop() { for (MagicPot&amp; pot : analogPots) //arr only contains 1 element { if(true == pot.read(20)) { CPPacket* analogPotChangedPacket = new CPPacket(HWEvent::Switch, pot.pin, pot.getValue()); SendPacket( &amp;myPacketSerial, analogPotChangedPacket); delete analogPotChangedPacket; } } } </code></pre> <p><strong>Actual Output: (read from computer(conn via Serial))</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Type</th> <th>Error</th> <th>Target</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>Switch</td> <td>NONE</td> <td>54</td> <td>516</td> </tr> <tr> <td>Switch</td> <td>NONE</td> <td>54</td> <td>515</td> </tr> <tr> <td>Switch</td> <td>NONE</td> <td>54</td> <td>514</td> </tr> <tr> <td>Switch</td> <td>NONE</td> <td>54</td> <td>513</td> </tr> </tbody> </table> </div> <p><strong>Expected Output:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Type</th> <th>Error</th> <th>Target</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>Switch</td> <td>NONE</td> <td>54</td> <td>516</td> </tr> <tr> <td>Switch</td> <td>NONE</td> <td>54</td> <td>496</td> </tr> <tr> <td>Switch</td> <td>NONE</td> <td>54</td> <td>456</td> </tr> <tr> <td>Switch</td> <td>NONE</td> <td>54</td> <td>436</td> </tr> </tbody> </table> </div>
<p>Consider this subtraction:</p> <pre class="lang-cpp prettyprint-override"><code>value - this-&gt;value </code></pre> <p>Like in any arithmetic operation, the operands undergo <a href="https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion" rel="nofollow noreferrer">integral promotion</a>, then <a href="https://en.cppreference.com/w/cpp/language/usual_arithmetic_conversions" rel="nofollow noreferrer">usual arithmetic conversions</a>. Oversimplifying a bit, “integral promotion” means that types smaller than <code>int</code> get promoted to <code>int</code>, whereas “usual arithmetic conversions” mean the smaller operand gets promoted to the type of the bigger one. If both types have the same size, the unsigned one wins.</p> <p>On the Arduino Mega, and <code>int</code> is 16 bits. Since the operands of the subtraction are both <code>uint16_t</code>, the types are not changed by these implicit conversions. The subtraction is performed with the <code>uint16_t</code> type and wraps around modulo 2<sup>16</sup>. If you expect −1, you get 65535.</p> <p>If you cast one of the operands to <code>int16_t</code>, then it will be implicitly converted back to <code>uint16_t</code> by the usual arithmetic conversions, and you get the same result.</p> <p>On your PC, an <code>int</code> is 32 bits, thus both operands get implicitly converted to <code>int</code> by integral promotion, and you get the expected signed result.</p> <p>The simple solution to your problem is to turn all your variables to <code>int16_t</code>. I suggest you always use signed types by default, and revert to unsigned types when you do need the wraparound semantics of the arithmetic operations (<a href="https://arduino.stackexchange.com/a/12588/7508">it is useful</a> sometimes).</p>
92680
|arduino-ide|c++|
How to return a value from a non integer input between 0-5 from an output range of 0-320 in map() method
2023-03-26T20:28:27.100
<p>I am experimenting using the map() method in an ArduinoIDE sketch in an attempt to obtain a pixel position for a horizontal meter in the range 0-320 from an input value in the range 0-5. However, when I do this I see in the method that the input must be 'long' type. Here's my example code:</p> <pre><code> float voltage = 2.5; float meterPosition = map(voltage, 0, 5, 0, 320); tft.fillRect(0, 0, meterPosition, 10, TFT_GREEN); tft.setCursor(10, 70); tft.setTextSize(3); tft.println(voltage); tft.println(meterPosition); </code></pre> <p>But when I run this, despite the input value being 50% of the input range, I expected the meterPosition value to be 160, but it is 128, due I think because the values for this method must be of type 'long' and so the 'float' value is rounded and becomes a 'long' type (I think that's what is happening!!).</p> <p>I am confused as to the function of the map() method if you are unable to map any range to any other range without using decimals as the input. I am obviously missing something here, so what do I need to change in my map() method code for it to work in my example please, if I am unable to use floats?</p> <p>Thanks. John</p>
<p>As you already noticed, the <code>map()</code> function is meant to work with the <code>long</code> data type. Here is <a href="https://github.com/arduino/ArduinoCore-API/blob/1.4.0/api/Common.cpp" rel="nofollow noreferrer">its implementation</a>:</p> <pre class="lang-cpp prettyprint-override"><code>long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } </code></pre> <p>If you want to use floats, you could write a version of this function that works with floats. Note, however, that since you are using zeros for both <code>in_min</code> and <code>out_min</code>, the expression simplifies itself to the point of becoming trivial:</p> <pre class="lang-cpp prettyprint-override"><code>float meterPosition = voltage * 320 / 5.0; </code></pre> <p>I would suggest two small changes to this expression though:</p> <ul> <li><p>add parentheses around <code>(320 / 5.0)</code>: this ratio will then be evaluated at compile-time and you will save an expensive run-time floating-point division</p> </li> <li><p>round to the nearest integer in order to minimize the error: your pixel position will have to be an integer anyway.</p> </li> </ul> <p>With these suggestions, we have:</p> <pre class="lang-cpp prettyprint-override"><code>int meterPosition = round(voltage * (320 / 5.0)); </code></pre> <p>Do not forget the <code>.0</code> in <code>5.0</code>, otherwise you would get an integer division.</p> <p>Note that using <code>map()</code> with ranges scaled by a factor 100 is not a terribly good idea: you will waste quite a lot of CPU cycles doing useless computations, and the result will be polluted by two rounding errors instead of one.</p>
92682
|arduino-uno|shift-register|7-segment|
Arduino uno - 4digit 7seg display via 74HC595 keeps blinking
2023-03-26T23:24:23.483
<p>I am trying to get my 4 digit display (SH5461AS) count from 0 to 9 based on millis() function.</p> <p>The problem is that it keeps blinking. Even if I display just one number, it shows then it goes black then it shows again, instead of staying on.. Also the upper segment (A) is somewhat delayed. Sometimes it shows, sometimes it does not. I am really not sure what is going on. It is best illustrated in the video: <a href="https://youtube.com/shorts/gmbNnvEYq2I" rel="nofollow noreferrer">https://youtube.com/shorts/gmbNnvEYq2I</a></p> <p>I have arduino UNO R3 hooked up to the 74HC595 8-bit register and from there to the corresponding 'data' pins on the display. It is a common cathode type so I have all of those connected via resistor to the ground.</p> <p><a href="https://i.stack.imgur.com/DEvoT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DEvoT.jpg" alt="enter image description here" /></a></p> <p>I appologize for the messy cabeling:</p> <p>From the display basically all resistors go to ground and all data cables to the register (Q0-DP omitted, segment A-Q7, B-Q6, .., G-Q1 [decimal number 1=A, 2=B, 3=AB,..]).</p> <p>In the register I got VCC, Ground, data cables, EO grounded, serial data-&gt;arduino D4, storage clock -&gt; D5, shift clock -&gt; D6</p> <pre><code> #include &lt;LiquidCrystal.h&gt; //LCD const int rs = 7, en = 8, d4 = 9, d5 = 10, d6 = 11, d7 = 12; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); //7SEG DISPLAY int LATCH = 5; int CLOCK = 6; int SERIALPIN = 4; const byte numbers[] = { 0b111111, 0b0000110, 0b1011011, 0b1001111, 0b1100110, 0b1101101, 0b1111101, 0b0000111, 0b1111111, 0b1101111 }; //OTHER void setup() { //LCD lcd.begin(16, 2); lcd.print(&quot;Test!&quot;); //7SEG pinMode(SERIALPIN, OUTPUT); pinMode(CLOCK, OUTPUT); pinMode(LATCH, OUTPUT); //OTHER pinMode(13, OUTPUT); // turn off onboard diode Serial.begin(9600); } void loop() { countSeconds(); delay(1000); } void countSeconds(){ digitalWrite(LATCH, LOW); // int number = (millis()/1000%10); // Serial.println(number); shiftOut(SERIALPIN, CLOCK, LSBFIRST, numbers[0]); //for demonstration purposes display 0 digitalWrite(LATCH, HIGH); } </code></pre> <p>Any ideas what's wrong?</p>
<p>As @Mat pointed out, the reset pin on the shift register was not connected. I didn't realize I need to anchor it high. Solved all problems, I guess it was resetting unpredictably..</p>
92693
|programming|variables|
how to "skip" one parameter of a method with a default value letting it use it's default value, but change parameters after it
2023-03-27T20:07:26.127
<p><strong>lets say we have a function like this(fictional):</strong></p> <pre><code>function1(int Z, int X, bool Y=true, int Count=10, int ID=1,bool TeaTime=false); </code></pre> <p>And I want to run this function, but I want to change all parameters, except for &quot;Count&quot;, and I want that to keep using it's default value.</p> <p><strong>Disclaimer</strong> in this fictional case and in the real case where I faced it I found the default value in the header file and I manually coded it in. but I do not want that, at least not to rely on it, for example if the default value changes in the library then in my code it would still be forced to use that old value. also for ease of use and reducing the chance at problems/mistakes.</p> <p><strong>What I tried:</strong> I already tried NULL and DEFAULT, both of them actually let my code work perfectly fine, but I made a test function which had such default values and printed the variables to the serial output and I found that using NULL actually overwrites it to 0 and DEFAULT overwrites it to 1.</p> <p>I also tried some things like keeping one empty and such but those would give compile faults.</p> <p><strong>in short:</strong></p> <p><strong>is there a way to let one parameter somewhere in the middle of the parameters of a function use it's default value while still manually setting the later ones?</strong></p>
<p>Most intuitive would be builder pattern with &quot;chaining&quot; ability (=returning reference to itself)</p> <p>Something like (computer version, in arduino remove main, iostream and cout):</p> <pre><code>#include &lt;iostream&gt; struct SomeParams { int X; int Z; bool Y = true; int count = 10; int ID = 1; bool teaTime = false; SomeParams(int x, int z) : X{x}, Z{z} {}; SomeParams &amp; noY() { Y=false; return *this; } SomeParams &amp; setCount(int c) { count = c; return *this; } SomeParams &amp; setId(int i) { ID = i; return *this; } SomeParams &amp; yesTeaTime() { teaTime = true; return *this; } }; void function(SomeParams const &amp; p) { std::cout &lt;&lt; &quot;X: &quot; &lt;&lt; p.X &lt;&lt; &quot; Y: &quot; &lt;&lt; p.Y &lt;&lt; &quot; Z: &quot; &lt;&lt; p.Z &lt;&lt; &quot; ID: &quot; &lt;&lt; p.ID &lt;&lt; &quot; count: &quot; &lt;&lt; p.count &lt;&lt; &quot; teaTime: &quot; &lt;&lt; p.teaTime &lt;&lt; &quot;\n&quot;; } int main() { function(SomeParams{45,68}.yesTeaTime().setId(154758).noY()); // without chaining: auto params = SomeParams{4457,5468}; params.setCount(4515); params.setId(15); function(params); } </code></pre>
92705
|arduino-uno|serial|softwareserial|
Incorrect data received on serial communication
2023-03-28T16:11:40.783
<p>I have two <strong>Arduino UNO</strong> connected with two wires, and ground, that exchange informations through <strong>serial data.</strong> The communication is working with INT, but I am having troubles to receive correct characters. Instead of characters I'm only receiving numbers.</p> <p>I tried every possible combination of <code>Serial.write()</code> or <code>Serial.println()</code>, with HEX and ascii, but it wouldn't work.</p> <p>I do not know what I am doing wrong, if anyone could help me, I will appreciate.</p> <p><strong>Transmitter :</strong></p> <pre><code>#include &lt;SoftwareSerial.h&gt; #define TX 2 #define RX 3 #define ask 3 #define ER_LED 12 String dataline = &quot;605030&quot;; const byte code = 60; SoftwareSerial syserial(RX, TX); // RX, TX void setup() { // put your setup code here, to run once: syserial.begin(57600); Serial.begin(57600); } void loop() { // put your main code here, to run repeatedly: //syserial.println(dataline); //NO //syserial.println(28, DEC); //ok for numbers Serial.println(dataline.length()); for (int i = 0; i &lt; dataline.length(); i++) { syserial.print((char)dataline[i]); } syserial.println(); //syserial.write(234); //syserial.print('&lt;'); delay(4000); } </code></pre> <p><strong>Receiver :</strong></p> <pre><code>#include &lt;SoftwareSerial.h&gt; #define TX 2 #define RX 3 const byte ask = 3; bool com_end; #define ER_LED 7 #define AC_LED 5 SoftwareSerial syserial(RX, TX); // RX, TX void setup() { // put your setup code here, to run once: syserial.begin(57600); Serial.begin(57600); } void loop() { // put your main code here, to run repeatedly: while (syserial.available()) { Serial.println(syserial.read()); } delay(100); } </code></pre> <p><strong>Serial monitor on whatev b/s:</strong></p> <pre><code>21:19:36.408 -&gt; 253 21:19:36.408 -&gt; 255 21:19:40.421 -&gt; 253 21:19:40.421 -&gt; 255 21:19:44.495 -&gt; 253 21:19:44.495 -&gt; 255 </code></pre> <p><strong>Monitor with <em>SySerial</em> on 57600 b/s:</strong></p> <pre><code>21:23:29.317 -&gt; 241 21:23:33.308 -&gt; 241 21:23:37.338 -&gt; 241 21:23:41.328 -&gt; 241 </code></pre> <p><strong>Monitor with <em>SySerial</em> on 300 b/s:</strong></p> <pre><code>21:27:03.444 -&gt; 255 21:27:07.731 -&gt; 255 21:27:12.095 -&gt; 255 21:27:16.335 -&gt; 255 21:27:20.635 -&gt; 255 </code></pre> <p><strong>Update :</strong></p> <p>I changed the pins on the UNO (TX -&gt;2)(RX -&gt; 3), and now i'm getting different numbers again. I must be doing something bad, but I can't understand what.</p>
<p><em>The communication is working with INT, but I am having troubles to receive correct characters. Instead of characters I'm only receiving numbers.</em></p> <p>Suggest you take a step back because you have code that has not been updated with what you have stated in subsequent comments and it is quickly becoming less clear what is going on.</p> <p>On each UNO Use pins 2,3 and GND. <strong>Don't connect anything else to either UNO.</strong></p> <p>UNO ONE pin <strong>2</strong> connects to UNO TWO pin <strong>3</strong></p> <p>UNO ONE pin <strong>3</strong> connects to UNO TWO pin <strong>2</strong></p> <p>UNO ONE GND to UNO TWO GND</p> <p>on UNO ONE run this code:</p> <pre><code>// RECEIVER #include &lt;SoftwareSerial.h&gt; SoftwareSerial SSerial(2,3); // RX, TX void setup() { Serial.begin(9600); // Arduino monitor hardware Serial SSerial.begin(9600); } void loop() { // display whatever comes in on the software serial to the Arduino monitor (the hardware serial) if (SSerial.available()) { Serial.write(SSerial.read()); } } </code></pre> <p>on UNO TWO run this code</p> <pre><code>// SENDER #include &lt;SoftwareSerial.h&gt; SoftwareSerial SSerial(2, 3); // RX, TX void setup() { SSerial.begin(9600); } void loop() { SSerial.println(&quot;Simple Arduino SoftwareSerial Test&quot;); delay(1000); } </code></pre> <p>Open the serial monitor on UNO ONE and you will see &quot;Simple Arduino SoftwareSerial Test&quot; printed every second.</p> <p>If you can't get that far, you have some other problem.</p> <p>Are you using two UNOs on two different computers? Are you using two UNOs on one computer, that is; running two instances of the IDE (may depend on OS - I do that all the time on Win 7 but I don't know about other OSs)?</p> <p>See if you can get this far first and I think it will be easier to get the rest fixed.</p>
92737
|esp32|ble|
ESP32 - BLE does not connect/restart after light sleep
2023-04-01T21:27:52.347
<p>noob in arduino here.</p> <p>I'm trying to connect via BLE after the ESP32 wakeups from light sleep. I have tried many different things, but none of them work. Everything works fine before the device sleeps the first time. Could you guys please give some ideas of what is wrong? the official docs are terrible.</p> <pre><code> btStop(); delay(1000); esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); Serial.println(&quot;Going to light sleep now&quot;); esp_light_sleep_start(); btStart(); </code></pre>
<p>I finally found the answer, you just need to advertise again the service after it sleeps. First you need to define this:</p> <pre><code>#if CONFIG_PM_ENABLE // Configure dynamic frequency scaling: // maximum and minimum frequencies are set in sdkconfig, // automatic light sleep is enabled if tickless idle support is enabled. // esp_pm_config_esp32c3_t pm_config = { // old version esp_pm_config_t pm_config = { .max_freq_mhz = 160, // e.g. 80, 160, .min_freq_mhz = 80, // 40 #if CONFIG_FREERTOS_USE_TICKLESS_IDLE .light_sleep_enable = true #endif }; ESP_ERROR_CHECK( esp_pm_configure(&amp;pm_config) ); #endif // CONFIG_PM_ENABLE </code></pre> <p>Then in your loop you could do something like:</p> <pre><code>esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); Serial.println(&quot;Going to light sleep now&quot;); esp_light_sleep_start(); Serial.println(&quot;depois do sleep start&quot;); BLEDevice::startAdvertising(); </code></pre>
92749
|esp8266|display|oled|
How to scroll text on an OLED display using only the SSD1306Wire library?
2023-04-02T21:28:37.353
<p>I'm a 13 years old boy and I am doing a project with esp01 and an OLED screen to display project ideas on the OLED with the ChatGPT API. The answer is displayed on the OLED but I would like it to scroll from bottom to top and so on to the next query so I can see the whole answer.I noted that the only library that worked for me for the esp01 was the SSD1306Wire library .My code is :</p> <pre><code>#include &lt;ESP8266HTTPClient.h&gt; #include &lt;ESP8266WiFi.h&gt; #include &lt;WiFiClientSecure.h&gt; #include &lt;Wire.h&gt; #include &lt;SSD1306Wire.h&gt; #include &lt;ArduinoJson.h&gt; const char* ssid = &quot;WIFI_NAME&quot;; const char* password = &quot;WIFI_PASSWORD&quot;; const char* apiEndpoint = &quot;https://api.openai.com/v1/engines/text-davinci-002/completions&quot;; const char* apiToken = &quot;OPENAI_TOKEN&quot;; SSD1306Wire display(0x3c, 2, 0); void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println(&quot;Connecting to WiFi...&quot;); } Serial.println(&quot;Connected to WiFi&quot;); display.init(); display.flipScreenVertically(); display.setFont(ArialMT_Plain_10); } void loop() { WiFiClientSecure client; client.setInsecure(); HTTPClient http; http.begin(client, apiEndpoint); http.addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;); http.addHeader(&quot;Authorization&quot;, &quot;Bearer &quot; + String(apiToken)); String payload = &quot;{\&quot;prompt\&quot;: \&quot;TEXT_TO_QUERY\&quot;,\&quot;temperature\&quot;:0.8,\&quot;max_tokens\&quot;:40}&quot;; int httpResponseCode = http.POST(payload); String response = &quot;&quot;; if (httpResponseCode == 200) { response = http.getString(); int startIndex = response.indexOf(&quot;text\&quot;:&quot;) + 7; int endIndex = response.indexOf(&quot;\&quot;,\&quot;index\&quot;&quot;); response = response.substring(startIndex, endIndex); response.replace(&quot;\\n&quot;, &quot;\n&quot;); Serial.println(response); } else { Serial.print(&quot;Error: &quot;); Serial.println(httpResponseCode); } http.end(); display.clear(); display.drawStringMaxWidth(0, 0, 128, response); display.display(); delay(18000000); } </code></pre> <p>Could anyone help me?</p>
<ul> <li>The SSD1306Wire code, its development history and discussions can be <a href="https://github.com/ThingPulse/esp8266-oled-ssd1306" rel="nofollow noreferrer">found here on github.com</a>.</li> <li>The Google search pattern &quot;scroll site:github.com/ThingPulse/esp8266-oled-ssd1306&quot; can be used to find all matches to &quot;scroll&quot; on these web pages. There appears to be interest in vertical scrolling by others but no support as of yet. There also appears to be some horizontal scrolling support or success as discussed <a href="https://github.com/ThingPulse/esp8266-oled-ssd1306/issues/160" rel="nofollow noreferrer">in this github.com issue for this project</a>.</li> <li>Also in that thread, there is <a href="https://github.com/androdlang/InfoTicker" rel="nofollow noreferrer">a link to another DSS1306 github.com project which explicitly states it supports horizontal scrolling</a>.</li> </ul>
92754
|esp32|wifi|
Issues getting WPS working on ESP32
2023-04-03T17:51:36.813
<p>I am trying to implement <a href="https://en.wikipedia.org/wiki/Wi-Fi_Protected_Setup" rel="nofollow noreferrer">WPS</a> on ESP32. <a href="http://www.wireless-tag.com/wp-content/uploads/2022/11/WT32-SC01-Plus-V1.3-EN.pdf" rel="nofollow noreferrer">A WT32-SC01 Plus</a> to be exact. It seems to working so far that I'll get the WPS connection but then it takes around 5 minutes [!!!] to get IP address from the router. Also when the WPS connection was successful, after a reboot it do not reconnect but expects a new WPS initialization.</p> <p>Can you take a look and tell me what am I doing wrong.</p> <p>Here is my code:</p> <pre><code>#include &quot;WiFi.h&quot; #include &quot;esp_wps.h&quot; #define ESP_MANUFACTURER &quot;ESPRESSIF&quot; #define ESP_MODEL_NUMBER &quot;ESP32&quot; #define ESP_MODEL_NAME &quot;ESPRESSIF IOT&quot; #define ESP_DEVICE_NAME &quot;ESP STATION&quot; struct WiFiHandler { bool connected = false; bool connecting = true; bool wpsDone = false; WiFiHandler() { WiFi.mode( WIFI_STA ); // WiFi.setAutoReconnect( false ); WiFi.onEvent( [ = ] ( WiFiEvent_t event, arduino_event_info_t info ) -&gt; void { switch( event ) { case ARDUINO_EVENT_WIFI_STA_START: Output::Message( &quot;Station Mode Started&quot; ); break; case ARDUINO_EVENT_WPS_ER_PIN: Output::Message( &quot;PIN: %d&quot;, info.wps_er_pin.pin_code ); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP: Output::StartUpMsg( &quot;Connected&quot; ); connected = true; connecting = false; break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: Output::Message( &quot;Reconnecting&quot; ); WiFi.reconnect(); break; case ARDUINO_EVENT_WPS_ER_SUCCESS: Output::StartUpMsg( &quot;WPS Successfull.&quot; ); WiFi.disconnect(); wpsStop(); WiFi.begin(); wpsDone = true; break; case ARDUINO_EVENT_WPS_ER_FAILED: Output::StartUpMsg( &quot;WPS Failed!&quot; ); connecting = false; break; case ARDUINO_EVENT_WPS_ER_TIMEOUT: Output::StartUpMsg( &quot;WPS Timedout!&quot; ); connecting = false; break; } } ); } bool initialise() { int cnt = 0; TaskHandle_t taskHandle = NULL; xTaskCreate( this-&gt;blink, &quot;WiFiConnect&quot;, 1000, this, 1, &amp;taskHandle ); Output::StartUpMsg( &quot;Establishing network connection ...&quot; ); if( String( WiFi.SSID().c_str() ).length() ) { WiFi.begin( WiFi.SSID().c_str(), WiFi.psk().c_str() ); while( ( WiFi.reconnect() != ESP_OK &amp;&amp; !this-&gt;connected ) &amp;&amp; ( ++cnt &lt; 20 ) ) { lv_bar_set_value( ui_BootProgress, lv_bar_get_value( ui_BootProgress ) + 1, LV_ANIM_ON ); delay( 100 ); } } if( !this-&gt;connected ) { WiFi.begin(); Output::StartUpMsg( &quot;Please initialise WPS connection on the router.&quot; ); cnt = 0; if( wpsInit() ) { if( esp_wifi_wps_start( 1000 ) != ESP_OK ) { Output::StartUpMsg( &quot;Can't start WPS&quot; ); } while( WiFi.status() != WL_CONNECTED ) { delay( 1000 ); if( WiFi.status() == WL_IDLE_STATUS &amp;&amp; wpsDone ) { WiFi.reconnect(); } // if( WiFi.status() == WL_CONNECTION_LOST &amp;&amp; wpsDone ) { // WiFi.disconnect(); // WiFi.begin( WiFi.SSID().c_str(), WiFi.psk().c_str() ); // } Output::Message( WiFi.SSID().c_str() ); Output::Message( WiFi.localIP().toString().c_str() ); Output::Message( String( WiFi.status() ).c_str() ); } delay( 2000 ); this-&gt;connected = true; } } if( this-&gt;connected ) { while ( !WiFi.SSID().length() ) { lv_bar_set_value( ui_BootProgress, lv_bar_get_value( ui_BootProgress ) + 1, LV_ANIM_ON ); delay( 100 ); } Output::StartUpMsg( &quot;Connected to: &quot; + WiFi.SSID() ); while ( !String( WiFi.localIP() ).length() || WiFi.localIP().toString() == &quot;0.0.0.0&quot; ) { lv_bar_set_value( ui_BootProgress, lv_bar_get_value( ui_BootProgress ) + 1, LV_ANIM_ON ); delay( 100 ); } Output::StartUpMsg( &quot;IP: &quot; + String( WiFi.localIP().toString() ) ); delay( 500 ); this-&gt;connecting = false; this-&gt;connected = true; } return this-&gt;connected; } String getIP() { return String( WiFi.localIP().toString() ); } String getPass() { return String( WiFi.psk().c_str() ); } String getNetworkName() { return String( WiFi.SSID() ); } String getMAC() { return String( WiFi.macAddress() ); } static void blink( void *pvParameter ) { WiFiHandler *l_pThis = ( WiFiHandler * ) pvParameter; for( int i = 0; l_pThis-&gt;connecting; i++ ) { i%2 ? lv_obj_add_flag( ui_WiFiStatus1, LV_OBJ_FLAG_HIDDEN ) : lv_obj_clear_flag( ui_WiFiStatus1, LV_OBJ_FLAG_HIDDEN ); delay( 250 ); } l_pThis-&gt;connected ? lv_obj_clear_flag( ui_WiFiStatus1, LV_OBJ_FLAG_HIDDEN ) : lv_obj_add_flag( ui_WiFiStatus1, LV_OBJ_FLAG_HIDDEN ); vTaskDelete( NULL ); } static bool wpsInit() { int cnt = 0; esp_wps_config_t config; config.wps_type = WPS_TYPE_PBC; strcpy( config.factory_info.manufacturer, ESP_MANUFACTURER ); strcpy( config.factory_info.model_number, ESP_MODEL_NUMBER ); strcpy( config.factory_info.model_name, ESP_MODEL_NAME ); strcpy( config.factory_info.device_name, ESP_DEVICE_NAME ); esp_err_t status = esp_wifi_wps_enable( &amp;config ); if( status != ESP_OK ) { Output::StartUpMsg( &quot;WPS config failed! &quot; + String( esp_err_to_name( status ) ) ); return false; } return true; } static void wpsStop() { if( esp_wifi_wps_disable() ) { Output::StartUpMsg( &quot;WPS Disable Failed&quot; ); } } }; </code></pre>
<p>Ok people, my router was apparently acting weird. It seems to works fine now!</p> <p>EDIT: Why the hell someone downvoted my answer? people are weird</p>
92787
|esp32|voltage|
Potential difference across the same wire
2023-04-05T21:02:18.163
<p>This issue may be weird, and I'm not sure if this is because of my wiring, but it would seem that <strong>I do not have the same voltage</strong> (or approximately the same voltage) between the <strong>VCC(3.3V)</strong> and the <strong>VCC power rail</strong> of my breadboard.</p> <p>When measuring the voltage, there is <strong>~0.300 mV</strong> difference. And indeed measuring VCC and GND gives me <strong>2.9 V</strong>, instead of <strong>3.3 V</strong></p> <ul> <li><p>I measured the flat jumper, it <strong>doesn't have any resistance</strong> (~~0)</p> </li> <li><p>The ESP is consuming <strong>below 100mA</strong>, so no voltage drop</p> </li> </ul> <p>Could anyone explain me that ? See attached pictures</p> <p><a href="https://i.stack.imgur.com/np6J3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/np6J3.jpg" alt="pin layout" /></a></p> <p><a href="https://i.stack.imgur.com/nUu2k.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nUu2k.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/PfON7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PfON7.jpg" alt="enter image description here" /></a></p>
<p>The only reasonable explanation is that the path between the 3.3V pin and the wire you are measuring does indeed have non-zero resistance. The wires look dirty to me from the photo, plus there would be internal resistance in the breadboard connectors.</p> <p>You are measuring from the 3.3V pin and not the other end of the wire. I suggest using a different wire, or cleaning that one with sandpaper or by filing it down until you see shiny copper. Also try a different pin on the breadboard.</p> <p>This is really a hardware or measurement issue. There is no way that a wire with zero resistance from one end to the other is going to have a 0.242V drop across it.</p>
92791
|arduino-nano|7-segment|
Arduino nano + 4x 7 segment display + 74HC595 - Only dot points are turn on
2023-04-07T06:13:24.890
<p>I am trying to run a thermometer with thermocouple sensor on Arduino Nano.</p> <p>I have bought 4x 7 segment display and 74HC595 chip. Everything is connected like in the attached diagram below (without DS18B20) <a href="https://i.stack.imgur.com/QJQH5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QJQH5.png" alt="schematic" /></a>, but when I uploaded sketch to Nano - only dots are turn on <a href="https://i.stack.imgur.com/JFXia.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JFXia.jpg" alt="dots" /></a>.</p> <p>Below You Can find my code</p> <pre class="lang-c prettyprint-override"><code>#include &lt;OneWire.h&gt; const int latchPin = 8; // Pin connected to ST_CP of 74HC595 const int clockPin = 9; // Pin connected to SH_CP of 74HC595 const int dataPin = 10; // Pin connected to DS of 74HC595 const int digitPins[4] = { 3, 4, 5, 6}; // pins to control the 4 common anode pins of display // seven segment digit bits + blank + minus const byte digit[12] = { B00111111, // 0 B00000110, // 1 B01011011, // 2 B01001111, // 3 B01100110, // 4 B01101101, // 5 B01111101, // 6 B00000111, // 7 B01111111, // 8 B01101111, // 9 B00000000, // Blank B01000000 //- }; int digitBuffer[4] = {1}; int digitScan = 0; int soft_scaler = 0; float tempC, tempF; int tmp; boolean sign = false; void setup() { TCCR2A = 0; TCCR2B = (1 &lt;&lt; CS21); TIMSK2 = (1 &lt;&lt; TOIE2); TCNT2 = 0; for (int i = 0; i &lt; 4; i++) pinMode(digitPins[i], OUTPUT); pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); } ISR(TIMER2_OVF_vect) { soft_scaler++; if (soft_scaler == 15) { refreshDisplay(); soft_scaler = 0; } }; void refreshDisplay() { for (byte k = 0; k &lt; 4; k++) digitalWrite(digitPins[k], LOW); digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, B11111111); digitalWrite(latchPin, HIGH); delayMicroseconds(50); digitalWrite(digitPins[digitScan], HIGH); digitalWrite(latchPin, LOW); if (digitScan == 1) { shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B10000000)); } else { shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[digitScan]]); } digitalWrite(latchPin, HIGH); digitScan++; if (digitScan &gt; 3) digitScan = 0; } void loop() { tempC = 90.8; tmp = int(tempC * 10); if (tempC &lt; 0) { sign = true; tmp = abs(tmp); } else { sign = false; } if (int(tmp) / 1000 == 0) { digitBuffer[3] = 10; if (sign) { digitBuffer[3] = 11; } } else { digitBuffer[3] = int(tmp) / 1000; } if (int(tmp) / 1000 == 0 &amp;&amp; (int(tmp) % 1000) / 100 == 0) { digitBuffer[2] = 10; if (sign) { digitBuffer[2] = 11; digitBuffer[3] = 10; } } else { digitBuffer[2] = (int(tmp) % 1000) / 100; } digitBuffer[1] = (int(tmp) % 100) / 10; digitBuffer[0] = (int(tmp) % 100) % 10; delay(500); } </code></pre> <p>I didn't connect thermocouple yet, but I use constant &quot;tempC&quot; with value = 90.8, to check if it works. If I change the value to higher - dots on displays are more dimmed.</p>
<p>The vendor description is not very good, however it is clear that 5 volts is not enough for these displays implying that you have to redesign the circuit to include a higher voltage power source. It does appear from the description, however, to be a common anode device. The screen shot from the data sheet shows each segment has 4 diodes in series and the DP has 2 diodes in series. That the DP lights with 5 volts indicates that the segments will light with 10 volts (possibly a bit less). Because it is common anode type you could use a TPIC6B595 shift register to replace the 74HC595. You need also 4 high side switches (each 1xPNP + 1xNPN transistor) for the 4 anodes. For this, you could also use a high side driver chip, say a MIC2981. Since the segment diode voltage drop is not shown, but should be in the range 2.1 to 4 volts, you really need to do a test to discover the optimum value of the segment current limiting resistors to give the 10mA talked about in the description, at the voltage you decide to drive the display at. The DP really requires a correspondingly higher value current limiting resistor.</p>
92795
|arduino-pro-mini|led-strip|
Motion-activated lights
2023-04-07T15:02:13.693
<p>I am attempting to follow <a href="https://speedysignals.com/2013/08/01/how-to-assemble-stair-lights/" rel="nofollow noreferrer">this tutorial</a> to light up a dark staircase with motion-activated LED strips. If my understanding of the tutorial is correct, essentially the Arduino's job is to power or depower transistors at the appropriate time to prohibit/allow enough voltage over the LED strips on the stairs.</p> <p>I have assembled a few light strips and soldered the microcontroller to the PCB with the appropriate components and was ready to test the device. The author of the guide helpfully created <a href="https://www.youtube.com/watch?v=Lc4w2SDPnmE&amp;embeds_euri=https%3A%2F%2Fspeedysignals.com%2F&amp;feature=emb_imp_woyt&amp;ab_channel=AndrewOng" rel="nofollow noreferrer">this video</a> demonstrating the expected behavior of the device on start-up: the lights should blink as shown and then turn off, awaiting activation from a motion sensor. However when I try to replicate this my lights simply turn on and never turn off, fade, or blink.</p> <p>Consulting the FAQ on the guide, I tried reorienting my transistors, thinking I perhaps had them backward. This had no effect.</p> <p>I then tried to verify that my microprocessor was working and programmed correctly. I modified the code in the setup section, adding the following commands:</p> <pre><code>pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); for(int i=0; i&lt;10; i++){ digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); delay(2000); } </code></pre> <p>The intention was to make the built-in LED on the board blink on and off a few times during startup. While the board was connected to the computer, it indeed blinked on and off after I hit upload. When it's attached to the power supply from the PCB it does not blink (though the LED lights for the stairs turn on as I have described).</p> <p>It seems to me that the microprocessor is simply not getting power or is not connected properly to the PCB. However I have done my best to verify all the connections and cannot find any problem. This is my first project of this type and am not sure what else to try. Any guidance with troubleshooting would be very much appreciated.</p> <p>I apologize for the long post but I wanted to be sure to include all the necessary information. Thank you for reading!</p> <p>Below are images of the PCB and schematics from the guide, which hopefully correspond to how I've actually connected the components.</p> <p><a href="https://i.stack.imgur.com/SBMoS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SBMoS.png" alt="PCB diagram" /></a></p> <p><a href="https://i.stack.imgur.com/BJEUY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BJEUY.png" alt="PCB Schematic" /></a></p> <p><a href="https://i.stack.imgur.com/FkBuT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FkBuT.jpg" alt="My Device" /></a></p> <p>Here is the code from the guide plus my blinking loop. The original is available at the <a href="https://github.com/androng/Shift-stairs" rel="nofollow noreferrer">author's github</a>.</p> <pre><code>##Shift_Stairs.ino #include &lt;math.h&gt; #include &lt;SPI.h&gt; //#include &lt;MemoryFree.h&gt; //#include &quot;expoDutyCycles.h&quot; //Data pin is MOSI (atmega168/328: pin 11. Mega: 51) //Clock pin is SCK (atmega168/328: pin 13. Mega: 52) const int ShiftPWM_latchPin=10; const bool ShiftPWM_invertOutputs = 0; // if invertOutputs is 1, outputs will be active low. Usefull for common anode RGB led's. #include &lt;ShiftPWM.h&gt; // include ShiftPWM.h after setting the pins! const int SWITCH_PIN = A0; const int PHOTORESISTOR_PIN = A2; const int MOTION_SENSOR_TOP_PIN = 2; const int MOTION_SENSOR_BOTTOM_PIN = 3; const unsigned char maxBrightness = 255; const unsigned char pwmFrequency = 75; const int numRegisters = 2; const int NUMLEDs = 9; const int MOTION_SENSOR_WARMUP_TIME = 10; const int ON_TIME = 10000; /* The duration between turn on and turn off. */ const int LIGHT_THRESHOLD = 300; /* Anything below this sensor value will enable lights */ /* These are used to detect rising edges in the absence of interrupts. Using interrupts with ShiftPWM crashes the program. */ unsigned char lastReadTopPin = LOW; unsigned char lastReadBotPin = LOW; volatile unsigned char topActivated = false; volatile unsigned char bottomActivated = false; unsigned long lastMotionTime = 0; const char BOTTOM_TO_TOP = 1; const char TOP_TO_BOTTOM = 2; /* For sake of the animation, stores the direction of propegation. Set when animation is active, cleared when animation is done. */ char directionTriggered = 0; const unsigned long BRIGHTNESS_SM_PERIOD = 2000; /* in μs */ unsigned long lastBrightnessSM = 0; /* LED 0 is on the top of stairs */ unsigned char brightnesses[NUMLEDs] = {0}; void setup() { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); for(int i=0; i&lt;10; i++){ digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); delay(2000); } pinMode(ShiftPWM_latchPin, OUTPUT); SPI.setBitOrder(LSBFIRST); // SPI_CLOCK_DIV2 is only a tiny bit faster in sending out the last byte. // SPI transfer and calculations overlap for the other bytes. SPI.setClockDivider(SPI_CLOCK_DIV4); SPI.begin(); Serial.begin(9600); /* Turn on pullup resistor for switch */ digitalWrite(SWITCH_PIN, HIGH); ShiftPWM.SetAmountOfRegisters(numRegisters); ShiftPWM.Start(pwmFrequency,maxBrightness); // Print information about the interrupt frequency, duration and load on your program ShiftPWM.SetAll(0); ShiftPWM.PrintInterruptLoad(); // Fade in all outputs for(int j=0;j&lt;maxBrightness;j++){ ShiftPWM.SetAll(j); delay(3); } // Fade out all outputs for(int j=maxBrightness;j&gt;=0;j--){ ShiftPWM.SetAll(j); delay(3); } } void loop() { /* Detect rising edge with polling. Interrupts crash the program. */ unsigned char pinRead = digitalRead(MOTION_SENSOR_TOP_PIN); if(pinRead == HIGH &amp;&amp; lastReadTopPin == LOW){ topActivated = true; } lastReadTopPin = pinRead; /* Detect rising edge with polling. Interrupts crash the program. */ pinRead = digitalRead(MOTION_SENSOR_BOTTOM_PIN); if(pinRead == HIGH &amp;&amp; lastReadBotPin == LOW){ bottomActivated = true; } lastReadBotPin = pinRead; /* Resets flags */ if(topActivated){ if(directionTriggered == 0){ directionTriggered = TOP_TO_BOTTOM; } lastMotionTime = millis(); topActivated = false; } if(bottomActivated){ if(directionTriggered == 0){ directionTriggered = BOTTOM_TO_TOP; } lastMotionTime = millis(); bottomActivated = false; } /* State machine */ if(micros() - lastBrightnessSM &gt; BRIGHTNESS_SM_PERIOD){ brightnessSM(); lastBrightnessSM = micros(); } } /** Returns true if switch is in &quot;1&quot; position. */ boolean switchPressed(){ return !digitalRead(SWITCH_PIN); } </code></pre> <pre><code>###brightnessSM.ino enum brightnessStates { sFullyOn, sOff, sTurningOn, sTurningOff, sOverrideSwitch }; int brightnessState = sOff; void brightnessSM(){ /* Actions */ switch(brightnessState){ case sFullyOn: break; case sOff: break; case sTurningOn:{ /* Increase brightness of lights. This for loop goes from -NUMLEDs to 0 or 0 to NUMLEDs depending on the direction of propegration. */ char startLight = -1 * (directionTriggered - 1) * (NUMLEDs - 1); char endLight = -1 * (directionTriggered - 2) * (NUMLEDs - 1); for(char l = startLight; l &lt;= endLight; l++){ /* Turn on the next LED only if the ones before it are on*/ if(brightnesses[abs(l)] != maxBrightness){ brightnesses[abs(l)] += 5; ShiftPWM.SetOne(abs(l), brightnesses[abs(l)]); break; } /* Turn on the next LED only if the one before it is partially on */ // if(brightnesses[abs(l)] != maxBrightness){ // if(l == startLight || (brightnesses[abs(l - 1)] &gt; maxBrightness*3/10)){ // brightnesses[abs(l)] += 1; // ShiftPWM.SetOne(abs(l), expoDutyCycles[brightnesses[abs(l)]]); // } // } } break; } case sTurningOff:{ /* Decrease brightness of lights. This for loop goes from -NUMLEDs to 0 or 0 to NUMLEDs depending on the direction of propegration. */ char startLight = -1 * (directionTriggered - 1) * (NUMLEDs - 1); char endLight = -1 * (directionTriggered - 2) * (NUMLEDs - 1); for(char l = startLight; l &lt;= endLight; l++){ /* Turn on the next LED only if the ones before it are on*/ if(brightnesses[abs(l)] != 0){ brightnesses[abs(l)] -= 5; ShiftPWM.SetOne(abs(l), brightnesses[abs(l)]); break; } /* Turn on the next LED only if the one before it is partially on */ // if(brightnesses[abs(l)] != 0){ // if(l == startLight || (brightnesses[abs(l - 1)] &lt; maxBrightness*9/10)){ // brightnesses[abs(l)] -= 1; // ShiftPWM.SetOne(abs(l), expoDutyCycles[brightnesses[abs(l)]]); // } // } } break; } case sOverrideSwitch: break; } /* Transitions */ switch(brightnessState){ case sFullyOn: if(millis() - lastMotionTime &gt; ON_TIME){ brightnessState = sTurningOff; } if(switchPressed()){ transitionToOverrideSwitch(); } break; case sOff: if(directionTriggered != 0){ if(analogRead(PHOTORESISTOR_PIN) &lt; LIGHT_THRESHOLD){ brightnessState = sTurningOn; } else { directionTriggered = 0; } } if(switchPressed()){ transitionToOverrideSwitch(); } break; case sTurningOn:{ /* If all the lights are on then proceed */ unsigned char allOn = true; for(unsigned char l = 0; l &lt; NUMLEDs; l++){ if(brightnesses[l] != maxBrightness){ allOn = false; break; } } if(allOn){ brightnessState = sFullyOn; } if(switchPressed()){ transitionToOverrideSwitch(); } break; } case sTurningOff:{ /* If all the lights are off then proceed */ unsigned char allOff = true; for(unsigned char l = 0; l &lt; NUMLEDs; l++){ if(brightnesses[l] != 0){ allOff = false; break; } } if(allOff){ directionTriggered = 0; brightnessState = sOff; } if(switchPressed()){ transitionToOverrideSwitch(); } break; } case sOverrideSwitch: if(switchPressed() == false){ /* Switch all LEDs off */ for(char l = 0; l &lt; NUMLEDs; l++){ ShiftPWM.SetOne(l, 0); brightnesses[l] = 0; } directionTriggered = 0; brightnessState = sOff; } break; } } void transitionToOverrideSwitch(){ brightnessState = sOverrideSwitch; /* Switch all LEDs on */ for(unsigned char l = 0; l &lt; NUMLEDs; l++){ ShiftPWM.SetOne(l, maxBrightness); brightnesses[l] = maxBrightness; } } </code></pre>
<p>The image of the Printed Circuit Board (PCB) posted in the above question contains many examples of what are commonly referred to as <a href="https://www.pcbdirectory.com/community/what-is-a-cold-solder-joint" rel="nofollow noreferrer">Cold Solder Joints</a>. These types of joints are unreliable and occasionally provide no electrical connectivity. And are often impossible to visually verify. The <a href="https://www.youtube.com/watch?v=VLubdi6aC3g" rel="nofollow noreferrer">first 2 minutes of this video</a> demonstrate how heat and flux can be combined to remedy cold solder joints involving a PCB and feed-through pin.</p> <p><em>(I can edit/change the following as we narrow in on the solution for this problem. The objective is to make a good stackexchange question &amp; answer.)</em></p> <p>Symptom:</p> <ul> <li>The project behaves as expected when cabled to the PC. This assumes the cable to the PC (likely to a USB/CDC to Serial Port) contains Ground, In, Out and Power. The expected behavior is to turn the LEDs on and off.</li> <li>The project does not work when disconnected from the PC and is powered by an external power supply. The LEDs only turn on.</li> </ul> <p>Consider verifying power to the processor or, better, at the processor. For the problem as described in the question, there may be an interruption of the power path from the external power supply to the processor. Check all the solder joints involved in connecting the Arduino's power input to the PCB. Likely the processor (Arduino) was powered up during programming through the Ground and Power pins of the serial port cable. Once that cable was removed, the processor may not be powered and may have not been running while the PCB was only powered from an external source.</p>
92819
|interrupt|code-optimization|timing|performance|
best practice for performance: empty loop() when using interrupt?
2023-04-10T14:21:31.553
<p>I'm working on a little midi hardware project and I'm using <code>attachInterrupt()</code> to assign a callback function to an interrupt pin.</p> <p>Nothing gets done in the loop function, so it looks like this:</p> <pre><code>void loop() { return; } </code></pre> <p>So far this seems to work out, but I'm wondering if this is a bad practice? I tried adding a short delay() call in there instead but I couldn't really measure if it performed better or worse.</p>
<p>There is no particular reason to worry about doing nothing in <code>loop</code> - the processor has to be doing <em>something</em> - you don't need to give it extra work.</p> <p>Plus, there is an implied <code>return</code> at the end of functions, you don't need to add your own.</p> <p>The bigger issue is that interrupt handlers should be short, so that you don't miss another interrupt while you are doing something lengthy in the first interrupt.</p>
92824
|communication|uart|feather|arduino-nano-33-iot|
Troubleshooting UART communication between nano 33 ble sense r2 and Adafruit Feather 32u4 with LoRa Radio Module
2023-04-11T01:12:24.057
<p>I've tried connecting the gnd's for both the boards and have connected rx to tx and vice versa in both the boards. I've powered both by batteries, and I'm trying to get sensor data from the nano, and trying to send it to the feather via UART, and long distance away using the Lora capabilities of the Feather.</p> <p>I've loaded this program in the nano:</p> <pre class="lang-cpp prettyprint-override"><code>/* Including libraries */ //Accelerometer{ #include &quot;Arduino_BMI270_BMM150.h&quot; //Accelerometer} //Temperature and humidity{ #include &lt;Arduino_HS300x.h&gt; //Temperature and humidity} //Pressure{ #include &lt;Arduino_LPS22HB.h&gt; //Pressure} /* Creating variables for sensors */ //Acceleration variables{ float x, y, z; //Acceleration variables} //Temperature and humidity variables{ float temperature; float humidity; //Temperature and humidity variables} //Pressure variables{ float pressure; //Pressure variables} void setup() { /* Setting up sensors */ Serial1.begin(9600); //Accelerometer{ if (!IMU.begin()) { Serial1.println(&quot;Failed to initialize IMU!&quot;); int i = 0; Serial1.println(&quot;Trying again\n&quot;); while (!IMU.begin()){ if(i&gt;0){ Serial1.print(&quot; Failed\n&quot;); } Serial1.print(&quot;Try number &quot;); Serial1.print(i); i++; delay(1000); } Serial1.print(&quot;Passed\nOn attempt number &quot;); Serial1.print(i); Serial1.print(&quot;\n&quot;); } //Accelerometer} //Temperature and humidity{ if (!HS300x.begin()) { Serial1.println(&quot;Failed to initialize humidity temperature sensor!&quot;); int i = 0; Serial1.println(&quot;Trying again\n&quot;); while (!HS300x.begin()){ if(i&gt;0){ Serial1.print(&quot; Failed\n&quot;); } Serial1.print(&quot;Try number &quot;); Serial1.print(i); i++; delay(1000); } Serial1.print(&quot;Passed\nOn attempt number &quot;); Serial1.print(i); Serial1.print(&quot;\n&quot;); } //Temperature and humidity} //Pressure{ if (!BARO.begin()) { Serial1.println(&quot;Failed to initialize pressure sensor!&quot;); int i = 0; Serial1.println(&quot;Trying again\n&quot;); while (!BARO.begin()){ if(i&gt;0){ Serial1.print(&quot; Failed\n&quot;); } Serial1.print(&quot;Try number &quot;); Serial1.print(i); i++; delay(1000); } Serial1.print(&quot;Passed\nOn attempt number &quot;); Serial1.print(i); Serial1.print(&quot;\n&quot;); } //Pressure} } void loop() { /* Read sensor data into the variables */ //Read acceleration{ if (IMU.accelerationAvailable()) { IMU.readAcceleration(x, y, z); } //Read acceleration} //Read temperature and humidity{ temperature = HS300x.readTemperature(); humidity = HS300x.readHumidity(); //Read temperature and humidity} //Read pressure{ pressure = BARO.readPressure(); //Read pressure} /* Print the sensor data to Serial1 (hopefully implement sending this data to the lora feather, which will radio it to a distant arduino) */ Serial1.print(&quot;\nAcceleration (x, y, z): &quot;); Serial1.print(x); Serial1.print(&quot;, &quot;); Serial1.print(y); Serial1.print(&quot;, &quot;); Serial1.print(z); Serial1.print(&quot;\nTemperature: &quot;); Serial1.print(humidity); Serial1.print(&quot;\nHumidity: &quot;); Serial1.print(humidity); Serial1.print(&quot;\nPressure: &quot;); Serial1.print(pressure); delay(1000); } </code></pre> <p>I've loaded this program in the transmitting feather:</p> <pre class="lang-cpp prettyprint-override"><code>/* The program for the feather1 to take information from nano 33 ble sense rev2 and radio it to where the feather2 ** will communicate to the ground station's program todisplay the data in a user friendly manner, and will display results */ #include &lt;RH_RF95.h&gt; // LoRa settings #define RFM95_CS 8 #define RFM95_RST 4 #define RFM95_INT 7 #define RFM95_FREQ 915.0 RH_RF95 rf95(RFM95_CS, RFM95_INT); void setup() { Serial.begin(9600); pinMode(RFM95_RST, OUTPUT); digitalWrite(RFM95_RST, HIGH); delay(100); digitalWrite(RFM95_RST, LOW); delay(10); digitalWrite(RFM95_RST, HIGH); delay(10); if (!rf95.init()) { Serial.println(&quot;LoRa init failed. Check your connections.&quot;); while (1) ; } rf95.setFrequency(RFM95_FREQ); rf95.setTxPower(23, false); Serial.println(&quot;LoRa Transmitter Ready!&quot;); } void loop() { static uint16_t messageCount = 0; String input; while (Serial.available() &gt; 0) { char c = Serial.read(); input += c; } if (input.length() &gt; 0) { uint8_t buf[RH_RF95_MAX_MESSAGE_LEN]; input.getBytes(buf, input.length() + 1); rf95.send(buf, input.length() + 1); rf95.waitPacketSent(); Serial.println(&quot;Sent message #&quot; + String(messageCount) + &quot;: &quot; + input); messageCount++; } delay(1000); } </code></pre> <p>I've got this program in the receiving feather:</p> <pre class="lang-cpp prettyprint-override"><code>/* The program for the feather2 to recieve information from feather1 ** and will communicate to the ground station's program todisplay the data in a user friendly manner, and will display results */ #include &lt;RH_RF95.h&gt; // LoRa settings #define RFM95_CS 8 #define RFM95_RST 4 #define RFM95_INT 7 #define RFM95_FREQ 915.0 RH_RF95 rf95(RFM95_CS, RFM95_INT); void setup() { Serial.begin(9600); while (!Serial) ; // Wait for serial port to be available /* The infinite while loop above not needed if you're not using rx/tx for sending ** the recieved radio data to your program or are using some other method to */ pinMode(RFM95_RST, OUTPUT); digitalWrite(RFM95_RST, HIGH); delay(100); digitalWrite(RFM95_RST, LOW); delay(10); digitalWrite(RFM95_RST, HIGH); delay(10); if (!rf95.init()) { Serial.println(&quot;LoRa init failed. Check your connections.&quot;); while (1) ; } rf95.setFrequency(RFM95_FREQ); rf95.setTxPower(23, false); Serial.println(&quot;LoRa Receiver Ready!&quot;); } void loop() { if (rf95.available()) { uint8_t buf[RH_RF95_MAX_MESSAGE_LEN]; uint8_t len = sizeof(buf); if (rf95.recv(buf, &amp;len)) { Serial.print(&quot;Received: &quot;); Serial.println((char*)buf); } else { Serial.println(&quot;LoRa receive failed&quot;); } } } </code></pre> <p>I have been able to establish UART communication between two Unos before, but I'm unable to find out why it isn't working in this case. I can confirm it isn't working because the Serial monitor for the recieving feather (feather2) only shows this:</p> <pre><code>17:52:39.840 -&gt; LoRa Receiver Ready! </code></pre> <p>Why this is happening, and any potential fixes for this?</p>
<p>As I see 32U4 I'd expect the Serial is used for native USB serial (CDC). If you want to use usart on pins 0 and 1, you'd have to use Serial1 instead.</p> <p>Nano 33 BLE is the same, it has native USB and you are correctly using Serial1 for accessing serial pins 0 and 1 (however nRF52840 can use any pins).</p>
92869
|pwm|audio|
tone() corrupts the PWM on a different pin
2023-04-15T22:34:48.597
<p>I have to use PWM to control some lights. I do this successfully with: <code>analogWrite(11, 127);</code> for a 50% PWM pulse on <code>pin 11</code>.</p> <p>Now, i also have to have <code>tone()</code> support on my code. When I do: <code>tone(10, melodyArray[thisNote], noteDuration);</code> I invoke the <code>tone()</code> function on <code>pin 10</code>.</p> <p>When I do so, then PWM pulse is corrupted. Since I do not have an oscilloscope, I cannot exactly understand what happens. But from the effects on the lights, I can speculate that the PWM pin (<code>pin 11</code>) is always <code>HIGH</code> or always <code>LOW</code>.</p> <p>It is obvious that the PWM pin and the <code>tone()</code> pin are different.</p> <p>Why does this happen? Perhaps the <code>tone()</code> uses some timers that interfere with the PWM? When I comment out the <code>tone()</code> line, the PWM works as intended.</p> <p>Is there a solution to this? Can I use the tone() function and still have <code>PWM</code> support (on another pin)?</p>
<p>To quote from the <a href="https://reference.arduino.cc/reference/en/language/functions/advanced-io/tone/" rel="nofollow noreferrer">Arduino documentation</a> of <code>tone()</code>:</p> <blockquote> <p>Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).</p> </blockquote> <p>So yes, you should use a different pin than 3 or 11 for <code>analogWrite()</code>. This is because <code>tone()</code> will configure the hardware Timer2 for outputting these timed signals via hardware. PWM on these pins is also tied to Timer2. When both functions are trying to configure Timer2 in a different way, there will be conflicts.</p> <p>Note: The documentation talks about &quot;boards other than the Mega&quot;, which was true when there weren't other Arduino boards than the old Uno/Nano/Mini (based on the Atmega328p). Nowadays there are so much boards, which all can be programmed with the Arduino framework, that this sentence is a real stretch. Instead I would say &quot;on boards based on the Atmega328p&quot;. Depending on your used board your mileage may very. Check the microcontrollers datasheet for the hardware Timers it has and their connected pins.</p>
92870
|esp32|adc|signal-processing|
If I reduce ADC sample rate, do I get an average over the time period?
2023-04-15T23:45:56.367
<p>I am working with a ESP32-C3 devkit. I am using the internal ADC on that chip to read from an analog microphone. I initialize the ADC like this:</p> <pre><code>adc_continuous_config_t dig_cfg = { .sample_freq_hz = 20000, // ... }; ESP_ERROR_CHECK(adc_continuous_config(handle, &amp;dig_cfg)); </code></pre> <p>If I reduce the sample frequency to, say 1000 Hz, then will each sample represent, roughly, an average of 20 samples from my previous stream (where the sample frequency was 20,000 Hz)? Or is it more like I will get just one out of every 20 samples from the original stream?</p> <p>The reason I ask is that I'm hoping to perform a kind of low-pass filter by changing the ADC sampling frequency and I'm wondering what's going on inside the ADC hardware when I change the sampling frequency.</p>
<p>Possibly not. The ADC on the Arduino Uno (a different processor, I know) uses the &quot;sample and hold&quot; technique. This means that the ADC samples the input voltage at a point in time, copying it into a sample-and-hold capacitor. It then successively compares it to be above or below threshold voltages to generate the individual bits of the resulting number. I have some details about the Uno ADC <a href="http://gammon.com.au/adc" rel="nofollow noreferrer">here</a>.</p> <p>It probably does this so that, when sampling a rapidly changing signal (like audio) it samples a moment in time, rather than having the comparison be of a signal that is changing over time.</p> <p>I can't find technical details for the ESP32 ADC sampling method, but it seems likely that a lower sample rate will simply sample less data points, not take an average. This could lead to wildly inaccurate results.</p> <p>You might want to check out the <a href="https://en.wikipedia.org/wiki/Nyquist_frequency" rel="nofollow noreferrer">Nyquist Frequency</a> to see the reasons for choosing a certain sample rate.</p> <p>If you want an average, feeding the signal into a suitably-sized RC filter might be a good way of finding an average voltage.</p>
92888
|spi|arduino-due|
Send data through SPI with DMA
2023-04-18T06:35:17.957
<p>I need to send data as fast as possible from an Arduino DUE to an extern DAC. To do so I use DMA &amp; SPI and I want DMA to fetch data from the memory and send it to the SPI which will just relay it via its Master Output Slave input. So far I did a DMA transfer from a variable to another, woked perfectly. I'm using the same code but change the address as SPI_TDR (Transmit Data Register), unfortunatly it's not working. I guess the address is not good but if so what should I do ?</p> <p>Here is my code :</p> <pre><code>#include &lt;dmac.h&gt; #include &lt;SPI.h&gt; #define DMA_CH 0 //N° Canal du DMA #define DMA_BUF_SIZE 32 //Taille mémoire DMA uint32_t g_dma_buf2[DMA_BUF_SIZE]; void setup() { Serial.begin(9600); SPI.begin(); SPI0-&gt;SPI_WPMR = 0x53504900; //Protection key SPI0-&gt;SPI_IDR = 0x0000070F; //Desactivation interrupts SPI0-&gt;SPI_MR = SPI_MR_MSTR | SPI_MR_PS; //SPI master } void loop() { Serial.println(&quot;+++++&quot;); pmc_enable_periph_clk(ID_DMAC); uint32_t i; uint32_t cfg; dma_transfer_descriptor_t desc; for (i = 0; i &lt; DMA_BUF_SIZE; i++) { g_dma_buf2[i] = i; Serial.print(g_dma_buf2[i]); } Serial.println(); dmac_init(DMAC); dmac_set_priority_mode(DMAC, DMAC_PRIORITY_ROUND_ROBIN); dmac_enable(DMAC); cfg = DMAC_CFG_SOD_ENABLE | DMAC_CFG_AHB_PROT(1) | DMAC_CFG_FIFOCFG_ALAP_CFG; //Config registre CFG dmac_channel_set_configuration(DMAC, DMA_CH, cfg); desc.ul_source_addr = (uint32_t)g_dma_buf2; desc.ul_destination_addr = SPI0-&gt;SPI_TDR; desc.ul_ctrlA = DMAC_CTRLA_BTSIZE(DMA_BUF_SIZE) | DMAC_CTRLA_SRC_WIDTH_WORD | DMAC_CTRLA_DST_WIDTH_WORD; desc.ul_ctrlB = DMAC_CTRLB_SRC_DSCR_FETCH_DISABLE | DMAC_CTRLB_DST_DSCR_FETCH_DISABLE | DMAC_CTRLB_FC_MEM2MEM_DMA_FC | DMAC_CTRLB_SRC_INCR_INCREMENTING | DMAC_CTRLB_DST_INCR_FIXED; desc.ul_descriptor_addr = 0; SPI_Enable(SPI0); dmac_channel_multi_buf_transfer_init(DMAC, DMA_CH, &amp;desc); dmac_channel_enable(DMAC, DMA_CH); Serial.println(&quot;*****&quot;); while (!dmac_channel_is_transfer_done(DMAC, DMA_CH)) { Serial.print('X'); } Se Serial.print(&quot;SR : &quot;); Serial.println(SPI0-&gt;SPI_SR, HEX); Serial.print(&quot;TDR : &quot;); Serial.println(SPI0-&gt;SPI_TDR, HEX); Serial.print(&quot;PSR : &quot;); Serial.println(PIOA-&gt;PIO_PSR, HEX); //PIO_SODR Serial.print(&quot;OSR : &quot;); Serial.println(PIOA-&gt;PIO_OSR, HEX); Serial.println(DMAC-&gt;DMAC_CH_NUM[0].DMAC_SADDR , HEX); Serial.println(DMAC-&gt;DMAC_CH_NUM[0].DMAC_DADDR, HEX); Serial.println(&quot;-----&quot;); } </code></pre> <p>I use mainly this example : <a href="https://ww1.microchip.com/downloads/en/Appnotes/Atmel-42291-SAM3A-3U-3X-4E-DMA-Controller-DMAC_ApplicationNote_AT07892.pdf#_OPENTOPIC_TOC_PROCESSING_d91e3076" rel="nofollow noreferrer">https://ww1.microchip.com/downloads/en/Appnotes/Atmel-42291-SAM3A-3U-3X-4E-DMA-Controller-DMAC_ApplicationNote_AT07892.pdf#_OPENTOPIC_TOC_PROCESSING_d91e3076</a> And here is the datasheet of the µc : <a href="https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf" rel="nofollow noreferrer">https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf</a></p> <p>You can see at the bottom of my code sevral prints, from them I had many idea : does the PIO could block the data ? Does the address PIO_PA26A_SPI0_MOSI could work ? Could the SPI block the data because conditions are not met ?</p> <p>Any idea is welcomed, I'm on this for some time now.</p> <p>Edit : SPI is not an necessity, the idea is to send data without length limit (unlike UART). I'm considering using SSC.</p>
<p>I believe I have gotten this to work the way you intended, without SSI. Bits of this code have been borrowed from an SD Card library (<a href="https://github.com/openbci-archive/OpenBCI_8bit/blob/master/OpenBCI_8bit_SDfat_Library/SdFat/SdSpiSAM3X.cpp" rel="nofollow noreferrer">https://github.com/openbci-archive/OpenBCI_8bit/blob/master/OpenBCI_8bit_SDfat_Library/SdFat/SdSpiSAM3X.cpp</a>, around line 110). I am trying to run a TFT using a &quot;framebuffer,&quot; but in order to do so I need DMA working with SPI.</p> <p>In your original source, it appears you are missing a few things in <code>cfg</code>. According to the aforementioned code listing, <code>cfg</code> should look something like <code>DMAC_CFG_DST_PER(1) | DMAC_CFG_DST_H2SEL | DMAC_CFG_SOD_ENABLE | DMAC_CFG_AHB_PROT(1) | DMAC_CFG_FIFOCFG_ALAP_CFG</code>. Per the datasheet, <code>DST_PER</code> must be set to one of the DMA channels seen on page 339, table 22-2. In this case, Channel 1 is used, as it corresponds to SPI0_TX. Likewise, you appear to be missing DMAC_CFG_DST_H2SEL for hardware handshaking. There's likely a few other things I'm not pointing out, as I had a fair amount of trouble with this too.</p> <p>TL;DR The following code should do the trick for a basic DMA transfer from a buffer:</p> <pre><code>#include &quot;sam.h&quot; #define CLOCK_SPEED 84000000 void setup_spi() { PMC-&gt;PMC_PCER0 |= (1 &lt;&lt; ID_PIOA); // Enable PIOA PIOA-&gt;PIO_ODR |= PIO_PA25; // MISO Pin - Input PIOA-&gt;PIO_PDR |= PIO_PA25; PIOA-&gt;PIO_ABSR &amp;= ~(PIO_PA25); // MISO Pin - (A) Peripheral PIOA-&gt;PIO_OER |= PIO_PA26; // MOSI Pin - Output PIOA-&gt;PIO_PDR |= PIO_PA26; PIOA-&gt;PIO_ABSR &amp;= ~(PIO_PA26); // MOSI Pin - (A) Peripheral PIOA-&gt;PIO_OER |= PIO_PA27; // SCLK Pin - Output PIOA-&gt;PIO_PDR |= PIO_PA27; PIOA-&gt;PIO_ABSR &amp;= ~(PIO_PA27); // SCLK Pin - (A) Peripheral PIOA-&gt;PIO_OER |= PIO_PA28; // CS Pin 0 - Output PIOA-&gt;PIO_PDR |= PIO_PA28; PIOA-&gt;PIO_ABSR &amp;= ~(PIO_PA28); // CS Pin 0 - (A) Peripheral PIOA-&gt;PIO_PUER |= PIO_PA28; // Disable the SPI to configure it SPI0-&gt;SPI_CR |= SPI_CR_SPIDIS; // SPI0 Setup -------------- PMC-&gt;PMC_PCER0 = (1 &lt;&lt; ID_SPI0); // Enable SPI0 Clock // Master Mode, Fixed Peripheral Mode, Mode fault detection disabled, Fixed peripheral modes SPI0-&gt;SPI_MR = SPI_MR_MSTR | SPI_MR_MODFDIS; // Mode and Clock Clock Freq Calculation SPI0-&gt;SPI_CSR[0] |= SPI_CSR_NCPHA | (((int8_t)(CLOCK_SPEED / 1000000)) &lt;&lt; 8); // Need to stick clock calculation in byte 2 // 8 bits per transfer SPI0-&gt;SPI_CSR[0] |= SPI_CSR_BITS_8_BIT; SPI0-&gt;SPI_CR |= SPI_CR_SPIEN; // Enable SPI0 } uint8_t pixbuf[] = &quot;This is a test!&quot;; // Buffer to be transmitted void setup_dma() { PMC-&gt;PMC_PCER1 |= (1 &lt;&lt; (ID_DMAC - 32)); // Turn on DMA Controller Clock (?) DMAC-&gt;DMAC_EN = 0; // Disable DMA Controller DMAC-&gt;DMAC_GCFG = DMAC_GCFG_ARB_CFG_ROUND_ROBIN; // Set arbitration method DMAC-&gt;DMAC_EN = 1; // Enable DMA Controller DMAC-&gt;DMAC_CHDR = DMAC_CHDR_DIS0; // Disable DMA Channel 0 DMAC-&gt;DMAC_CH_NUM[0].DMAC_SADDR = (uint32_t)pixbuf; // Set src buffer DMAC-&gt;DMAC_CH_NUM[0].DMAC_DADDR = (uint32_t)&amp;SPI0-&gt;SPI_TDR; // Set dst buffer DMAC-&gt;DMAC_CH_NUM[0].DMAC_DSCR = 0x0; DMAC-&gt;DMAC_CH_NUM[0].DMAC_CTRLA = DMAC_CTRLA_DST_WIDTH_BYTE | DMAC_CTRLA_SRC_WIDTH_BYTE | DMAC_CTRLA_BTSIZE(0x10); // Set src/dest bit width (8 bits) and set buffer size to 16 DMAC-&gt;DMAC_CH_NUM[0].DMAC_CTRLB = DMAC_CTRLB_DST_INCR_FIXED | DMAC_CTRLB_SRC_INCR_INCREMENTING | DMAC_CTRLB_FC_MEM2PER_DMA_FC | DMAC_CTRLB_DST_DSCR | DMAC_CTRLB_SRC_DSCR | DMAC_CTRLB_FC_MEM2PER_DMA_FC; DMAC-&gt;DMAC_CH_NUM[0].DMAC_CFG = DMAC_CFG_DST_PER(1) | DMAC_CFG_DST_H2SEL | DMAC_CFG_SOD_ENABLE | DMAC_CFG_AHB_PROT(1) | DMAC_CFG_FIFOCFG_ALAP_CFG; // Configure DMA Controller DMAC-&gt;DMAC_EBCISR; // Read interrupt register to clear interrupt flags DMAC-&gt;DMAC_CHER = DMAC_CHER_ENA0; // Enable DMA Channel 0 } int main(void) { /* Initialize the SAM system */ SystemInit(); setup_dma(); setup_spi(); while (!(DMAC-&gt;DMAC_CHSR &amp; DMAC_CHSR_ENA0 &lt;&lt; 0)); uint32_t dma_status; dma_status = DMAC-&gt;DMAC_EBCISR; //SPI0-&gt;SPI_TDR = 'a'; // Write dummy out /* Replace with your application code */ while (1) { } } </code></pre> <p>Hope this helps.</p>
92906
|arduino-uno|avr|memory|avr-toolchain|
What's Memory Allocation technique in Arduino
2023-04-19T18:05:54.003
<p>I am currently working on an assignment for my embedded systems course, and my professor has asked us to determine the memory allocation technique employed in Arduino. Specifically, I need to identify whether it utilizes best fit, quick fit, worst fit, next fit, or first fit memory allocation methods.</p> <p>Despite conducting online research and seeking input from my colleagues, We have been unable to find an answer to this question.</p> <p>I would greatly appreciate any insights or information on the memory allocation technique used in Arduino.</p> <p>Thank you.</p>
<p>Long answer short, it used both first-fit and best-fit.</p> <p>The <a href="http://svn.savannah.gnu.org/viewvc/avr-libc/tags/avr-libc-2_0_0-release/libc/stdlib/malloc.c?revision=2516&amp;view=markup" rel="nofollow noreferrer">malloc</a> function in the <a href="https://www.nongnu.org/avr-libc/user-manual/index.html" rel="nofollow noreferrer">avr-libc</a> makes use of a so-called free list to track the free spaces in the memory.</p> <p>When there is a memory request, it starts by looping over this list searching for the first exact match <strong>[First Fit]</strong>.</p> <p>While looping over the list, it keeps track of the piece of memory that will leave the least amount of space(best-fit). If it didn't find the exact match, it uses this piece of memory <strong>[Best Fit]</strong>.</p> <p>Furthermore, it doesn't use this piece of memory directly, it checks for its size first, if it is big enough, it takes the amount of memory needed and adds the leftover to the free list, else, it allocates the whole piece of memory.</p> <p>N.B. it allocates new memory space to the heap if it doesn't find the first-fit or best-fit.</p> <hr /> <h3>Example Scenarios:</h3> <ol> <li>First Fit:</li> </ol> <ul> <li>Free list: [64, 128, 128, 256, 512, 128]</li> <li>Request: 128</li> <li>Action: Take the first 128.</li> </ul> <ol start="2"> <li>Best Fit:</li> </ol> <ul> <li>Free list: [64, 256, 512]</li> <li>Request: 128</li> <li>Action: Take the 256, use 128, and add the other 128 to the free list.</li> </ul> <ol start="3"> <li>Best Fit:</li> </ol> <ul> <li>Free list: [64, 256, 512, 130]</li> <li>Request: 128</li> <li>Action: Take the 130 and use it all.</li> </ul> <p>Hope things are clear now!</p>
92915
|arduino-ide|arduino-leonardo|
help with error: cant open device "\\.\COM6":Access is denied
2023-04-20T04:48:39.053
<p>I built a new pc which I use as a flight simulator. On my old PC I had ArduinoIDE for programming a pro micro as well as a teensy 4.1 using the teensyduino library. I installed all the necessary libraries and can make revisions to the code for the Teensy and successfully upload them. However when I try to upload anything to the arduino I get the above mentioned error. The old pc could program the arduino without a problem.</p> <p>The arduino is showing up in device manager and it disappears when the usb cable is unplugged. The correct port is chosen in the tools menu and I can get the board info. I just can upload it to the board. Still using windows 10 pro, the same OS as on the previous pc.</p> <p>Running the arduino IDE (v2.1.0) as admin does not help.</p>
<p>Installing Arduino 1.8.19 solved the problem. I guess v2.1.0 has some code that trips over itself.</p>
92925
|arduino-uno|interrupt|
Why does the interrupt not work after pressing the button
2023-04-21T09:44:02.040
<p>Implement interrupt processing when the button is pressed, and the very start on the rising edge, the interrupt pin and to which the button is connected 11. Why does the interrupt not work after pressing the button?</p> <pre><code>#include &lt;PinChangeInterrupt.h&gt; const uint8_t buttonPin = 11; volatile bool buttonPressed = false; void setup() { pinMode(buttonPin, INPUT_PULLUP); attachPCINT(buttonPin, buttonISR, RISING); Serial.begin(9600); } void loop() { if (buttonPressed) { Serial.println(&quot;Button pressed!&quot;); buttonPressed = false; } } void buttonISR() { buttonPressed = true; } </code></pre> <p>Model: <a href="https://i.stack.imgur.com/3O7RY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3O7RY.jpg" alt="enter image description here" /></a></p>
<p>I just tested proper code with some changes:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;PinChangeInterrupt.h&gt; const uint8_t buttonPin = 11; volatile bool buttonPressed = false; void buttonISR() { buttonPressed = true; } void loop() { if (buttonPressed) { delay(20); buttonPressed = false; digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } } void setup() { pinMode(buttonPin, INPUT_PULLUP); attachPCINT(digitalPinToPCINT(buttonPin), buttonISR, RISING); pinMode(LED_BUILTIN, OUTPUT); } </code></pre> <p>And with <code>attachPCINT(digitalPinToPCINT(buttonPin), buttonISR, RISING);</code> it works flawlessly. Only difference is that <code>digitalPinToPCINT</code> (as every example for PinChangeInterrupt library tries to suggest).</p> <p>You also tried attachInterrupt + digitalPinToInterrupt with the pin 11, but Arduino Uno has only two external interrupt capable pins D2 and D3. So it couldn't work with D11. It also depends on MCU (see <a href="https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/" rel="nofollow noreferrer">attachInterrupt() reference</a>).</p> <p>The PCINT is more or less related to the old AVRs like Atmega328 or Atmega2560. And PCINT in Atmega2560 isn't available on all port (it uses ISR per port and it has many ports.</p> <p>If the proteus simulator is the cause, you can also ommit the ISR (as you are not doing anything big here) and just poll the pin:</p> <pre><code>const uint8_t buttonPin = 11; bool buttonPressed = false; void loop() { bool pinHigh = (digitalRead(buttonPin) == HIGH); if (pinHigh &amp;&amp; buttonPressed) { // button released delay(20); buttonPressed = false; digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } else if (!pinHigh &amp;&amp; !buttonPressed) { buttonPressed = true; } } void setup() { pinMode(buttonPin, INPUT_PULLUP); pinMode(LED_BUILTIN, OUTPUT); } </code></pre>
92936
|rgb-led|
How much time does it take to propagate the control signal through all LEDs in the ws2812b strip?
2023-04-22T23:40:00.167
<p>In my next small Arduino project, I wanted to use some addressable rgb led strips. I made some small research and choose to use a strip with ws2812b. Generally, I know how this works but I am not 100% sure if what I think is correct. So please correct me if I am wrong.</p> <p>For each pixel in the strip, we need to send 24 bits to control it. If we have 10 pixels in a strip then we need to send 240 bits. Then first pixel reads all 240 bits, sets itself color, and lastly propagates other 216 bits to the next pixel. And so on to the last pixel.</p> <p>I am wondering, how much time does it take to update state of the last pixel in strip?</p> <p>If sending 24 bit takes something about 30us (1.25us for 1 bit) then is that mean that sending signals to the last pixel in a strip with 10 pixels would take 300us + 270us + 240us + ... + 30us or is it rather just 300us?</p>
<p>I have <a href="http://www.gammon.com.au/forum/?id=13357" rel="nofollow noreferrer">a page about the WS2812 chip</a> along with a suggested way of writing code simply for it. It also describes the timing.</p> <p>The documented timing for a 0-bit is 1150 ns and for a 1-bit is 1300 ns.</p> <p><a href="https://i.stack.imgur.com/sb567.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sb567.png" alt="NeoPixels timing" /></a></p> <p>Thus, if we assume all bits are on, then 24 bits would take 24 * 1300 ns which is 31.2 µs.</p> <p>Since the bits are propagated along the strip, then it would take 10 * 31.2 µs (312 µs) to send all 10 colours.</p> <p>What I mean by &quot;propagated&quot; is that as each bit arrives at each chip it also forwards it onward to the next chip, much like a shift register. Thus the more bits you send the further the original ones are &quot;pushed&quot; towards the end of the strip.</p> <p>As the documentation describes, each chip &quot;reshapes&quot; the incoming bit, so that any jitter or noise in the arriving bit is cleaned up as it is forwarded so that the individual bits do not degrade as they are forwarded. Think of <a href="https://en.wikipedia.org/wiki/Chinese_whispers" rel="nofollow noreferrer">Chinese Whispers</a> - because of the reshaping by each chip the information is <strong>not</strong> corrupted as it is passed on.</p> <p>Then you send 50 µs of 0V to latch the new colours to the entire strip.</p> <p>So, the answer to your question is 362 µs (roughly).</p>
92953
|esp32|firmware|
Same Bin file to similar ESP32 boards yields different results
2023-04-24T17:59:43.450
<p>Sorry for the confusing title. It is a bit hard to explain.</p> <p>We have a remote developer who compiles his code into a bin file and sends it to all of us. He loads it onto his ESP32 boards and they work just fine. However, when we load the bin file onto our ESP32 boards, they do not work. We are all using the same configuration ESP32 boards. We are all using Expressif Flash Download tool to load the bin file.</p> <p>Where would y'all recommend I start my investigation? What additional info do you need from me to help figure this out? I have confirmed that we are all using the same ESP32 boards as well as the same flash tool. Ideas?</p> <p>By the way, I am not the programmer, I do not have access to the source code. I only have the bin file.</p> <p>Thank you</p>
<p>My fault. I hadn't wired the final product exactly as the designer had. Once the wiring was correct the issue was resolved. Just needed a physical troubleshooting as the software troubleshooting wasn't the issue.</p> <p>Funny thing is, there are only two wires on the entire project and I had gotten them wrong.</p> <p>So I think the lesson here is, check your physical configuration as well as the software/firmware.</p> <p>Thank you all for your help.</p>
92981
|spi|stm32|
Arduino Bluepill STM32 spi doesn't work
2023-04-26T09:54:32.213
<p>Has anyone successfully use SPI1 of those pins?</p> <pre><code>SCLK -&gt; PB3 SDIO -&gt; PB5 SDO -&gt; PB4 MISO CS -&gt; PA15 </code></pre> <p>I've tried to use another side of SPI1 pins on the other sides of the board (PA4, 5, 6, 7) and i can successfully communicate with <a href="https://i.stack.imgur.com/SNhzx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SNhzx.png" alt="enter image description here" /></a></p>
<p>It depends on how you use the SPI object. If you use the SPI object directly like what Arduino Uno without creating an instance object, the SPI construct will default to the PA4 - PA7, see the <a href="https://github.com/stm32duino/Arduino_Core_STM32/blob/main/variants/STM32F1xx/F103C8T_F103CB(T-U)/variant_PILL_F103Cx.h#L104-L113" rel="nofollow noreferrer">default pins definition</a> and <a href="https://github.com/stm32duino/Arduino_Core_STM32/blob/main/libraries/SPI/src/SPI.cpp#L25" rel="nofollow noreferrer">default Class construct</a> of Blue Pill.</p> <p>For STM32 Arduino Core (Stm32duino), there are four STM32 Arduino Core specific APIs for configure the alternative SPI pins.</p> <pre><code>void setMISO(uint32_t miso) void setMOSI(uint32_t mosi) void setSCLK(uint32_t sclk) void setSSEL(uint32_t ssel) </code></pre> <p>These <strong>must</strong> be called before the <code>SPI.begin()</code>.</p> <p>Another alternative way of using the alternative SPI pins is to create an SPI object and pass-in the pin assignments like this:</p> <pre><code>#include &lt;SPI.h&gt; SPIClass mySPI(PB5, PB4, PB3, PB15); //mosi, miso, sclk, ssel </code></pre> <p>See the <a href="https://github.com/stm32duino/Arduino_Core_STM32/blob/main/libraries/SPI/src/SPI.cpp#L46-L52" rel="nofollow noreferrer">alternative construct</a> API, and further information on STM32duino <a href="https://github.com/stm32duino/Arduino_Core_STM32/wiki/API#spi" rel="nofollow noreferrer">wiki</a> page.</p>
92992
|arduino-uno|calculation|
Unexpected Behaviour w/ Arduino Uno Calculation
2023-04-27T00:12:01.940
<p>I have a really simple snippet of code wherein the same calculation outputs different values depending on how I do the calculation. The platform that I am running this code on is an <strong>Arduino Uno</strong> - with an <strong>Atmel MEGA328P</strong> microcontroller chip. Here's the code:</p> <pre><code>void setup() { Serial.begin(9600); unsigned long num = 100927; Serial.println(1000*60); Serial.println(num/(1000*60)); Serial.println(num/(60000)); } void loop() {} </code></pre> <p>This code prints the following on the console:</p> <pre><code>-&gt; -5536 -&gt; 0 -&gt; 1 </code></pre> <p>I don't understand why <code>num/(1000*60)</code> and <code>num/(60000)</code> evaluate to different values? Also, <code>1000*60</code> evaluates to a garbage value which looks like it somehow set the data type to int and resulted in overflowing the &quot;int&quot; range.</p> <p>My programming background is heavy in Python. I figure I'm used to python dynamically interpreting variable data types for me which is why the arduino language confuses me a bit here. Any help is appreciated!</p>
<p>This is a pure C++ programming issue, which I cover <a href="http://www.gammon.com.au/forum/?id=12146" rel="nofollow noreferrer">on my web site</a>.</p> <p>However, since link-only answers are not allowed here, I reproduce that post below:</p> <hr /> <p>On the Arduino (Uno) platform, what do you think will be printed here?</p> <pre><code>void setup () { Serial.begin (115200); Serial.println (); Serial.println (30000 + 30000); // twice 30000 Serial.println (60 * 60 * 24); // seconds in a day Serial.println (50 / 100 * 1000); // half of 1000 } // end of setup void loop () { } </code></pre> <p>Did you guess:</p> <pre><code>60000 86400 500 </code></pre> <p>Nope!</p> <p>It prints:</p> <pre><code>-5536 20864 0 </code></pre> <p>This is because of <strong>integer arithmetic</strong>. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767. This may be unexpected for users of modern compilers because nowadays an <code>int</code> is usually 32 bits. However on the 8-bit Arduino processors such as the Atmega328P the compiler treats an int as 16 bits wide. The C++ standard permits an int size of <strong>at least</strong> 16 bits, but you are not guaranteed that it will be larger.</p> <p>And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.</p> <p>For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.</p> <p>Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).</p> <p>Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.</p> <hr /> <p>So, can we &quot;help&quot; the compiler by telling it the sort of result we want, like this?</p> <pre><code>void setup () { Serial.begin (115200); Serial.println (); long a = 30000 + 30000; long b = 60 * 60 * 24; float c = 50 / 100 * 1000; Serial.println (a); Serial.println (b); Serial.println (c); } // end of setup void loop () { } </code></pre> <p>That prints:</p> <pre><code>-5536 20864 0.00 </code></pre> <p>So no, that hasn't helped.</p> <hr /> <h2>Solution</h2> <p>First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:</p> <pre><code>void setup () { Serial.begin (115200); Serial.println (); Serial.println (30000L + 30000); // twice 30000 Serial.println (60L * 60 * 24); // seconds in a day Serial.println (50.0 / 100 * 1000); // half of 1000 } // end of setup void loop () { } </code></pre> <p>Now we get:</p> <pre><code>60000 86400 500.00 </code></pre> <p>You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression. *</p> <p>Or we can &quot;cast&quot; them:</p> <pre><code>void setup () { Serial.begin (115200); Serial.println (); long a = (long) 30000 + 30000; long b = (long) 60 * 60 * 24; float c = (float) 50 / 100 * 1000; Serial.println (a); Serial.println (b); Serial.println (c); } // end of setup void loop () { } </code></pre> <p>Results:</p> <pre><code>60000 86400 500.00 </code></pre> <p>Casting is useful for variables, because you can't just add &quot;L&quot; to the end of a variable name.</p> <p>An alternative syntax is to use a constructor like this:</p> <pre><code>void setup () { Serial.begin (115200); Serial.println (); long a = long (30000) + 30000; long b = long (60) * 60 * 24; float c = float (50) / 100 * 1000; Serial.println (a); Serial.println (b); Serial.println (c); } // end of setup void loop () { } </code></pre> <p>(Same results).</p> <hr /> <p>* It's actually somewhat more complex than that as this link explains: <a href="https://wiki.sei.cmu.edu/confluence/display/c/INT02-C.+Understand+integer+conversion+rules" rel="nofollow noreferrer">Understand integer conversion rules</a></p> <p>The compiler &quot;promotes&quot; a value in an expression to match another &quot;higher-ranked&quot; type, under certain circumstances. For example, adding an <strong>int</strong> and a <strong>long</strong> will result in the <strong>int</strong> being promoted to a <strong>long</strong> (regardless of whether it appears first in the expression or not). However if an <strong>int</strong> is being added to another <strong>int</strong>, it will <em>not</em> promote them to a <strong>long</strong>, even though the result may not fit into an <strong>int</strong>.</p> <hr /> <h2>More explanations</h2> <p>I was asked in the comments why <code>1000 * 60</code> is not the same as <code>60000</code> from the compiler's point of view.</p> <p>The answer is that a compiler will treat an integer literal as an <strong>int</strong> (if possible) and an <strong>int</strong> on this platform is 16 bits.</p> <p>Thus 1000 (an <strong>int</strong>) * 60 (another <strong>int</strong>) are multiplied using 16-bit arithmetic, giving a result that overflows.</p> <p>However the literal, 60000, cannot be stored as an <strong>int</strong> and thus the compiler promotes it to <strong>long</strong> (aka &quot;<strong>long</strong> <strong>int</strong>&quot;). Since it has been promoted to a <strong>long</strong> it is correctly stored, and further operations on 60000 will be done with <strong>long</strong> arithmetic.</p> <p>I have seen people code 60000 as 60000L however that is unnecessary. The compiler is not silly enough to make 60000 be stored as -5536, as that is clearly not the intent of the programmer.</p>
93023
|arduino-uno|serial|array|loop|
Program to Multiply Numbers Won't Actually Multiply Them
2023-04-29T18:49:10.023
<p>I am trying to write a program which takes in a number of pairs to be multiplied, then prints out the result of each multiplication. Instead of doing this, the program just prints out the number of multiplications and the numbers, but it never does the multiplications or add the newline characters (despite me explicitly using println). In the example below I specify 2 number pairs to multiply, and then enter 3,4,7,8 (entering a NL character after each number, but spaces and commas cause the same problem).</p> <p><a href="https://i.stack.imgur.com/doNnK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/doNnK.jpg" alt="Result" /></a></p> <p>I thought my approach would work, but I believe that there is something I am doing with the serial input that is causing the code not work (although there could be some other issue). I also wonder if maybe it's because I'm running this in Tinkercad and not the real Arduino IDE. Any help would be greatly appreciated.</p> <pre><code>void loop() { int numOfMults = 0; // number of pairs to multiply float *numArray; // pointer to beginning of array memory block numArray = (float *)malloc(sizeof(float)*50); // dynamically allocate an array that can hold up to 50 floats numOfMults = Serial.parseInt(); // take in the number of multiplications from user Serial.println(numOfMults); // take in the specified amount of numbers (2 times the num of multiplications) in format: 1,2,3... // then convert that into an array of floats, where every 2 indices // is a pair of numbers to multiply for (int i = 0; i &lt; (2*numOfMults) ;i++) { numArray[i] = Serial.parseFloat(); } multNums(numOfMults,numArray); // call function to get the product of all the numbers delay(5000); // wait 5 seconds before starting the loop again } void multNums(int numofNums,float nums[]) { float *productArray; // pointer to beginning of the product array memory block productArray = (float *)malloc(sizeof(float)*25); // dynamically allocate an array that can hold up to 25 floats (for the products) // multiply all the number pairs in the array, store the product in another for(int i=0;i&lt;(2*numofNums);i+2) { productArray[i/2] = nums[i]*nums[i+1]; // multiply current number pair, store in the product array one index at a time } // print the products for(int i=0; i &lt; sizeof(productArray) ;i++) { Serial.println(productArray[i]); } } </code></pre>
<p>There are quite a few issues in this code:</p> <ul> <li><p>In C++, you are supposed to do dynamic allocation with <code>new</code> rather than <code>malloc()</code>.</p> </li> <li><p>If you allocate dynamic memory in a loop and forget to free it (with <code>free()</code>/<code>delete</code>), you will quite quickly run out of memory.</p> </li> <li><p>Actually, you do not even need to do any dynamic allocation at all: automatic allocation is the safest way to handle these arrays.</p> </li> <li><p>Since you know the exact size you need, allocate that rather than a default size.</p> </li> <li><p><code>multNums</code> receives as a parameter the number of multiplications, not the length of the array.</p> </li> <li><p><code>i+2</code> does not change the value of <code>i</code>. You meant <code>i+=2</code>.</p> </li> <li><p><code>sizeof(productArray)</code> does not give the length of the array, but its size in bytes. Besides, your last loop is supposed to iterate only through the initialized part of the array.</p> </li> </ul> <p>If you fix those issues, the program should work as expected.</p>
93066
|ide|java|
Arduino IDE Auto Format Error
2023-05-03T18:04:23.617
<p>Whenever I try to format a sketch in the IDE (1.8.19) I get this output in the terminal:</p> <pre><code>Exception in thread &quot;AWT-EventQueue-0&quot; java.lang.UnsatisfiedLinkError: 'java.lang.String cc.arduino.packages.formatter.AStyleInterface.AStyleMain(java.lang.String, java.lang.String)' at cc.arduino.packages.formatter.AStyleInterface.AStyleMain(Native Method) at cc.arduino.packages.formatter.AStyle.run(AStyle.java:80) at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313) at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770) at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721) at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740) at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203) at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124) at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113) at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109) at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90) </code></pre> <p>...And formatting fails.</p> <p>I can use astyle from the command line (linux mint) and it works well.</p> <p>Guessing that some basic package was missing, or corrupted, I reinstalled Arduino, but the issue remained.</p> <p>I don't precisely recall any specific changes made to my system prior to encountering this behavior, as it's been like this for at least 8 or 9 months now. I hadn't used Arduino for some time up until that point and it may have been a fresh instal.</p> <p>Since I just started a new project for a buddy of mine and encountered the bug again I decided maybe it was time to see about a better solution.</p> <p>Any help troubleshooting this would be greatly appreciated.</p>
<p>I googled the first line of stack trace and found similar <a href="https://github.com/arduino/Arduino/issues/11728" rel="nofollow noreferrer">issue on github</a> (but for SUSE linux). In this issue the Arduino IDE was installed by system package manager and after downloading latest package from arduino.cc/en/software it started working.</p> <p>In general Arduino IDE linux packages are somehow problematic (as far as I know Ubuntu has still version around 1.0.6) and it's better to use latest version directly from arduino.cc</p>
93087
|arduino-uno|interrupt|
How can when the button is clicked to display its name
2023-05-05T12:20:09.997
<p>I need to recognize a signal from an IR remote, not to use a library for working with IR remotes/receivers. How can when the button is clicked to display its name. I have PIC12F615 microcontroller with this code: <a href="https://github.com/circuitvalley/IR-Remote-Control/blob/master/NEC%20IR%20Transmitter%20Remote/main.c" rel="nofollow noreferrer">code</a> and 5 buttons connected to him and I need recognise which button pressed. I have some code but it gives different hex codes if I pressed the same button.</p> <pre><code>byte IRpin = 2; volatile boolean remote = false; volatile unsigned long irCode = 0; void remoting () { if ( remote ) { remote = false; unsigned long T; for ( byte n = 0; n &lt; 32; n ++ ) { do { T = pulseIn ( IRpin, HIGH, 2200 ); } while ( T &lt; 64 ); bitWrite ( irCode, n, T &gt; 1120 ); } } } void setup () { Serial.begin ( 9600 ); Serial.println ( &quot;\n\tReady for keyboard reading!\n&quot; ); pinMode ( IRpin, INPUT_PULLUP ); attachInterrupt ( digitalPinToInterrupt ( IRpin ), remoting, FALLING ); } void loop () { if (irCode) { Serial.println (irCode, HEX); irCode = 0; } delay (40); remote = true; } </code></pre> <p>Schema: <a href="https://i.stack.imgur.com/Pf4Ik.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pf4Ik.jpg" alt="enter image description here" /></a></p>
<p>The function pulseIn() has this comment in the source code: &quot;This function performs better with short pulses in noInterrupt() context&quot; see: <a href="https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_pulse.c" rel="nofollow noreferrer">https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_pulse.c</a>. It is not clear if your code violates the &quot;short pulse&quot; rule, however, blocking an Interrupt Service Routine (in your case, the external interrupt call back routine remoting() ) for the entire length of an IR data stream is certain to cause other problems, for example, with the millis() timer.</p> <p>This is in the style of your code but avoids using interrupts. It has been tested against an NEC remote control and gives repeatable results. Your code fails the same test.</p> <pre><code>byte IRpin = 2; unsigned long irCode = 0; void setup () { Serial.begin ( 9600 ); Serial.println ( &quot;\n\tReady for keyboard reading!\n&quot; ); pinMode ( IRpin, INPUT_PULLUP ); } void loop () { while ( digitalRead ( IRpin ) ); // wait until start of first pulse unsigned long T; uint8_t validPulses = 0 ; for ( byte n = 0; n &lt; 36 ; n ++ ) // enough to drop long header { T = pulseIn ( IRpin, HIGH , 12000 ); // 12ms timeout if ( T &lt; 4000 &amp;&amp; T &gt; 400 &amp;&amp; validPulses &lt; 32 ) { // valid pulse bitWrite ( irCode, validPulses++, T &gt; 1120 ); } } if (irCode &gt; 0 ) Serial.println (irCode, HEX); else Serial.println (&quot;no code&quot;); irCode = 0 ; } </code></pre>
93090
|arduino-uno|sensors|linux|windows|ubuntu|
Arduino Readings Update Correctly on Windows but not Linux
2023-05-05T13:48:00.697
<p>I have written a simple script to get angle measurements from a magnetic sensor. The script works very well on Windows. However, when compiling the script on a Linux VirtualBox (Ubuntu 20.04), the sensor repeats the first angle reading and does not change from this, despite the angle changing. There are no errors/warnings given by Windows or Linux at any stage of compiling/uploading.</p> <p>Uploading the script on Windows and then viewing in Linux serial monitor works. However, uploading it on Linux and then viewing in Windows serial monitor does not work (&quot;Board is not available&quot;), even when connecting the board to Linux and not Windows.</p> <p>I've compared both systems and everything seems to be the same: the same Arduino Uno R3 board, Arduino IDE 1.8.19 on both systems, Arduino AVR Boards 1.8.3 on both, &quot;Arduino Uno&quot; selected as the board on both, the library is SimpleFOC v2.2.0 on both. The only difference I can see is that the Windows port is COM3, whereas the Linux port is /dev/ttyACM0.</p> <p>My script is the following and I would appreciate any help or advice to get this working on Linux. Thank you.</p> <pre><code>#include &lt;SimpleFOC.h&gt; #define PI 3.1415926535897932384626433832795 // Magnetic sensor instance MagneticSensorSPI AS5x4x = MagneticSensorSPI(8, 14, 0x3FFF); void setup() { // initialize magnetic sensor hardware AS5x4x.init(); // use monitoring with serial Serial.begin(9600); Serial.println(&quot;Ready.&quot;); _delay(1000); } void loop() { Serial.println(AS5x4x.getAngle()); // display angle } </code></pre>
<p>It turns out that the Arduino Library Manager was giving me incorrect information about the library version installed. By removing the library it was using and then installing the correct library that corresponds to the required version number, the code now works well.</p>
93097
|arduino-uno|interrupt|
Why NEC IR remote control decoder does not work
2023-05-06T08:57:47.730
<p>I need to recognize a signal from an IR remote, not to use a library for working with IR remotes/receivers. How can when the button is clicked to display its name. I have PIC12F615 microcontroller with this code: <a href="https://github.com/circuitvalley/IR-Remote-Control/blob/master/NEC%20IR%20Transmitter%20Remote/main.c" rel="nofollow noreferrer">code</a> and 5 buttons connected to him and I need recognise which button pressed. Why NEC IR remote control decoder does not work, it doesn't set nec_ok to true.If output nec_state to the terminal, I get 0 1 0 1 0 1 and so on.</p> <pre><code> boolean nec_ok = 0; byte i, nec_state = 0, command, inv_command; unsigned int address; unsigned long nec_code; void setup() { Serial.begin(9600); // Timer1 module configuration TCCR1A = 0; TCCR1B = 0; // Disable Timer1 module TCNT1 = 0; // Set Timer1 preload value to 0 (reset) TIMSK1 = 1; // enable Timer1 overflow interrupt attachInterrupt(digitalPinToInterrupt(2), remote_read, CHANGE); // Enable external interrupt (INT0) } void remote_read() { unsigned int timer_value; if(nec_state != 0){ timer_value = TCNT1; // Store Timer1 value TCNT1 = 0; // Reset Timer1 } switch(nec_state){ case 0 : // Start receiving IR data (we're at the beginning of 9ms pulse) TCNT1 = 0; // Reset Timer1 TCCR1B = 2; // Enable Timer1 module with 1/8 prescaler ( 2 ticks every 1 us) nec_state = 1; // Next state: end of 9ms pulse (start of 4.5ms space) i = 0; return; case 1 : // End of 9ms pulse if((timer_value &gt; 19000) || (timer_value &lt; 17000)){ // Invalid interval ==&gt; stop decoding and reset nec_state = 0; // Reset decoding process TCCR1B = 0; // Disable Timer1 module } else nec_state = 2; // Next state: end of 4.5ms space (start of 562µs pulse) return; case 2 : // End of 4.5ms space if((timer_value &gt; 10000) || (timer_value &lt; 8000)){ nec_state = 0; // Reset decoding process TCCR1B = 0; // Disable Timer1 module } else nec_state = 3; // Next state: end of 562µs pulse (start of 562µs or 1687µs space) return; case 3 : // End of 562µs pulse if((timer_value &gt; 1400) || (timer_value &lt; 800)){ // Invalid interval ==&gt; stop decoding and reset TCCR1B = 0; // Disable Timer1 module nec_state = 0; // Reset decoding process } else nec_state = 4; // Next state: end of 562µs or 1687µs space return; case 4 : // End of 562µs or 1687µs space if((timer_value &gt; 3600) || (timer_value &lt; 800)){ // Time interval invalid ==&gt; stop decoding TCCR1B = 0; // Disable Timer1 module nec_state = 0; // Reset decoding process return; } if( timer_value &gt; 2000) // If space width &gt; 1ms (short space) bitSet(nec_code, (31 - i)); // Write 1 to bit (31 - i) else // If space width &lt; 1ms (long space) bitClear(nec_code, (31 - i)); // Write 0 to bit (31 - i) i++; if(i &gt; 31){ // If all bits are received nec_ok = 1; // Decoding process OK detachInterrupt(0); // Disable external interrupt (INT0) return; } nec_state = 3; // Next state: end of 562µs pulse (start of 562µs or 1687µs space) } } ISR(TIMER1_OVF_vect) { // Timer1 interrupt service routine (ISR) nec_state = 0; // Reset decoding process TCCR1B = 0; // Disable Timer1 module } void loop() { Serial.println(nec_ok); if(nec_ok){ // If the mcu receives NEC message with successful nec_ok = 0; // Reset decoding process nec_state = 0; TCCR1B = 0; // Disable Timer1 module address = nec_code &gt;&gt; 16; command = nec_code &gt;&gt; 8; inv_command = nec_code; attachInterrupt(digitalPinToInterrupt(2), remote_read, CHANGE); // Enable external interrupt (INT0) } } </code></pre> <p>Schema: <a href="https://i.stack.imgur.com/Pf4Ik.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pf4Ik.jpg" alt="enter image description here" /></a></p>
<p>External interrupt version of NEC protocol decoder using micros() for timing instead of Timer 1. Drops NEC repeat codes, Otherwise, in the style of the code in the question.</p> <pre><code>volatile boolean nec_ok = 0; byte command, inv_command; volatile byte nec_state = 0 ; unsigned int address; volatile unsigned long nec_code; volatile uint32_t errFlag = 0 ; volatile uint32_t decodeStartAtMs = 0 ; void setup() { Serial.begin(9600); pinMode( 2, INPUT_PULLUP ) ; attachInterrupt(digitalPinToInterrupt(2), remote_read, CHANGE); // Enable external interrupt (INT0) } void remote_read() { static byte i = 0 ; static bool wasSpace; static unsigned long enteredAtUs = 0 ; static unsigned long pulseLengthLastUs ; wasSpace = ! digitalRead( 2 ) ; pulseLengthLastUs = micros() - enteredAtUs; // Calculate pulse length enteredAtUs = micros(); // Store current time for next entry switch (nec_state) { case 0 : // Wait here until 9ms pulse found ) if ( pulseLengthLastUs &gt; 8000 &amp;&amp; pulseLengthLastUs &lt; 10000 ) { // got a 9ms pulse decodeStartAtMs = millis() ; // for timeout nec_state = 1 ; nec_code = 0 ; i = 0 ; } break; case 1 : // handle 4.5ms space /* if ((pulseLengthLastUs &gt; 2000) &amp;&amp; (pulseLengthLastUs &lt; 2500)) { // silently drop repeat codes !!! nec_state = 0; // Reset decoding process } else */ if ((pulseLengthLastUs &gt; 5500) || (pulseLengthLastUs &lt; 3500)) { errFlag = 10000000 + pulseLengthLastUs ; nec_state = 0; // Reset decoding process } else nec_state = 2; // Next state: end of 562µs pulse (start of 562µs or 1687µs space) break; case 2 : // handle 562µs or 1687µs space if ((pulseLengthLastUs &gt; 1900) || (pulseLengthLastUs &lt; 400)) { // Time interval invalid ==&gt; stop decoding errFlag = 20000000 + pulseLengthLastUs ; nec_state = 0; // Reset decoding process break; } if ( wasSpace ) { // we are interested only in the space length if ( pulseLengthLastUs &gt; 1000) // If space width &gt; 1ms (short space) bitSet(nec_code, (31 - i)); // Write 1 to bit (31 - i) else // If space width &lt; 1ms (long space) bitClear(nec_code, (31 - i)); // Write 0 to bit (31 - i) i++; if (i &gt; 31) { // If all bits are received i = 0 ; nec_ok = 1; // Decoding process OK detachInterrupt(0); // Disable external interrupt (INT0) } } break; } } void loop() { if ( errFlag &gt; 0 ) { Serial.print( &quot;Error: &quot; ) ; Serial.println( errFlag ) ; errFlag = 0 ; } if ( nec_state &gt; 0 &amp;&amp; millis() - decodeStartAtMs &gt; 90 ) { Serial.println( &quot;Timeout&quot; ) ; nec_state = 0 ; } if (nec_ok) { Serial.print( &quot;Code received = &quot; ) ; Serial.println( nec_code, HEX ) ; address = (nec_code &gt;&gt; 16) &amp; 0xFF; // Extract address from received code inv_command = (nec_code &gt;&gt; 8) &amp; 0xFF; // Extract inverted command from received code command = nec_code &amp; 0xFF; // Extract command from received code if (command == ((~inv_command) &amp; 0xFF)) { // Verify command validity Serial.print(&quot;Received valid NEC code: &quot;); Serial.print(address, HEX); Serial.print(&quot;, &quot;); Serial.print(command, HEX); Serial.print(&quot;, &quot;); Serial.println(inv_command, HEX); } else { Serial.println(&quot;Received invalid NEC code!&quot;); } nec_ok = 0; // Reset decoding process nec_state = 0; // Reset decoding state attachInterrupt(digitalPinToInterrupt(2), remote_read, CHANGE); // Re-enable external interrupt (INT0) } } </code></pre> <p>This utility can be used to verify the output of an IR receiver showing the timings of the pulses and spaces to 4us resolution.</p> <pre><code>// protocol analyser utility // intended to dump timings to the serial console for example from demodulated NEC IR codes // Connect the IR receiver output to pin 2 const uint8_t DATA_SIZE = 100 ; struct intervalRead_t { uint32_t durationUs ; bool space ; } ; intervalRead_t intervalRead[ DATA_SIZE ] ; volatile unsigned long enteredAtUs = 0 ; volatile uint8_t index = 0 ; volatile bool firstPulse = true ; void saveTimes() { bool wasSpace; uint32_t pulseLengthLastUs ; wasSpace = ! digitalRead( 2 ) ; pulseLengthLastUs = micros() - enteredAtUs; // Calculate pulse length enteredAtUs = micros(); // Store current time for next entry if ( firstPulse ) { firstPulse = false ; index = 0 ; } else { if ( index &lt; DATA_SIZE ) { intervalRead[ index ].durationUs = pulseLengthLastUs ; intervalRead[ index ].space = wasSpace ; index++ ; } } } void setup() { Serial.begin(9600); pinMode( 2, INPUT_PULLUP ) ; attachInterrupt(digitalPinToInterrupt(2), saveTimes, CHANGE); // Enable external interrupt (INT0) } void loop() { if ( !firstPulse &amp;&amp; micros() - enteredAtUs &gt; 500000UL ) { for ( uint8_t i = 0; i &lt; index ; i++ ) { Serial.print( i ) ; Serial.print( &quot;\tinterval= &quot; ) ; Serial.print( intervalRead[ i ].durationUs ) ; Serial.print( &quot;us \t&quot;) ; Serial.print( intervalRead[ i ].space ? &quot;space&quot; : &quot;pulse&quot; ) ; Serial.println( ) ; } Serial.println( ) ; firstPulse = true ; } } </code></pre>
93099
|linker|io-expander|
override pinMode, digitalWrite and digitalRead
2023-05-06T11:24:59.270
<p>I am using the <a href="https://github.com/espressif/arduino-esp32" rel="nofollow noreferrer">ESP32 Arduino Framework</a> and I have some <a href="https://www.ti.com/product/TCA6408A" rel="nofollow noreferrer">GPIO expanders</a> attached via I²C. They work fine and I now want to map some unused pin numbers to them so I can used my custom pin numbers in <code>pinMode</code>, <code>digitalRead</code> and <code>digitalWrite</code>.</p> <p>Luckily, <a href="https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/esp32-hal-gpio.c#L228" rel="nofollow noreferrer">the Arduino core links these functions weakly</a>.</p> <pre class="lang-cpp prettyprint-override"><code>extern void pinMode(uint8_t pin, uint8_t mode) __attribute__ ((weak, alias(&quot;__pinMode&quot;))); </code></pre> <p>I defined my own functions like so:</p> <pre class="lang-cpp prettyprint-override"><code>void pinMode(uint8_t pin, uint8_t mode) { if(pin&lt;0x80) // call conventional handler else // communicate with GPIO expander via I²C } </code></pre> <p>Unfortunately, calling any of the functions will not result in the linker picking my implementation but the linker picks the default implementation.</p> <p>Any ideas how to override the weakly linked <code>pinMode</code>, <code>digitalWrite</code> and <code>digitalRead</code>?</p>
<p>I found the issue: I ran <code>platformio run --target clean</code> instead of <code>platformio run --target cleanall</code>. It seems that only the latter command cleans all build artifacts. The next time I compiled and uploaded, it worked as expected.</p> <p>Another issue occurs only with Adafruit libraries: Some libraries do not use <code>uint8_t</code> for ports but <code>int8_t</code> and they do checks like</p> <pre class="lang-cpp prettyprint-override"><code>if(pin_number &gt;=0) { // code that only works with pin numbers between 0x01 and 0x80 } </code></pre> <p>Take the <a href="https://github.com/adafruit/Adafruit-GFX-Library/blob/5ea4be3ffeae918899aeec8cbb67f87359cf0026/Adafruit_SPITFT.cpp#L533" rel="nofollow noreferrer">Adafruit GFX library</a> as an example. As a workaround, I will map my GPIO expander ports to 0x40, 0x41, ...</p>
93100
|arduino-uno|motor|
timing changes once DC motors are connected to power
2023-05-06T14:39:38.857
<p>I'm using an arduino uno with two DC motors. I'm also using the built in LED to tell me when the motors should be on as a debug tool. The code is a simple while loop that turns both the motors and the LED on for 10 seconds, and off for 5, and repeat, while a witch is on. This works fine when the motors are not connected to power (when the switch is on, the LED turns on for 10 secs, off for 5 and repeat), but when the motor driver is connected to the power the timing is changed. The motors and the LED are on for less than a second, and off for 5. the &quot;on&quot; period changes a bit, once it even reached the intended 10 seconds.</p> <p>Why is that and how do I fix that? I tried changing batteries (though i don't know how that might change things, as the led is also working incorrectly and it works of a seperate power source).</p> <p>the Arduino is connected to a 9V battery and the motors are connected to 4 AA batteries through a L298N motor driver.</p> <p>this is my code:</p> <pre><code>#include &lt;Arduino.h&gt; int RightSpeedPin = 5; int Rdir2 = 6; int Rdir1 = 7; int led = 13; int LeftSpeedPin = 10; int Ldir2 = 8; int Ldir1 = 9; int SwitchPin = 4; int ReadVal; void setup() { // put your setup code here, to run once: pinMode(Rdir1, OUTPUT); pinMode(Rdir2, OUTPUT); pinMode(RightSpeedPin, OUTPUT); pinMode(LeftSpeedPin, OUTPUT); pinMode(Ldir1, OUTPUT); pinMode(Ldir2, OUTPUT); pinMode(SwitchPin, INPUT); pinMode(led, OUTPUT); } void loop() { ReadVal = digitalRead(SwitchPin); while (ReadVal == 1) { digitalWrite(led, HIGH); // starting situation- both motors heading forward // running for 10 secs digitalWrite(Rdir1, HIGH); digitalWrite(Ldir1, HIGH); digitalWrite(Rdir2, LOW); digitalWrite(Ldir2, LOW); analogWrite(RightSpeedPin, 255); analogWrite(LeftSpeedPin, 255); delay(10000); // off for 5 analogWrite(RightSpeedPin, 0); analogWrite(LeftSpeedPin, 0); digitalWrite(led, LOW); ReadVal = digitalRead(SwitchPin); delay(5000); } } </code></pre> <p><a href="https://crcit.net/c/58642dd9da3d41948a9847bb69c874b9" rel="nofollow noreferrer">link to the schematics</a>. its rough, I'm not very experienced at drawing schematics. Note that all the ground wires are connected to a breadboard ground rail other that the 9V that powers the arduino. its connected with a round plug, so i don't have individual wires. EDIT: fixed the schematic <a href="https://i.stack.imgur.com/eBwSk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eBwSk.png" alt="circuit" /></a></p>
<p>After debugging by printing:</p> <pre><code>sTime = millis(); analogWrite(RightSpeedPin, 255); analogWrite(LeftSpeedPin, 255); delay(5000); analogWrite(RightSpeedPin, 0); analogWrite(LeftSpeedPin, 0); Serial.print(millis() - stime); </code></pre> <p>I got times that are less than 300 ms, and no reset (added print to setup). I still have no idea why. after that, I just replaced delay with <code>while (millis() &lt; Stime + t) {</code> which solved my problem.</p>
93111
|esp32|sound|
How to configure I2S with ESP32 and MAX98357A to reproduce wav files?
2023-05-07T16:36:55.033
<p>I have configured I2S to reproduce files with an ESP32 and a MAX98357A from and SD card. The problem is that it reproduces the files way too fast, like they are sped up * 100. Here is my (simplified) code:</p> <pre class="lang-cpp prettyprint-override"><code>#define I2S_DOUT 25 #define I2S_BCLK 27 #define I2S_LRC 26 void setup() { // Start SD card and sqlite SPI.begin(); if (!SD.begin()) { Serial.println(&quot;SD card not found&quot;); while (1) {}; } // Configure I2S i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX), .sample_rate = 44100, .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, .communication_format = I2S_COMM_FORMAT_I2S_MSB, .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, .dma_buf_count = 2, .dma_buf_len = 1024, .tx_desc_auto_clear = true, }; i2s_pin_config_t pin_config = { .bck_io_num = I2S_BCLK, .ws_io_num = I2S_LRC, .data_out_num = I2S_DOUT, .data_in_num = -1, }; i2s_driver_install(I2S_NUM_0, &amp;i2s_config, 0, NULL); i2s_set_pin(I2S_NUM_0, &amp;pin_config); i2s_set_dac_mode(I2S_DAC_CHANNEL_RIGHT_EN); i2s_set_sample_rates(I2S_NUM_0, 44100); } void loop() { // Play the audio file string filename = &quot;/audios/&quot; + text + &quot;.wav&quot;; File file = SD.open(filename.c_str()); if (!file) { Serial.println(&quot;Failed to open file for reading&quot;); return; } const size_t buffer_size = 512; uint8_t buffer[buffer_size]; size_t bytes_read; size_t bytes_written; while (file.available() &amp;&amp; (bytes_read = file.read(buffer, buffer_size)) &gt; 0) { i2s_write(I2S_NUM_0, buffer, bytes_read, &amp;bytes_written, portMAX_DELAY); if (bytes_read == 0) break; } file.close(); } </code></pre> <p>How do I configure it correctly?</p>
<p>So I figured it out (a somewhat long time ago) but forgot to post here hahaha.</p> <p>Basically, the <code>i2s_config_t</code> was not properly configured. Here's a corrected version:</p> <pre class="lang-cpp prettyprint-override"><code>i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX), .sample_rate = 44100, .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, .communication_format = I2S_COMM_FORMAT_I2S_MSB, .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, .dma_buf_count = 8, .dma_buf_len = 1024, .use_apll = false, .tx_desc_auto_clear = true, }; </code></pre> <p>If you compare, the <code>.channel_format</code> configuration changes from <code>I2S_CHANNEL_FMT_RIGHT_LEFT</code> to <code>I2S_CHANNEL_FMT_ONLY_LEFT</code>. This is important because when using <code>RIGHT_LEFT</code> and only using one amplifier, 2 sound outputs were sent but only one amp was receiving them, causing the sound to play at twice the speed. Now, the <code>.dma_buf_count</code> was increased to 8, and added the <code>.use_apll</code> config, because I saw it somewhere else, I don't really know what it does hahaha.</p> <p>There are other things.<br /> In the setup for the i2s communication, I didn't include</p> <pre class="lang-cpp prettyprint-override"><code>i2s_set_dac_mode(I2S_DAC_CHANNEL_RIGHT_EN); i2s_set_sample_rates(I2S_NUM_0, 44100); </code></pre> <p>And created a new function, <code>play_sound</code>.</p> <p>Here's the complete code:</p> <pre class="lang-cpp prettyprint-override"><code>// sound.cpp #include &lt;sound.h&gt; bool parseWavHeader(File &amp;file, WavHeader &amp;header) { if (file.read() != 'R' || file.read() != 'I' || file.read() != 'F' || file.read() != 'F') { Serial.println(&quot;Invalid WAV file&quot;); return false; } file.seek(22); header.num_channels = file.read() | (file.read() &lt;&lt; 8); header.sample_rate = file.read() | (file.read() &lt;&lt; 8) | (file.read() &lt;&lt; 16) | (file.read() &lt;&lt; 24); file.seek(34); header.bits_per_sample = file.read() | (file.read() &lt;&lt; 8); file.seek(44); // Skip to the audio data return true; } void setup_sound() { i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX), .sample_rate = 44100, .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, .communication_format = I2S_COMM_FORMAT_I2S_MSB, .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, .dma_buf_count = 8, .dma_buf_len = 1024, .use_apll = false, .tx_desc_auto_clear = true, }; i2s_pin_config_t pin_config = { .bck_io_num = I2S_BCLK, .ws_io_num = I2S_LRC, .data_out_num = I2S_DOUT, .data_in_num = -1, }; i2s_driver_install(I2S_NUM_0, &amp;i2s_config, 0, NULL); i2s_set_pin(I2S_NUM_0, &amp;pin_config); } void play_sound(std::string text, fs::FS &amp;SD) { std::string filename = &quot;/audios/&quot; + text + &quot;.wav&quot;; File file = SD.open(filename.c_str()); if (!file) { Serial.println(&quot;Failed to open file for reading&quot;); while (1) delay(1); } WavHeader header; if (!parseWavHeader(file, header)) { Serial.println(&quot;Invalid WAV file&quot;); return; } i2s_set_sample_rates(I2S_NUM_0, header.sample_rate); const size_t buffer_size = 512; uint8_t buffer[buffer_size]; size_t bytes_read; size_t bytes_written; while (file.available() &amp;&amp; (bytes_read = file.read(buffer, buffer_size)) &gt; 0) { i2s_write(I2S_NUM_0, buffer, bytes_read, &amp;bytes_written, portMAX_DELAY); if (bytes_read == 0) break; } file.close(); } </code></pre> <pre class="lang-cpp prettyprint-override"><code>// sound.h #ifndef SOUND_H #define SOUND_H #include &lt;SD.h&gt; #include &lt;driver/i2s.h&gt; #define I2S_DOUT 25 #define I2S_BCLK 33 #define I2S_LRC 26 struct WavHeader { uint32_t sample_rate; uint16_t bits_per_sample; uint16_t num_channels; }; bool parseWavHeader(File &amp;file, WavHeader &amp;header); void setup_sound(); void play_sound(std::string text, fs::FS &amp;SD); #endif // SOUND_H </code></pre> <p>Hope it helps you not go through the struggle I went through!</p>
93117
|adc|potentiometer|filter|
Avoid 1-LSB noise on ADC readings
2023-05-08T17:29:29.580
<p>I have a potentiometer connected to an ADC input of an Arduino Leonardo. The ADC resolution is 10-bit (0..1024), while I need just 7-bit (0..127).</p> <p>I use a simple filter to reduce the noise and then a <code>map</code> to cut the unused bits:</p> <pre><code>#define ADC_CH 18 #define ADC_FILTER 0.90 uint16_t value; uint16_t adc = analogRead(ADC_CH); value = (uint16_t) ((float) ADC_FILTER * adc + (1. - ADC_FILTER) * value); </code></pre> <p>I show <code>value</code> on an LCD. It's very stable, but it may happen that if the adc readings are in the nearby of two values, there is nothing that could prevent a change in the final value, even if the noise is of just few LSBs.</p> <p>Is there a simple way to implement an hysteresis for each low-res value?</p> <p>In this way the change between N and N+1 happens on a different ADC reading than between N and N-1, improving the noise rejection without increasing the filter delay (that would only increase the change interval).</p>
<p>When you reduce the resolution from 10 bits to 7 bits, every possible output corresponds to an interval of inputs. If you add some hysteresis, then those intervals should overlap. Below is a representation of the input intervals corresponding to outputs 0, 1,… 6, for an hysteresis width of 4:</p> <pre><code>input: 0 5 10 15 20 25 30 35 40 45 50 55 60 └────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴ ├─────0────┤ ├───────1──────┤ ├───────2──────┤ ├───────3──────┤ ├───────4──────┤ ├───────5──────┤ ├───────6──────┤ </code></pre> <p>To implement this in code, you have to remember the last output, and change it only if the input lies outside the interval assigned to this output. Here is an example implementation:</p> <pre class="lang-cpp prettyprint-override"><code>const int hysteresis = 4; // tune to taste /* Remove 3 bits of resolution while adding some hysteresis. */ int resample(int adc) { static int value; // last output if (adc &lt; (value&lt;&lt;3) - hysteresis) { value = (adc + hysteresis) &gt;&gt; 3; } else if (adc &gt;= ((value+1)&lt;&lt;3) + hysteresis) { value = (adc - hysteresis) &gt;&gt; 3; } return value; } </code></pre> <p>Note that a <code>static</code> local variable keeps its value between successive calls to the function.</p>
93148
|arduino-uno|
How can I observe the "voltage dips" the starter kit talks about in Project 5?
2023-05-12T20:57:27.590
<p>Project 5 of the Arduino Starter Kit <a href="https://www.uio.no/studier/emner/matnat/ifi/IN1060/v21/arduino/arduino-projects-book.pdf" rel="nofollow noreferrer">book</a> (page 63) involves wiring up a potentiometer to control a servomotor (see diagram). The book also recommends wiring up decoupling capacitors as shown in the diagram:</p> <blockquote> <p>When a servo motor starts to move, it draws more current than if it were already in motion. This will cause a dip in the voltage on your board. By placing a 100uf capacitor across power and ground right next to the male headers as shown in Fig. 1, you can smooth out any voltage changes that may occur. You can also place a capacitor across the power and ground going into your potentiometer.</p> </blockquote> <p>Since the book doesn't explicitly warn against it, I decided to do this whole project without the capacitors just to see what would happen. It seemed to work fine, I didn't notice any erratic behavior. Is there some experiment I could do to actually measure these voltage &quot;dips&quot;?</p> <p>I thought maybe I could try to measure the voltage drop across the servo, so I wired it in series with a resistor and connected the A0 ADC pin between the servo and the resistor. I did measure a drop, but the servo didn't work... I'm guessing it wasn't getting enough power because of the resistor?</p> <p><a href="https://i.stack.imgur.com/Gimeu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gimeu.png" alt="enter image description here" /></a></p>
<blockquote> <p>I'm guessing it wasn't getting enough power because of the resistor?</p> </blockquote> <p>Yes, that is probably what happened (you didn't specify what value your resistor had). When the servo tries to draw more current, more current has to flow through the resistor. This means more voltage over the resistor and less for the servo, which then doesn't have enough to to powerful or even run at all (depending on the resistors value).</p> <blockquote> <p>Is there some experiment I could do to actually measure these voltage &quot;dips&quot;?</p> </blockquote> <p>You tried to measure the dips with the Arduino. Since the servo is connected directly to the 5V line of the Arduino, so its own Vcc, you cannot measure it the same way as the potentiometer. By default <code>analogRead()</code> uses Vcc as reference, meaning the max value. Instead you can configure it to use the internal 1.1V fixed reference (which doesn't depend on Vcc)(refer to <a href="https://reference.arduino.cc/reference/en/language/functions/analog-io/analogreference/" rel="nofollow noreferrer"><code>analogReference()</code></a>) and divide down Vcc with a fixed voltage divider (so that the voltage on the analog input pin would not exceed 1.1V).</p> <p>Though to see the dips you still would need to measure the data points fast enough to catch them. Without knowing how long the dips might be it is difficult to say, if you can easily catch them. There are ways to do analog measurements relatively fast, but for a beginner (and specifically for a beginner book) that is a bit much.</p> <p>The easier, but also more expensive solution (in terms of tools) is to measure Vcc with an oscilloscope. As entry a USB oscilloscope might be fitting (in the range of maybe 50$). If you don't wanna buy, you might be able to get access to one at the next makerspace or university. Some schools also might have some oscilloscopes.</p> <blockquote> <p>Since the book doesn't explicitly warn against it, I decided to do this whole project without the capacitors just to see what would happen. It seemed to work fine</p> </blockquote> <p>Dips in your supplied voltage might cause the Arduino to reset. But that only happens, when the dip is too big. And that depends on multiple factors:</p> <ul> <li>How much current can be drawn from your power supply. USB ports on a PC won't give you more than 500mA for example. And some battery types have a big series resistance, meaning that the voltage will drop significantly, when you draw too much current from them.</li> <li>Sometimes, when working on a breadboard, the contacts might also have a significant resistance to them. This can lead to a voltage loss there.</li> <li>How strong the motor is. In starter kits you typically have these cheap and small SG90 micro servos. These don't draw a lot of power generally and are not really strong.</li> <li>How much load is on the motor. A motor draws different amounts of current depending on its load. When it runs feely the currently is the smallest. When its starting, then it needs to fight against its own inertia, thus needing more current. The most current is used, when the motor stalls, because it is not powerful enough to push against the load.</li> </ul> <p>The last two points affect the motor current, which might cause a voltage dip, if the power supply cannot provide that much current with the specified voltage.</p> <p>The capacitors are a precaution in this case. I think the author wanted to explain this to make sure that it would work for everyone and that students would already know about this, when moving to bigger, more power hungry projects.</p>
93179
|adc|mathematics|filter|
Hysteresis and scaling range
2023-05-15T09:15:40.513
<p><a href="https://arduino.stackexchange.com/q/93117/54202">Here</a> I asked about how to add an hysteresis on ADC readings. The answer received was very good and it worked out of the box.</p> <p>Still I'm having troubles trying to generalize the <code>resample</code> function in order to map the input values to a different range of output values, where the lower rail is <strong>not</strong> zero.</p> <p>If the lower rail was zero, it would be enough to change the shifts with a multiplication/division for <code>1024 / max</code>. But I cannot understand how to handle the lower rail when <code>min &gt; 0</code>.</p> <p>My attempt:</p> <pre><code>int Menu::resample(int adc, int *value, byte min, byte max) { // sanity checks omitted: min &lt; max and max &lt; 128 double m = 1015.0 / (max - min); // 1015 = 1023 - 8 (1 LSB of low-res output) // otherwise it reaches 126 even if max = 127 int q = min &lt;&lt; 3; int lowerTest = (q + *value * m) - ADC_HYSTERESIS; int higherTest = (q + (*value + 1) * m) + ADC_HYSTERESIS; int lowerOutput = min + (adc + ADC_HYSTERESIS) / m; int higherOutput = min + (adc - ADC_HYSTERESIS) / m; if (adc &lt; lowerTest) *value = lowerOutput; else if (adc &gt;= higherTest) *value = higherOutput; if (*value &gt; max) *value = max; if (*value &lt; min) *value = min; return *value; } </code></pre> <p>There is something wrong in my math, since the comparison always falls under the first <code>if</code> (i.e. <code>*value = lowerOutput</code>).</p> <p>May you help me to fix this code so I can have an hysteresis on any scaled output?</p> <p><strong>Note</strong>: instead of using a static variable for value as in the answer, I use a <code>struct</code>:</p> <pre><code>slider.value = resample(adc, &amp;slider.lastValue, slider.min, slider.max); </code></pre> <p>where:</p> <pre><code>typedef struct { int value; int lastValue; int min; int max; } slider_t; slider_t slider; </code></pre>
<p>First, a couple of comments about this first attempt.</p> <p>There is no point in storing in <code>slider_t</code> both <code>lastValue</code> and <code>value</code>. The way this is used, both fields are always updated with the same value: <code>lastValue</code> is updated by pointer inside <code>resample()</code>, while <code>value</code> is updated by assigning it the value returned by <code>resample()</code>. I would suggest removing the field <code>lastValue</code> and either:</p> <ol> <li><p>providing <code>value</code> by value (rather than by pointer) to <code>resample()</code>, or</p> </li> <li><p>providing a reference to a <code>slider_t</code> as the only parameter.</p> </li> </ol> <p>The first approach is better if you want to avoid <code>resample()</code> and <code>slider_t</code> being tightly coupled.</p> <p>Next, there is a mix between <code>int</code> and <code>byte</code> types. If you want to save memory, and improve consistency, I would use <code>byte</code> for all low-res values living in the output domain of <code>resample()</code>. Actually, I would use <code>uint8_t</code>, which is the same, only more standard.</p> <p>Then, there are a few things I do not understand in this code:</p> <ul> <li><p>Why <code>1015</code>? It seems to me this number should be dependent on the width of output range.</p> </li> <li><p>Why <code>min &lt;&lt; 3</code>? Again, this is a division by 8, while the proper factor should be probably be output-range dependent.</p> </li> </ul> <p>Now, for the solution, I would try this approach:</p> <ul> <li><p>Compute the minimum and maximum possible output values consistent with the provided input, accounting for the hysteresis.</p> </li> <li><p>Constrain the output to remain within this bracket.</p> </li> </ul> <p>In code:</p> <pre class="lang-cpp prettyprint-override"><code>uint8_t Menu::resample(int adc, uint8_t value, uint8_t min, uint8_t max) { value = constrain(value, min, max); // just in case... uint8_t lower = map(adc - ADC_HYSTERESIS, 0, 1024, min, max+1); uint8_t upper = map(adc + ADC_HYSTERESIS, 0, 1024, min, max+1); return constrain(value, lower, upper); } </code></pre> <p>Some points worth noticing:</p> <ol> <li><p>I do not know whether this was originally intended, but the Arduino function <code>map(x, in_min, in_max, out_min, out_max)</code> does a poor job at mapping the interval [<code>in_min</code>, <code>in_max</code>] to [<code>out_min</code>, <code>out_max</code>]. It does, however, do a good job at mapping [<code>in_min</code>, <code>in_max</code>) to [<code>out_min</code>, <code>out_max</code>) (mind the semi-open intervals). This is why the four last parameters of the call to <code>map()</code> are (0, 1024, min, max+1), rather than (0, 1023, min, max).</p> </li> <li><p>The first call to <code>constrain()</code> can be removed if the caller bears the responsibility of guaranteeing this precondition.</p> </li> <li><p>If the precondition is valid (or, like here, enforced), it will also hold for the returned value, provided <code>adc</code> is within [0, 1024).</p> </li> </ol> <p>This method would be called like this:</p> <pre class="lang-cpp prettyprint-override"><code>slider.value = resample(adc, slider.value, slider.min, slider.max); </code></pre>
93192
|arduino-mega|voltage-level|code-review|
Pin outping 1V instead of expected 5V, not hardware related
2023-05-17T10:01:01.363
<p>Heyo everyone !</p> <p>I'm in a project where I need to send a signal if I detect vaccuum. I'm sending the signal on PIN 9 but I soon realized that I was only getting 1V.</p> <p>Tought I was alternating between signal/no_signal but the log provided me with constant and consistent values.</p> <p>Then I started doubting about my board so I made PIN 10 always output. Under the same load as PIN 9 (I switch the cable connecting from PIN 9 to the circuit, to PIN 10 to the circuit ), I get a good 5V. Thus, I exclude any load problem.</p> <p>Regarding the PIN output issue, you can all see that it's not missing.</p> <p>My last hypothesis is that there's some sort of sorcery with my code that I don't know and couln't find on the internet...</p> <p>Any idea on what might be going on ?</p> <pre><code>// Constant const int BL1 = 9;// BINARY LED 1 pin const int TEST = 10;// BINARY LED 1 pin const int AP = A0;// ANALOG PRESSOSTAT pin const int P = 85;// TRIGGER PRESSURE value // Variables int LS1 = LOW; // LED 1 STATE float RPV = 1; // Raw Pressostat Voltage (0-1024) float PV = 1; // Pressostat Voltage (V) float PDP = 20; // Pressostat Deduced Pressure (kPa) // Initialization of pins at startup void setup() { pinMode(AP, INPUT); // ANALOG PRESSOSTAT pin set as INPUT pinMode(BL1, OUTPUT);// BINARY LED 1 pin set as OUTPUT pinMode(TEST, OUTPUT);// BINARY LED 1 pin set as OUTPUT pinMode(LED_BUILTIN, OUTPUT);// LED_BUILTIN pin set as OUTPUT Serial.begin(9600); } void loop() { digitalWrite(TEST, HIGH); RPV = analogRead(AP); PV = (RPV/1024)*5; PDP = (-1)*(PV-1)*(-101/4); Serial.print(&quot;Pression: &quot;); Serial.print(PDP); if ( PDP &gt; P ){ int LS1 = HIGH; // LED 1 STATE digitalWrite(BL1, HIGH); digitalWrite(LED_BUILTIN, HIGH); Serial.print(&quot; | LED: 1&quot;); } else { int LS1 = LOW; // LED 1 STATE digitalWrite(BL1, LOW); digitalWrite(LED_BUILTIN, LOW); Serial.print(&quot; | LED: 0&quot;); } digitalWrite(BL1, LS1); Serial.print(&quot; | Trigger: &quot;); Serial.println(P); } </code></pre>
<p>I'll reduce it a little</p> <pre><code>void loop() { // ... doesn't matter if ( PDP &gt; P ){ int LS1 = HIGH; // shadows global variable (creates local variable that won't exist after }) digitalWrite(BL1, HIGH); } else { int LS1 = LOW; // again shadows global variable digitalWrite(BL1, LOW); } digitalWrite(BL1, LS1); // LS1 is still LOW } </code></pre> <p>Mistery solved</p>
93198
|serial|arduino-zero|
Maduino (Arduino Zero) at91samd21g18 - Unable to connect to the serial port
2023-05-17T23:39:20.780
<p>I have been using this device very little but it was use to work, and it also gave me the same issue in the past, the somewhat I was able to upload again.</p> <p>I tried to use the reset button, and short GRD with RST pins, but nothing helped. The device is recognised as <strong>Arduino MRK1000</strong> and connected. I also tried to specify <strong>Arduino Zero (Native USB Port)</strong>. <em>Under Tools &gt; Get Board</em> Info I get:</p> <pre><code>BN: Arduino MKR1000 VID 0x2341 PID: 0X804E SN: 414C4E1[...] </code></pre> <p><strong>My issue:</strong><br /> When I try to upload the sketch (even empty) it hangs forever, or some times it shows the same message shown when you unplug the device while uploading.</p> <pre><code>No device found on COM5 Failed uploading: uploading error: exit status 1 </code></pre> <p>The serial monitor is unable to connect</p> <pre><code>Sketch uses 33108 bytes (12%) of program storage space. Maximum is 262144 bytes. Global variables use 3552 bytes (10%) of dynamic memory, leaving 29216 bytes for local variables. Maximum is 32768 bytes. No device found on COM5 Failed uploading: uploading error: exit status 1 </code></pre> <p><strong>Attempted resolution actions:</strong><br /> I tried to use the reset button, and short GRD with RST pins, but nothing helped. I tried multiple USB ports, different PC, different cable.</p> <p><strong>For information about the device:</strong><br /> <a href="https://github.com/Makerfabs/Maduino-Zero-4G-LTE" rel="nofollow noreferrer">https://github.com/Makerfabs/Maduino-Zero-4G-LTE</a> <a href="https://wiki.makerfabs.com/Maduino_Zero_4G_LTE.html" rel="nofollow noreferrer">https://wiki.makerfabs.com/Maduino_Zero_4G_LTE.html</a></p> <p><strong>Requests:</strong><br /> If you could guide me, maybe I can try to &quot;factory reset&quot; the MCU, or maybe try to connect in a different way.<br /> I read about the bootloaders but I don't know how they work and I don't want to try alone and make worse.<br /> The manufacturer didn't reply to my messages,on GitHub I didn't receive any reply either, so this is one last attempt before I throw this into the bin.<br /> If anyone can recommend al alternative board with GPS and LTE/4G connectivity would be a plus.</p>
<p>As suggested by Juraj (thank you), <strong>pushing the reset button twice</strong> allowed me to upload an empty sketch and &quot;revive&quot; an otherwise unusable device.</p>
93214
|eeprom|loop|struct|
manage some output based on some parameter and rtc
2023-05-19T15:49:08.773
<p>i'm trying to create a program that given a configuration (i've used multiple struct nested) i need in loop() to check for each output if they need to be on or off and set the output accordingly</p> <p>let me explain the configuration (i'm not sure that this is the best way to make and store this config, suggestions are appreciated)</p> <pre><code>struct Period { String name; String type; String value; }; struct State { String name; Period periods[2]; }; struct Output { String name; int pin; int forcePin; State states[2]; }; Output outputs[4]; </code></pre> <p>now i populate the first object (this is something that need to be editable by the user and i was thinking to store it in the EEPROM, for now in the setup() i do this</p> <pre><code> outputs[0].name = &quot;OUTPUT 1&quot;; outputs[0].pin = 27; outputs[0].forcePin = 25; outputs[0].states[1].name = &quot;STATE 1&quot;; outputs[0].states[1].periods[0].name = &quot;day&quot;; outputs[0].states[1].periods[0].type = &quot;BOOL&quot;; outputs[0].states[1].periods[0].value = &quot;ON&quot;; outputs[0].states[1].periods[1].name = &quot;night&quot;; outputs[0].states[1].periods[1].type = &quot;BOOL&quot;; outputs[0].states[1].periods[1].value = &quot;OFF&quot;; outputs[0].states[0].name = &quot;STATE 2&quot;; outputs[0].states[0].periods[0].name = &quot;day&quot;; outputs[0].states[0].periods[0].type = &quot;BOOL&quot;; outputs[0].states[0].periods[0].value = &quot;ON&quot;; outputs[0].states[0].periods[1].name = &quot;night&quot;; outputs[0].states[0].periods[1].type = &quot;BOOL&quot;; outputs[0].states[0].periods[1].value = &quot;OFF&quot;; </code></pre> <p>then in the loop i have few function that determinate the state and period and i call this function that should manage all the outputs globalState in loop read from an input and set the variable globalPeriod check the time and set if night or day</p> <pre><code>void manageOutputs() { for (Output out : outputs) { Serial.println(out.name); Serial.println(out.pin); Serial.println(out.forcePin); if (digitalRead(out.forcePin) == LOW) { Serial.println(&quot;forced on set output&quot;); digitalWrite(out.pin, HIGH) continue; } Serial.println(out.states[globalState].name); Serial.println(out.states[globalState].periods[globalPeriod].name); Serial.println(out.states[globalState].periods[globalPeriod].type); Serial.println(out.states[globalState].periods[globalPeriod].value); if (out.states[globalState].periods[globalPeriod].type.equals(&quot;BOOL&quot;)) { if (out.states[globalState].periods[globalPeriod].value.equals(&quot;ON&quot;)) { digitalWrite(out.pin,HIGH); } else { digitalWrite(out.pin,LOW); } } } } </code></pre> <p>i have multiple type of output in mind for example TIMER (so in the value field i would have some parameter to call another function that will alternate the output on and off for the time given) will have something like &quot;15:10&quot; so it will stay 15 minutes on and 10 minutes off, or a condition (for example if VAR1 &gt; 50) so the field value would have &quot;VAR1:&gt;:50&quot; so it will turn on only if the condition is met. So i will have a switch case where now i check if BOOL.</p> <p>now that i hope that i have explained the situation, i would like to know if it's a good way to have 3 nested struct or if there is a better solution considering the necessity to have it stored in EEPROM, and if this is a good way to have this kind of condition like this or if there is a better way. Considering also that in the future i would like to make a webpage or an api to update this kind of configuration from a pc (maybe using a esp-8266 for that, that is also connected to the arduino, or do everything with an esp32, but i would like first to have the basic loop working and then i will make the &quot;UI&quot;)</p> <p>thanks a lot</p>
<p>There are many uses of the <code>String</code> class in these code snippets. Using strings is quite natural in some higher-level languages. On an Arduino, however, I would strongly advise you against this for two reasons:</p> <ol> <li><p>String objects use dynamic memory, which is not friendly to the small amount of RAM available on a typical Arduino.</p> </li> <li><p>Saving a String to EEPROM is not trivial: you do not want to save the String object (it contains a pointer that would not make sense in EEPROM context), and you instead have to save the character array it refers to. This could involve handling complex memory allocation withing the EEPROM.</p> </li> </ol> <p>Instead of a string meant to handle one of a predefined set of values (<code>&quot;BOOL&quot;</code>, <code>&quot;TIMER&quot;</code>, ...), use an <code>enum</code>. This is similar to an <code>int</code>, where each possible value has been given a name (<code>TYPE_BOOL</code> is 0, <code>TYPE_TIMER</code> is 1, ...). Instead of a string holding numbers, store the numbers themselves. In essence, you want to create a data storage format that is friendly to the binary nature of the CPU. If you really have to store strings, e.g. for names (are those <code>name</code> fields really useful? they do not look so in the provided example), limit their length and store them as fixed-size character arrays.</p> <p>The <code>period::value</code> field is interesting in that it can store different kinds of information depending on the <code>type</code> field. For such a situation the appropriate data structure is a <a href="https://en.wikipedia.org/wiki/Tagged_union" rel="nofollow noreferrer">discriminated union</a>. A <code>union</code> is like a <code>struct</code> except that all fields share the same memory space and only one can be valid at a time. In a discriminated union, the <code>union</code> is accompanied by a <code>ytpe</code> field that tells us which is the valid field.</p> <p>Applying those principles to your problem could give this kind of data structure:</p> <pre class="lang-cpp prettyprint-override"><code>// All the possible Period types. enum Type { TYPE_BOOL, TYPE_TIMER, // etc. }; // This is a discriminated union. struct Period { Type type; union { // one union member per possible type. bool bool_value; // valid when type == TYPE_BOOL struct { int on_time; int off_time; } timer_value; // valid when type == TYPE_TIMER // etc. }; }; struct State { Period periods[2]; }; struct Output { int pin; int forcePin; State states[2]; }; </code></pre> <p>These data structures can be trivially saved in EEPROM, as they are self-contained: they hold no pointers to data stored in dynamic memory.</p> <p>Then, in <code>manageOutputs()</code>, you will read a period's <code>bool_value</code> only when <code>type</code> is <code>TYPE_BOOL</code>, it's <code>timer_value</code> only when <code>type</code> is <code>TYPE_TIMER</code>, etc:</p> <pre class="lang-cpp prettyprint-override"><code>void manageOutputs() { for (Output out : outputs) { if (digitalRead(out.forcePin) == LOW) { digitalWrite(out.pin, HIGH); continue; } Period &amp;period = out.states[globalState].periods[globalPeriod]; switch (period.type) { case TYPE_BOOL: if (period.bool_value) { digitalWrite(out.pin, HIGH); } else { digitalWrite(out.pin, LOW); } break; case TYPE_TIMER: digitalWrite(out.pin, HIGH); delay(period.timer_value.on_time); digitalWrite(out.pin, LOW); delay(period.timer_value.off_time); } } } </code></pre>
93237
|esp8266|wifi|networking|
Mobile hotspot with wemos d1 mini
2023-05-22T11:07:47.920
<p>I recently got a wemos d1 mini and now am trying to connect it to my IPhone 13's hotspot, however it doesn't connect, I tried to run the wifiscan example - and it doesn't even detect it there.</p> <p>I tried connecting it to my home router - and this worked hence I have no ideas on fixing it, so any help would be appreciated!</p>
<p>By default the iPhone hotspot is 5GHz only, which is why your ESP8266 can't see it. The ESP8266's WiFi radio is 2.4GHz only.</p> <p>To enable 2.4GHz on the iPhone hotspot, turn on the &quot;Maximize Compatibility&quot; button under &quot;Settings | Personal Hotspot&quot;. Then 2.4GHz devices should be able to connect to the phone.</p> <p><a href="https://i.stack.imgur.com/OWQHj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OWQHj.png" alt="enter image description here" /></a></p>
93242
|library|adafruit|display|feather|
Having issues understanding what "#define GET_STATUS" does
2023-05-23T00:43:36.783
<p>I am trying to use a <a href="https://www.waveshare.com/wiki/4.2inch_e-Paper_Module" rel="nofollow noreferrer">Waveshare 4.2inch e-paper display</a> with an <a href="https://www.adafruit.com/product/2796" rel="nofollow noreferrer">Adafruit Feather Adalogger M0</a>, but am having issues with two separate instances of <code>#define GET_STATUS</code> being defined differently in different locations. More specifically, in the <a href="https://www.waveshare.com/w/upload/3/39/E-Paper_code.7z" rel="nofollow noreferrer">Demo Library (download)</a> for the Waveshare display, one of the files (epd4in2.h) defines GET_STATUS as 0x71. However, in a file (USBCore.h) I downloaded from the board manager in the ArduinoIDE to be able to support the Feather Adalogger, GET_STATUS is defined as 0.</p> <p>I've tried messing with the values to see if making them match (both as 0x71 and both as 0) would solve the issue, but it didn't change anything. I can't find any information about what GET_STATUS in general, so I'm unsure what I can even try to fix this issue. Furthermore, I can't find any instances of GET_STATUS being used, so I'm unsure what its significance even is. So, basically, my questions are: 1) what is the significance of GET_STATUS, and 2) how can I reconcile it being used differently in two different places?</p> <p>Below is the code I'm trying to run (it's the demo code from Waveshare), and the libraries other than &quot;&lt;SPI.h&gt;&quot; are in the demo library download from Waveshare.</p> <pre><code>#include &lt;SPI.h&gt; #include &quot;epd4in2.h&quot; #include &quot;imagedata.h&quot; #include &quot;epdpaint.h&quot; #define COLORED 0 #define UNCOLORED 1 void setup() { // put your setup code here, to run once: Serial.begin(9600); Epd epd; if (epd.Init() != 0) { Serial.print(&quot;e-Paper init failed&quot;); return; } /* This clears the SRAM of the e-paper display */ epd.ClearFrame(); /** * Due to RAM not enough in Arduino UNO, a frame buffer is not allowed. * In this case, a smaller image buffer is allocated and you have to * update a partial display several times. * 1 byte = 8 pixels, therefore you have to set 8*N pixels at a time. */ unsigned char image[1500]; Paint paint(image, 400, 28); //width should be the multiple of 8 paint.Clear(UNCOLORED); paint.DrawStringAt(0, 0, &quot;e-Paper Demo&quot;, &amp;Font24, COLORED); epd.SetPartialWindow(paint.GetImage(), 100, 40, paint.GetWidth(), paint.GetHeight()); paint.Clear(COLORED); paint.DrawStringAt(100, 2, &quot;Hello world&quot;, &amp;Font24, UNCOLORED); epd.SetPartialWindow(paint.GetImage(), 0, 64, paint.GetWidth(), paint.GetHeight()); paint.SetWidth(64); paint.SetHeight(64); paint.Clear(UNCOLORED); paint.DrawRectangle(0, 0, 40, 50, COLORED); paint.DrawLine(0, 0, 40, 50, COLORED); paint.DrawLine(40, 0, 0, 50, COLORED); epd.SetPartialWindow(paint.GetImage(), 72, 120, paint.GetWidth(), paint.GetHeight()); paint.Clear(UNCOLORED); paint.DrawCircle(32, 32, 30, COLORED); epd.SetPartialWindow(paint.GetImage(), 200, 120, paint.GetWidth(), paint.GetHeight()); paint.Clear(UNCOLORED); paint.DrawFilledRectangle(0, 0, 40, 50, COLORED); epd.SetPartialWindow(paint.GetImage(), 72, 200, paint.GetWidth(), paint.GetHeight()); paint.Clear(UNCOLORED); paint.DrawFilledCircle(32, 32, 30, COLORED); epd.SetPartialWindow(paint.GetImage(), 200, 200, paint.GetWidth(), paint.GetHeight()); /* This displays the data from the SRAM in e-Paper module */ epd.DisplayFrame(); /* This displays an image */ epd.DisplayFrame(IMAGE_BUTTERFLY); /* Deep sleep */ epd.Sleep(); } void loop() { // put your main code here, to run repeatedly: } </code></pre> <p>When I run the code, I get the following messages</p> <pre><code>In file included from /home/beingpool/Arduino/epd4in2-demo/epd4in2-demo.ino:28: /home/&lt;user&gt;/Arduino/libraries/epd4in2/epd4in2.h:64: warning: &quot;GET_STATUS&quot; redefined 64 | #define GET_STATUS 0x71 | In file included from /home/beingpool/.arduino15/packages/adafruit/hardware/samd/1.7.11/cores/arduino/Arduino.h:157, from /home/beingpool/.var/app/cc.arduino.IDE2/cache/arduino/sketches/96EFEDEA56FF573B678089A960FFC685/sketch/epd4in2-demo.ino.cpp:1: /home/beingpool/.arduino15/packages/adafruit/hardware/samd/1.7.11/cores/arduino/USB/USBCore.h:23: note: this is the location of the previous definition 23 | #define GET_STATUS 0 | </code></pre>
<p>There is no generic meaning in <code>GET_STATUS</code>. Apparently both libraries use the very same identifier for their own different purpose.</p> <p>If you do not use <code>GET_STATUS</code> in your sketch, you can remove the definition before the inclusion of &quot;epd4in2.h&quot;, like this:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;SPI.h&gt; #undef GET_STATUS #include &quot;epd4in2.h&quot; // ... </code></pre>
93247
|arduino-nano|pwm|
Bad readings from 12V pwm fan tachometer signal
2023-05-23T13:25:36.150
<p>I have the following circuit:</p> <p><a href="https://i.stack.imgur.com/wZ7WC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wZ7WC.png" alt="enter image description here" /></a></p> <p>(The Arduino is powered via the USB)</p> <p>The problem is that I the reading from the fan's tachometer signal are incorrect,</p> <p>I tried to add the two resistors as voltage dividers but still the readings are wrong. When I check the voltage of the tachometer signal with a multimeter, in the time the multimeter is connected the readings are somewhat correct (not 100%).</p> <p>Here is a snippet from the fan's documentation: <a href="https://i.stack.imgur.com/ejMKW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ejMKW.png" alt="enter image description here" /></a></p> <p>(BTW: When I used a different 12v pwm fan and didn't use a voltage divider the readings were incorrect only in the time I switched the 12v power off until the fan stopped spinning (after it stopped spinning the tachometer stopped sending signals so the rpm was 0 which was correct).)</p> <p>Working code (correct tacho signal value):</p> <pre><code>const byte tachpin = 2; unsigned int tacho = 0; long int startTime = 0; long int elapsed = 0; void setup() { Serial.begin(9600); // Configure Timer 1 for PWM @ 25 kHz. TCCR1A = 0; TCCR1B = 0; TCNT1 = 0; TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM11); TCCR1B = _BV(WGM13) | _BV(CS10); ICR1 = 320; pinMode(tachpin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(tachpin), tachisr, RISING); startTime = millis(); } void tachisr(){ tacho++; } void loop() { elapsed = millis() - startTime; if(elapsed &gt; 1000) { int tachcopy = 0; noInterrupts(); tachcopy = tacho; tacho = 0; interrupts(); rpm = (tachcopy / 2.0) * (60000 / elapsed); Serial.println(rpm,DEC); } startTime = millis(); } </code></pre> <p>Correct reading from working code</p> <blockquote> <p>rpm = 0, tachcopy = 0<br /> rpm = 1150, tachcopy = 39<br /> rpm = 2360, tachcopy = 80<br /> rpm = 2655, tachcopy = 90<br /> rpm = 2773, tachcopy = 94<br /> rpm = 2655, tachcopy = 90<br /> rpm = 1268, tachcopy = 43</p> </blockquote> <p>Not working code (incorrect tachometer signal):</p> <pre><code>const byte tachpin = 2; unsigned int tacho = 0; long int startTime = 0; long int elapsed = 0; long int rpm = 0; unsigned int pwmValue = 0; unsigned int outValue = 0; unsigned int seconds_counter = 0; void setup() { Serial.begin(9600); // Configure Timer 1 for PWM @ 25 kHz. TCCR1A = 0; TCCR1B = 0; TCNT1 = 0; TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM11); TCCR1B = _BV(WGM13) | _BV(CS10); ICR1 = 320; // Set the PWM pins as output. pinMode( 9, OUTPUT); //!!!ADDED LINE!!! pinMode(tachpin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(tachpin), tachisr, RISING); startTime = millis(); } void tachisr(){ tacho++; } //!! ADDED FUNCTION !!! void analogWrite25k(int value) { OCR1A = value; } void loop() { elapsed = millis() - startTime; if(elapsed &gt; 1000) { int tachcopy = 0; noInterrupts(); tachcopy = tacho; tacho = 0; interrupts(); startTime = millis(); rpm = (tachcopy / 2.0) * (60000 / elapsed); Serial.print(&quot;rpm = &quot;); Serial.print(rpm,DEC); Serial.print(&quot;, tachcopy = &quot;); Serial.println(tachcopy,DEC); seconds_counter++; } analogWrite25k(100); //!!!ADDED LINE!!! } </code></pre> <p>Not working code output:</p> <blockquote> <p>rpm = 737854, tachcopy = 25012<br /> rpm = 738591, tachcopy = 25037<br /> rpm = 737824, tachcopy = 25011<br /> rpm = 738591, tachcopy = 25037<br /> rpm = 738562, tachcopy = 25036<br /> rpm = 737854, tachcopy = 25012<br /> rpm = 738562, tachcopy = 25036<br /> rpm = 737854, tachcopy = 25012<br /> rpm = 738562, tachcopy = 25036<br /> rpm = 737824, tachcopy = 25011<br /> rpm = 738591, tachcopy = 25037<br /> rpm = 737854, tachcopy = 25012<br /> rpm = 738562, tachcopy = 25036<br /> rpm = 737854, tachcopy = 25012<br /> rpm = 738562, tachcopy = 25036<br /> rpm = 737854, tachcopy = 25012</p> </blockquote> <p>Readings when using 10K ohm resistor as pull up (instead of the voltage divider (10K+4.7K)) and maxing out analogWrite25k - <code>analogWrite25k(320);</code>:</p> <blockquote> <p>rpm = 6165<br /> rpm = 6401<br /> rpm = 6136<br /> rpm = 6136<br /> rpm = 6165<br /> rpm = 6018<br /> rpm = 6283<br /> rpm = 5870<br /> rpm = 6047<br /> rpm = 6578<br /> rpm = 6460<br /> rpm = 6224<br /> rpm = 5782<br /> rpm = 6047<br /> rpm = 6136<br /> rpm = 6136<br /> rpm = 6313<br /> rpm = 5988<br /> rpm = 6224<br /> rpm = 6195<br /> rpm = 6136<br /> rpm = 5900</p> </blockquote> <p>Which is interesting because the max speed of the fan is ~3000rpm (so rpm readings are about x2 max fan rpm when maxing out analogWrite25k)</p> <p><strong>Update:</strong></p> <p>Added debounce + 10K Ohm to Arduino 5V:</p> <pre><code>#define DEBOUNCE 10 //Interrupt handler. Stores the timestamps of the last 2 interrupts and handles debouncing unsigned long volatile ts1=0,ts2=0; //Calculates the RPM based on the timestamps of the last 2 interrupts. Can be called at any time. unsigned int calcRPM(){ unsigned long ts1_copy, ts2_copy; noInterrupts(); ts1_copy = ts1; ts2_copy = ts2; interrupts(); Serial.print(ts1_copy); Serial.print(&quot; / &quot;); Serial.print(ts2_copy); Serial.print(&quot; / &quot;); Serial.println(ts2_copy - ts1_copy); return (60000000.0 / (ts2_copy - ts1_copy ) / 2.0); } void tachisr2() { unsigned long m=micros(); if((m-ts2)&gt;DEBOUNCE){ ts1=ts2; ts2=m; } } </code></pre> <p>Output after adding debounce:</p> <blockquote> <p>rpm = 2953.92<br /> 90923308 / 90923320 / 12<br /> rpm = 2500000.00<br /> 91948328 / 91958496 / 10168<br /> rpm = 2950.43<br /> 92994188 / 92994200 / 12<br /> rpm = 2500000.00<br /> 94031032 / 94031040 / 8<br /> rpm = 3750000.00<br /> 95047108 / 95057256 / 10148<br /> rpm = 2956.25<br /> 96093308 / 96093320 / 12<br /> rpm = 2500000.00<br /> 97119144 / 97129296 / 10152<br /> rpm = 2955.08</p> </blockquote> <p>When the value is ~2900 it is the correct value.</p> <p><strong>Update 2</strong></p> <p>Hope you can help me with another problem, The rpm value is scattering on a range of up to 120rpm+ even on low fan cycle of 800 rpm, of course when the elapsed time wait is bigger the scattering range is lower, the rpm reading might be not precise by about ~10%, I saw videos of <a href="https://www.youtube.com/watch?v=8dZ-ZqsTAjw&amp;t=130s" rel="nofollow noreferrer">live speed reading from BIOS</a> of PC fan connected to PC motherboard and some of the fans are more precise (maybe because of BIOS code? (maybe there is a standard that specifies minimum time before reading the tacho counter?)), The question is are the tachometer sensors on 12V PC fans not supposed to be super precise by design or do I still have some problems with my circuit?, If I want a more precise rpm reading should I use an external tachometer sensor? which one is the best? optical/magnet based? (btw my current circuit doesn't include the 4.7KOhm resistor from the schematic, only 10KOhm pull up to 5V)</p>
<p><strong>1. Open Collector Output of a module.</strong></p> <p>The power for the open collector output should come from the MCU, not (indirectly) from the sensor's power supply. It is very similar to wiring a push button switch on the low side. Usually, the internal pullup resistor of the Arduino pin which is connected to the module passes enough power to detect the status of this output (as you have done). This internal pullup resistor has a value of around 30k. It is also possible to add a lower value external pull up resistor, if required say because of electrical noise, between the Arduino's 5v power rail and the pin. Ensure, however, that the current is within the tolerance of the connected device.</p> <p>Measuring PWM voltages with a multimeter will not be successful, as you have discovered. These tend to integrate and show an average voltage. Say 12 volts at a 50% duty cycle will be read as 6 volts. Use an oscilloscope to see the voltage across the wave form.</p> <p><strong>2. Electrical Interference.</strong></p> <p>Your figure here <code>tachcopy = 25012</code> indicate that your 25KHz signal is leaking through and being detected as pulses from the sensor. Powering the open collector via the Nano's 5v power rail (as above) may eliminate this. Maybe also better decoupling on the 12 volt power supply (say adding a big capacitor).</p> <p><strong>3. Code Issues</strong></p> <p>Your code has an number of issues which should be cleaned up. Some may show up after only about 25 days. Some may show up after the next recompilation and some affect the accuracy of the results.</p> <ul> <li><code>unsigned int tacho = 0;</code> should be volatile.</li> <li><code>int tachcopy = 0;</code> should be unsigned int to match the data tape it is copying.</li> <li>Variables which are derived from millis() should be unsigned long (uint32_t) as here: <code>elapsed = millis() - startTime;</code>.</li> <li>This <code>(60000 / elapsed)</code> should be forced to a floating point division say <code>(60000.0 / elapsed)</code></li> <li>This could be in setup() instead of loop(): <code>analogWrite25k(100); //!!!ADDED LINE!!!</code></li> </ul> <p><strong>4. &quot;rpm readings is about x2 max fan rpm&quot;</strong></p> <p>I can't explain that. It may be that the sensor output needs to be debounced.</p> <p><strong>5. Sample debounce routine (lockout principle)</strong></p> <pre><code>// Simple debounce routine. Based on original code. // After accepting a pulse locks out further pulses for 3 ms // Should be OK for 100Hz (period 10ms) void tachisr(){ // ISR (external interrupt) static uint32_t lastAcceptedPulseAtMs = 0 ; // static initialised once only uint32_t ms = millis() ; if ( ms - lastAcceptedPulseAtMs &gt;= 3 ) { // 3 ms - tune if required lastAcceptedPulseAtMs = ms ; tacho++; } } </code></pre> <p>Note: An ISR should be quick to execute and should not contain Serial.print() etc.</p>
93273
|esp32|programmer|esp32-cam|
unable to program esp32cam via cloned esp32-cam-mb
2023-05-25T20:59:56.017
<p>I bought a couple of ESP32CAMs from aliexpress... althought <a href="https://www.aliexpress.com/item/1005002808966055.html" rel="nofollow noreferrer">the listing</a> shows them with two buttons, I got the ESP32-CAM-MB boards with just the reset button...</p> <p>I have my computer set up to dual boot Windows and Linux so when I got an error in windows, I rebooted and installed the ESP32 boards for Arduino 2.1 and went ahead. I had to also install esptool and pyserial for it to work, but it ended up recognizing the port and every time I try to program it the flash flashes, but the programmer responds with</p> <blockquote> <pre><code>A fatal error occurred: Failed to connect to ESP32: Wrong boot mode detected (0xb)! The chip needs to be in download mode. </code></pre> </blockquote> <p>When I enable the serial console and press the reset button I get the following:</p> <pre><code>ets Jul 29 2019 12:21:46 rst:0x1 (POWERON_RESET),boot:0x1b (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:2 load:0x3fff0030,len:4 load:0x3fff0034,len:6968 load:0x40078000,len:13072 ho 0 tail 12 room 4 load:0x40080400,len:3896 entry 0x40080688 [0;32mI (31) boot: ESP-IDF v4.1-dirty 2nd stage bootloader[0m [0;32mI (31) boot: compile time 16:15:01[0m [0;32mI (31) boot: chip revision: 3[0m [0;32mI (34) boot_comm: chip revision: 3, min. bootloader chip revision: 0[0m [0;32mI (41) boot.esp32: SPI Speed : 40MHz[0m [0;32mI (46) boot.esp32: SPI Mode : DIO[0m [0;32mI (51) boot.esp32: SPI Flash Size : 4MB[0m [0;32mI (55) boot: Enabling RNG early entropy source...[0m [0;32mI (60) boot: Partition Table:[0m [0;32mI (64) boot: ## Label Usage Type ST Offset Length[0m [0;32mI (71) boot: 0 nvs WiFi data 01 02 00009000 00005000[0m [0;32mI (79) boot: 1 otadata OTA data 01 00 0000e000 00002000[0m [0;32mI (86) boot: 2 app0 OTA app 00 10 00010000 00300000[0m [0;32mI (94) boot: 3 spiffs Unknown data 01 82 00310000 000f0000[0m [0;32mI (101) boot: End of partition table[0m [0;32mI (106) boot_comm: chip revision: 3, min. application chip revision: 0[0m [0;32mI (113) esp_image: segment 0: paddr=0x00010020 vaddr=0x3f400020 size=0x1d2048 (1908808) map[0m [0;32mI (849) esp_image: segment 1: paddr=0x001e2070 vaddr=0x3ffbdb60 size=0x04d3c ( 19772) load[0m [0;32mI (857) esp_image: segment 2: paddr=0x001e6db4 vaddr=0x40080000 size=0x00400 ( 1024) load[0m [0;32mI (858) esp_image: segment 3: paddr=0x001e71bc vaddr=0x40080400 size=0x08e54 ( 36436) load[0m [0;32mI (880) esp_image: segment 4: paddr=0x001f0018 vaddr=0x400d0018 size=0x9df74 (647028) map[0m [0;32mI (1127) esp_image: segment 5: paddr=0x0028df94 vaddr=0x40089254 size=0x0b6a0 ( 46752) load[0m [0;32mI (1159) boot: Loaded app from partition at offset 0x10000[0m [0;32mI (1159) boot: Disabling RNG early entropy source...[0m � SD Size: 29557MB OK </code></pre> <p>I can see that the board is in <code>SPI_FAST_FLASH_BOOT</code> mode which according to the <a href="https://docs.espressif.com/projects/esptool/en/latest/esp32/advanced-topics/boot-mode-selection.html#manual-bootloader" rel="nofollow noreferrer">linked documentation</a> is wrong... but how to I get it to reboot in the correct mode?</p> <p><a href="https://www.reddit.com/r/esp32/comments/qjflp4/bought_a_shady_esp32cammb_that_doesnt_have_a_gp0/" rel="nofollow noreferrer">Others have had similar issues</a>, but they use another tool stack, so I am not sure what their solution would translate to in the Arduino 2.1 IDE...</p> <p><a href="https://i.stack.imgur.com/cahAL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cahAL.jpg" alt="stacked" /></a> <a href="https://i.stack.imgur.com/5ENAx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5ENAx.jpg" alt="bottoms" /></a> <a href="https://i.stack.imgur.com/5Di1x.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Di1x.jpg" alt="tops" /></a></p>
<p>While making sure I included all the correct links and pictures in the question, I found the answer - if an SD card is inserted, the flashing cannot be performed.</p> <p>Removing the SD card and resetting the ESP32 works. I now have a very bright flashing LED</p>
93275
|esp8266|arduino-ide|ch340|esp|arduino-ide-2|
Error while uploading "A fatal esptool.py error occurred: Write timeout"
2023-05-25T22:09:52.623
<p>I have constantly been getting this error while trying to upload a sketch on Wemos D1 Mini R1 &amp; R2 type board.</p> <blockquote> <p>A fatal esptool.py error occurred: Write timeout</p> </blockquote> <p>I've recently updated my Arduino IDE, so I assumed that it might be due to a bad installation. But after reinstalling everything including the Board Manager lib for ESP, Arduino IDE itself nothing worked. When I click on the Board Info, it displays an error &quot;Native serial port, can't obtain info&quot;.</p> <p>I've also tried different type of ESP boards (e.g. NodeMCU) but for all boards the problem is same. When I plug an Arduino to the same USB Port, it auto-detect the board, but when I plug-in the ESP boards, it doesn't recognize the boards automatically. So my guess is it has something to do with the CH34X driver. However I have tried reinstalling few versions of the driver from authentic sources, but nothing made an impact.</p> <p>Any help is appreciated.</p> <p>Following is the full trace of log getting printed:</p> <pre><code>. Variables and constants in RAM (global, static), used 28104 / 80192 bytes (35%) ║ SEGMENT BYTES DESCRIPTION ╠══ DATA 1496 initialized variables ╠══ RODATA 920 constants ╚══ BSS 25688 zeroed variables . Instruction RAM (IRAM_ATTR, ICACHE_RAM_ATTR), used 59667 / 65536 bytes (91%) ║ SEGMENT BYTES DESCRIPTION ╠══ ICACHE 32768 reserved space for flash instruction cache ╚══ IRAM 26899 code in IRAM . Code in flash (default, ICACHE_FLASH_ATTR), used 232148 / 1048576 bytes (22%) ║ SEGMENT BYTES DESCRIPTION ╚══ IROM 232148 code in flash esptool.py v3.0 Serial port COM8 Connecting... A fatal esptool.py error occurred: Write timeout </code></pre> <p>Following is the IDE Settings while uploading:</p> <p><a href="https://i.stack.imgur.com/pudIm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pudIm.png" alt="Arduino-IDE-upload-settings-for-D1-Mini-(ESP8266)" /></a></p>
<p>The &quot;most common reason&quot; mentioned in <a href="https://raspberrypi.stackexchange.com/a/140835">this answer</a> was actually the problem I had. Unfortunately I was using a charge only cable even though the cable package clearly said it was a data-cable. At times, these cheap electronics products confuses us a lot and we often miss to critically scrutinize the most obvious problems. As described in <a href="https://learn.adafruit.com/getting-started-with-raspberry-pi-pico-circuitpython/circuitpython" rel="nofollow noreferrer">this Adafruit tutorial</a> this problem seems to be a very common one.</p>
93281
|i2c|
How to change the I2C address of the AS5048B?
2023-05-27T03:49:28.937
<p>I saw <a href="https://www.youtube.com/watch?v=KN4wAZHtbzc" rel="nofollow noreferrer">this video</a> from James Bruton. See the links to the GitHub repos in the video description.</p> <p>I bought <a href="https://www.mouser.ca/ProductDetail/985-AS5048B-TS_EK_AB" rel="nofollow noreferrer">a few AS5048B boards from AMS</a>, so I can measure the position of my stepper motors.</p> <p>In the <code>sosandroid</code> repo, I ran <code>program_address</code> and was able to get one of them working, but they all have the same I2C address, and because I want to have 6 of them running simultaneously, it of course won't work. I know I could get an I2C multiplexer...</p> <p>I also tried setting the A1 and A2 pins on the AS5048B to high and low, which change the I2C address (for a total of 4)... But I want to change the I2C address permanently for each board.</p> <p>It looks to me like <code>program_address</code> is supposed to permanently program the I2C address, which the user can specify in the .ino file:</p> <pre><code>// Construct our AS5048B object with an I2C address of 0x40 AMS_AS5048B mysensor(0x40); </code></pre> <p>But no matter what I set it to (e.g. <code>0x40, 0x41, 0x42, 0x43, 0x44</code>), <a href="https://playground.arduino.cc/Main/I2cScanner/" rel="nofollow noreferrer">the Arduino I2C scanner</a> always finds <code>0x44</code>, which is the default address, so the <code>program_address</code> must not be working.</p> <p>EDIT: the default address is actually <code>0x40</code>. I must have programmed it to <code>0x44</code> without knowing (I was playing around with this board trying to figure this all out).</p> <p>I know that normally the I2C addresses cannot be changed, but it looks like <a href="https://ams.com/documents/20143/36005/AS5048_AN000386_1-00.pdf/3fc346bf-2379-6a45-9adb-1fe5407b8889" rel="nofollow noreferrer">this one</a> can:</p> <p>Here's a snippet from the link above. It says the OTP bits can be programmed/burned (only once!). My understanding is that the I2C address is saved in the OTP bits.</p> <blockquote> <p>Program the OTP bits permanently:</p> <ol> <li>Write dec.253 into the OTP control register (dec.3) to enable the special programming mode</li> <li>Set the Burn bit (dec.8) in the OTP control register (dec.3) to enable automatic programming procedure</li> <li>Write dec.0 into the OTP control register (dec.3) to disable the special programming mode</li> </ol> </blockquote> <p>I am using the Teensy 4.1 using PlatformIO in VS Code, and I also tried using an Arduino Uno in the Arduino IDE.</p> <p>My wiring is as follows:</p> <p><a href="https://i.stack.imgur.com/jUHkC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jUHkC.png" alt="wiring" /></a></p> <p><strong>So how do I program the I2C address on the AS5048B boards?</strong></p> <h2>EDIT:</h2> <ul> <li>I changed an image to text, and cleaned things up.</li> </ul> <p>As @6v6gt requested, I used the I2C scanner and it is still showing 0x40 (on this particular board), so it must not have been programmed (unless it's possible to program it to 0x40 even though 0x40 is its default value). The only thing I changed from the <code>program_address</code> repo is this line in the .ino file:</p> <pre><code>// Construct our AS5048B object with an I2C address of 0x40 AMS_AS5048B mysensor(0x48); </code></pre> <p>I changed the 0x40 to 0x48. But now I am getting this in the serial monitor:</p> <pre><code>Angle degree : I2C error: 2 359.9780273437 </code></pre> <p>Since I must have programmed the other board to 0x44 successfully, I am trying to think of what I did differently, but I don't remember.</p> <p>There are hundreds of lines of code in <code>program_address</code> (and the .h and .cpp file), so I probably shouldn't post all of it here. But here's <a href="https://github.com/sosandroid/AMS_AS5048B/tree/master/examples/program_address" rel="nofollow noreferrer">the GitHub repo</a>.</p>
<p>The device slave I2C address consists of the hardware setting on pins A1, A2 <strong>and upper MSBs programmable by the user.</strong> It is the setting of the MSBs, in addition to A1/A2 that I believe the OP is after.</p> <p>The information provided by @Nick Gammon concerning A1 and A2 is correct, but does not consider the other 5 bits (the MSBs). It appears that you can, indeed, permanently set a new I2C slave address on the device.</p> <p>You need to read the <a href="https://ams.com/documents/20143/36005/AS5048_AN000386_1-00.pdf/3fc346bf-2379-6a45-9adb-1fe5407b8889" rel="nofollow noreferrer">programming application note</a> very carefully, but they explain how to burn those bits into the register....it seems straightforward and is really just four steps, but I suppose it can be a little daunting, e.g., &quot;<em><strong>slave address consist of 5 programable bits (MSBs) and the hardware setting of Pins A1 and A2 I²C address &lt;4&gt; is by default not programmed and due to the inversion defined as '1'</strong></em>&quot;</p> <p>The application note gives an example of the 4 steps.... <a href="https://i.stack.imgur.com/Bv7Mb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bv7Mb.jpg" alt="enter image description here" /></a></p> <p>It may be the case that you already changed the I2C address default to 0x44 by following the instructions. [edited to add] Can you post the complete program [Arduino IDE code] that you used to <em>try</em> to change the I2C address?</p>
93298
|c++|shift-register|
Good practice to assign shift-register pins at the same time?
2023-05-28T21:28:19.633
<p>I'm new to bit register manipulation and am trying to set input and output values of some pins. The code sample I have on hand does it this way::</p> <pre><code>DDRD |= (1 &lt;&lt; 2); DDRD |= (1 &lt;&lt; 4); DDRD &amp;= ~(1 &lt;&lt; 5); PORTD |= (1 &lt;&lt; 2); PORTD &amp;= ~(1 &lt;&lt; 4); PORTD &amp;= ~(1 &lt;&lt; 5); </code></pre> <p>I have two questions:</p> <ol> <li><p>This is part of a code where I'm attempting to determine the time for a capacitor's discharge between pins 2 and 4. The arduino helpfiles mention that there may be a benefit to triggering both pins at once. Therefore: Is it is it possible to do <code>DDRD |= B00010100;</code> and <code>PORTD |= B00000100;</code> or combine the first three <code>DDRD</code> lines so it happens simultaneously, or does it have to be separately called?</p> </li> <li><p>Why is it <code>PORTD &amp;= ~(1 &lt;&lt; 4)</code> and not <code>PORTD |= ~(1 &lt;&lt; 4);</code>Can this conflict with the previous state of PORTD.</p> </li> </ol>
<blockquote> <pre><code>DDRD |= (1 &lt;&lt; 2); DDRD |= (1 &lt;&lt; 4); </code></pre> </blockquote> <p>The equivalent to that is:</p> <pre><code>DDRD |= (1 &lt;&lt; 2) | (1 &lt;&lt; 4); </code></pre> <p>However I prefer <code>bit</code> because it does the shift for you:</p> <pre><code>DDRD |= bit(2) | bit(4); </code></pre> <hr /> <blockquote> <p>Why is it <code>PORTD &amp;= ~(1 &lt;&lt; 4)</code> and not <code>PORTD |= ~(1 &lt;&lt; 4);</code></p> </blockquote> <p><code>PORTD &amp;= ~(1 &lt;&lt; 4)</code> is turning a bit <strong>off</strong>. First you invert the sense of the bit with the <strong>ones complement operator</strong> (~) and then by <strong>anding</strong> it, it means that all bits are retained except that one. So this is basically turning bit 4 off. If you used <code>|=</code> it would turn all of the other bits <strong>on</strong>.</p> <p>Equivalent code:</p> <pre><code>PORTD &amp;= ~bit(4); </code></pre> <p>Based on your example you meant bit 5 not bit 4.</p> <hr /> <blockquote> <pre><code>PORTD |= (1 &lt;&lt; 2); PORTD &amp;= ~(1 &lt;&lt; 4); PORTD &amp;= ~(1 &lt;&lt; 5); </code></pre> </blockquote> <p>That is turning on bit 2, and turning off bits 4 and 5, and leaving the rest unchanged.</p> <hr /> <blockquote> <p>Thanks. In that case would DDRD &amp;= B00000000; DDRD |= B00010100; have a similar result ...</p> </blockquote> <p>If you do <code>DDRD &amp;= B00000000;</code> then you are setting all bits to zero. So the simple equivalent to the above would be:</p> <pre><code>DDRD = B00010100; </code></pre> <p>This is a straight assignment, so you don't need to clear any bits.</p> <p>Or, you could write:</p> <pre><code>DDRD = bit(2) | bit(4); </code></pre> <hr /> <blockquote> <p>Do you know if bit() faster or is it cleaner compared to 1 &lt;&lt; x; or is it better for me to hook up a scope to test this myself?</p> </blockquote> <p>It is <strong>exactly the same</strong>. <code>bit</code> is just a <code>#define</code> in the Arduino.h file, as follows:</p> <pre><code>#define bit(b) (1UL &lt;&lt; (b)) </code></pre> <p>So all it does is save you writing the brackets and the shift left operator. It expands out to the same as what you were writing and thus will execute at the same speed, and take the same amount of memory.</p>
93302
|arduino-uno|programming|library|stepper|hc-sr04|
How to drive two Stepper motors and use an Ultrasonic sensor together?
2023-05-29T10:10:39.697
<p>I am working on an autonomous robot using two 4-pin stepper motors, HC-SR04 ultrasonic sensor, 2 L298N motor drivers (one for each motor), and an Arduino Uno. My problem is that when I use the stepper motors with the Stepper library, only one motor works at a time. My solution was to control the one step at a time in a short period of time, which worked, however, this introduces a new problem. The ultrasonic sensor requires a delay to work, but this makes the movement of the robot quite slow and jittery as it works only by one step at a time. When I remove the delay from the ultrasonic sensor, it starts returning the correct value, but then also returning 0 right after each correct value. My solution was to ignore the returned 0, but this is not ideal.</p> <p>How can I use two stepper motors at the same time and use an Ultrasonic sensor?</p> <p>Here is my code:</p> <pre><code>#include &lt;Stepper.h&gt; #include &lt;Ultrasonic.h&gt; /* * Pass as a parameter the trigger and echo pin, respectively, * or only the signal pin (for sensors 3 pins), like: * Ultrasonic ultrasonic(13); */ Ultrasonic ultrasonic(13, 12); int distance; int driveSpeed = 100; int stepsPerRevolution = 200; int leftMotorStep = 0; int rightMotorStep = 0; // Time interval between steps for both motors const int stepInterval = 10; // Adjust as needed // Last step time for each motor unsigned long leftMotorLastStepTime = 0; unsigned long rightMotorLastStepTime = 0; Stepper rightMotor(stepsPerRevolution, 8, 9, 10, 11); Stepper leftMotor(stepsPerRevolution, 4, 5, 6, 7); void setup() { Serial.begin(9600); rightMotor.setSpeed(driveSpeed); leftMotor.setSpeed(driveSpeed); } void loop() { distance = ultrasonic.read(); Serial.print(&quot;Distance in CM: &quot;); Serial.println(distance); delay(250); //This delay makes the motors behave strangely if (distance &lt; 15) { Serial.println(&quot;AVOIDING OBSTACLE!&quot;); // Perform obstacle avoidance behavior avoidObstacle(); } else if (distance &lt; 30) { Serial.println(&quot;APPROACHING OBSTACLE!&quot;); // Perform slow approach behavior slowApproach(); } else { Serial.println(&quot;DRIVING!&quot;); // Perform normal driving behavior drive(); } } void avoidObstacle() { // Stop the robot halt(); // Rotate the robot to avoid the obstacle leftM(); // Delay to allow the rotation to complete delay(1000); } void slowApproach() { // Slow down the motors int slowSpeed = 50; rightMotor.setSpeed(slowSpeed); leftMotor.setSpeed(slowSpeed); // Move the robot forward slowly forwardM(); // Delay to allow the slow approach delay(1000); } void drive() { // Set the motors back to the normal speed rightMotor.setSpeed(driveSpeed); leftMotor.setSpeed(driveSpeed); // Move the robot forward forwardM(); } void forwardM() { rightMotor.step(1); leftMotor.step(1); } void leftM() { rightMotor.step(1); leftMotor.step(-1); } void rightM() { rightMotor.step(-1); leftMotor.step(1); } void reverseM() { rightMotor.step(-1); leftMotor.step(-1); } void halt() { rightMotor.step(0); leftMotor.step(0); } </code></pre>
<p>Try this code.</p> <p>Here is a simulation. <a href="https://wokwi.com/projects/366108641014000641" rel="nofollow noreferrer">https://wokwi.com/projects/366108641014000641</a></p> <p>Click on the sensor to set the distance in the simulation</p> <p>NOTE: centimeters is <code>cm</code>, not <code>CM</code>.</p> <p>Not tested on hardware.</p> <pre class="lang-cpp prettyprint-override"><code> // https://arduino.stackexchange.com/questions/93302/how-to-drive-two-stepper-motors-and-use-an-ultrasonic-sensor-together #include &lt;Stepper.h&gt; #include &lt;Ultrasonic.h&gt; /* * Pass as a parameter the trigger and echo pin, respectively, * or only the signal pin (for sensors 3 pins), like: * Ultrasonic ultrasonic(13); */ Ultrasonic ultrasonic(13, 12); int distance; int slowSpeed = 100; int driveSpeed = 1000; int stepsPerRevolution = 100; int leftMotorStep = 0; // current step speed and direction int rightMotorStep = 0; int stepSpeed = 10; // this is the motor speed const int stepInterval = 1; // Time interval between steps for both motors unsigned long leftMotorLastStepTime = 0; // Last step time for each motor unsigned long rightMotorLastStepTime = 0; Stepper rightMotor(stepsPerRevolution, 8, 9, 10, 11); Stepper leftMotor (stepsPerRevolution, 4, 5, 6, 7); void setup() { Serial.begin(9600); rightMotor.setSpeed(1); leftMotor. setSpeed(1); } void loop() { distance = ultrasonic.read(); Serial.print(&quot;Distance in cm: &quot;); Serial.print(distance); Serial.print(&quot;\t&quot;); switch (distance) { // used switch/case for cleaner looking code case 0 ... 14: Serial.println(&quot;avoid&quot;); avoidObstacle(); // Perform obstacle avoidance behavior break; case 15 ... 29: Serial.println(&quot;approach&quot;); slowApproach(); // Perform slow approach behavior break; default: Serial.println(&quot;drive&quot;); drive(); // Perform normal driving behavior break; } rightMotor.step(rightMotorStep); // this actually moves the motors leftMotor .step(leftMotorStep); } void avoidObstacle() { halt(); // Stop the robot leftM(); // Rotate the robot to avoid the obstacle } void slowApproach() { rightMotor.setSpeed(slowSpeed); // Slow down the motors leftMotor. setSpeed(slowSpeed); forwardM(); // Move the robot forward slowly } void drive() { rightMotor.setSpeed(driveSpeed); // Set the motors back to the normal speed leftMotor. setSpeed(driveSpeed); forwardM(); // Move the robot forward } void forwardM() { rightMotorStep = stepSpeed; // select direction of step only leftMotorStep = stepSpeed; // do not move motor } // actual stepping is done at end of loop() void leftM() { rightMotorStep = stepSpeed; leftMotorStep = -stepSpeed; } void rightM() { rightMotorStep = -stepSpeed; leftMotorStep = stepSpeed; } void reverseM() { rightMotorStep = -stepSpeed; leftMotorStep = -stepSpeed; } void halt() { rightMotorStep = 0; leftMotorStep = 0; } </code></pre>
93304
|battery|charging|
Determine if a XIAO ESP32C3 is charging
2023-05-29T18:35:20.500
<p>When the XIAO ESP32C3 is charging a LiPo battery, there is a small LED on the board that lights up. Is there any way to access this information in an Arduino program?</p>
<p>No, according to the <a href="https://files.seeedstudio.com/wiki/XIAO_WiFi/Resources/Seeeduino-XIAO-ESP32C3-SCH.pdf" rel="nofollow noreferrer">schematic</a> it's not wired to any pin on MCU.</p> <p><a href="https://i.stack.imgur.com/0W8IU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0W8IU.png" alt="enter image description here" /></a></p>
93339
|array|
ArduinoJSON - How to check if array is empty
2023-06-02T05:02:30.480
<p>Parameters file defines the creation of entities and stored in flash. Its structure is given, and all fields ( keys &amp; values ) are given. In current phase - those parameters are hard-coded in a <code>const char* cont_params</code>, as shown below.</p> <p>My goal, is when array is empty, for example <code>RF_2entity</code> - means that current MCU does not uses its RF abilities, and will not init any RF entities. The way <code>RF_2entity</code> is defined below, as empty array, <code>[]</code> , ArduinoJSON's <code>isNull()</code> function return <code>0</code> in that case.</p> <p>How can I keep parameters file's structure and logic, rather that fill its values with <code>255</code> for example.</p> <pre><code> Serial.begin(115200); StaticJsonDocument&lt;1200&gt; doc; const char *cont_params = &quot;{\&quot;entityType\&quot;: [1,1,1,1],\ \&quot;SWname\&quot;: [\&quot;SW_0\&quot;,\&quot;SW_1\&quot;,\&quot;SW_2\&quot;,\&quot;SW_3\&quot;],\ \&quot;SW_buttonTypes\&quot;: [2,1,1,1],\ \&quot;SW_timeout\&quot;: [10,11,12,13],\ \&quot;SWvirtCMD\&quot;:[0,0,0,0],\ \&quot;Winname\&quot;: [],\ \&quot;WextInputs\&quot;: [],\ \&quot;WinvirtCMD\&quot;:[],\ \&quot;RF_2entity\&quot;: [],\ \&quot;v_file\&quot;: 0.5}&quot;; DeserializationError err = deserializeJson(doc, cont_params); JsonArray array = doc[&quot;Winname&quot;].as&lt;JsonArray&gt;(); serializeJsonPretty(array,Serial); Serial.println(array.isNull()); </code></pre> <p>output:</p> <pre><code>[]0 </code></pre>
<p>The method <code>isNull()</code> is not what you want. It tells you whether the instance holds an array at all or not. And of course, your specific instance holds an array, though an empty one. Therefore, the method correctly returns <code>false</code>, aka <code>0</code>.</p> <p>As <a href="https://arduinojson.org/v6/api/jsonarray/" rel="nofollow noreferrer">the API documentation</a> shows, there are more methods to use.</p> <p>What you want is <code>size()</code>, which returns the number of elements in the array. It will even return <code>0</code> on an instance without an array.</p>
93353
|arduino-uno|programming|led|button|
How do I turn on 3 LEDs in a repetitive sequence where all three LEDs would then turn OFF when the push button used is released?
2023-06-03T23:45:30.563
<p>Basically, how do I modify my code listed below to turn <strong>ON</strong> each of the three LEDs one at a time in a repetitive sequence while keeping the push-button pressed?</p> <ul> <li>Red (3 sec),</li> <li>Yellow (1 sec), and</li> <li>Green (3 sec).</li> </ul> <p>I'm trying to get all three LEDs to turn <strong>OFF</strong> when the push button is released.</p> <p>The code I wrote that doesn't allow me to achieve what I'm trying to do (I'm not sure where I went wrong):</p> <pre><code>#define Button_Pin 2 //Push Button Pin #define LED_Pin_1 11 //Red LED #define LED_Pin_2 10 //Yellow LED #define LED_Pin_3 9 //Green LED byte Button_State; void setup() { pinMode(Button_Pin, INPUT); pinMode(LED_Pin_1, OUTPUT); pinMode(LED_Pin_2, OUTPUT); pinMode(LED_Pin_3, OUTPUT); Serial.begin(9600); Serial.println(&quot;Design Part B - Digital I-O Control&quot;); delay(1000); } void loop() { Button_State = digitalRead(Button_Pin); Serial.print(&quot;Button State: &quot;); Serial.print(Button_State); if (Button_State == 1){ digitalWrite(LED_Pin_1, HIGH); delay(3000); //Wait for 3 Secs digitalWrite(LED_Pin_2, HIGH); delay(1000); //Waits for 1 Sec digitalWrite(LED_Pin_3, HIGH); delay(3000); Serial.println(&quot; --&gt; Button Pressed --&gt; LED ON&quot;); } else{ digitalWrite(LED_Pin_1, LOW); digitalWrite(LED_Pin_2, LOW); digitalWrite(LED_Pin_3, LOW); Serial.println(&quot; Button is Released --&gt; LED OFF&quot;); } } </code></pre> <p><a href="https://i.stack.imgur.com/jWU2r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jWU2r.png" alt="The circuit layouts being used" /></a></p>
<p>Having examined several sample sketches, including the recommended one, and watching instructional YouTube videos to grasp the fundamentals of Arduino programming, I am delighted to announce that my understanding of programming the Arduino and comprehending its functions has significantly improved, considering my novice status.</p> <p>I can confidently assert that this question has been resolved, and I have enclosed the code that fulfills the initial requirements that was asked of me.</p> <pre><code>#define pushButton_pin 2 #define grn_LED_pin 9 #define yel_LED_pin 10 #define red_LED_pin 11 bool pushButton_state; void setup() { pinMode(pushButton_pin, INPUT); pinMode(grn_LED_pin, OUTPUT); pinMode(yel_LED_pin, OUTPUT); pinMode(red_LED_pin, OUTPUT); Serial.begin(115200); Serial.println(&quot;Use push button (digital input) to control 3 LEDs (digital output)&quot;); delay(1000); } void loop() { pushButton_state = digitalRead(pushButton_pin); Serial.println(pushButton_state); if (pushButton_state == 1) { digitalWrite(grn_LED_pin, LOW); digitalWrite(yel_LED_pin, LOW); digitalWrite(red_LED_pin, HIGH); Serial.println(&quot; :push button state is 1, red LED is ON&quot;); delay(2000); digitalWrite(grn_LED_pin, LOW); digitalWrite(yel_LED_pin, HIGH); digitalWrite(red_LED_pin, LOW); Serial.println(&quot; :push button state is 1, yel LED is ON&quot;); delay(1000); digitalWrite(grn_LED_pin, HIGH); digitalWrite(yel_LED_pin, LOW); digitalWrite(red_LED_pin, LOW); Serial.println(&quot; :push button state is 1, grn LED is ON&quot;); delay(2000); } else { digitalWrite(grn_LED_pin, LOW); digitalWrite(yel_LED_pin, LOW); digitalWrite(red_LED_pin, LOW); Serial.println(&quot; :push button state is 0, all LEDs OFF&quot;); } delay(500); } </code></pre>
93409
|esp8266|power|current|
How much maximum current do the Arduino Wemos D1 (R1 & R2) consume?
2023-06-11T06:42:47.163
<p>I have been powering my WeMos D1 R1 and D1 R2 Arduinos (with ESP8266) using a simple USB cable connected to a standard charger whose rating is 3.1 amps. Is this sufficient to charge two such Arduino boards (it has two USB slots) simultaneously?</p> <p>Also, should I be using the other Power Input which I understand is 9V?</p> <p>All the specs I have seen specify the voltage but not the current usage.</p> <p>Either way, what is the maximum amperage that the board might need/is rated for? Is it different for the R1 vs. R2? Is it possible to measure how much it is using from any of the pins?</p>
<blockquote> <p>It is possible to measure how much it is using from any of the pins?</p> </blockquote> <p>Put an ammeter (multimeter in current mode) in series with the power supply and measure it, when configured in the way you intend to use it.</p>
93429
|serial|softwareserial|rs232|
Arduino unable to read 0x41 and 0x42 (reads others just fine (ICT bill acceptor)
2023-06-13T18:50:53.627
<p>Here is my issue:</p> <p>My code successfully recognizes and accepts $1 (0x40) and $20 bills (0x43), but it fails to recognize, display, process, anything for the $5 bill (0x41), and $10 bills (0x42). Also, when I say &quot;Arduino&quot;, I mean TTGO btw...</p> <p>I have verified that the bill acceptor is indeed sending the correct value (0x41) for the $5, and $10 (0x42) bills using an external monitoring tool like Docklight, and I used an oscilloscope too! All signals from all bill types were near identical and valid. However, the Arduino code does not seem to receive those two values (and ONLY those two values) at all... Meanwhile, it will display every other little thing there is... I have my code setup where it displays all incoming bytes, be it B.A. (bill acceptor) idle signals, rejection signals, everything, but it goes 100% blank, MIA, for 0x41 and 0x42... WHY?!?! So frick'n random...</p> <p>===================================================</p> <p><strong>Just so you all know, this is how the bill acceptor (B.A.) works:</strong></p> <ol> <li>Insert a bill into BA</li> <li>BA sends the corresponding HEX value (ex. 0x40) of the bill to my Arduino (Using RS232 cables and an RS232 to TTL converter (the converters are confirmed to be 100% operational BTW))</li> <li>Once the Arduino &quot;sees&quot; the HEX value for a bill of N value, it will then send 0x02 to the BA to accept the bill.</li> <li>If 0x02 is NOT sent to the BA within 5 seconds, then it will reject the bill and spit it back out the front.</li> <li>Code then adds that value to &quot;total count&quot;</li> </ol> <p>OFC, my code is setup where the only way an accept (0x02) signal is sent is IF 0x4N is received... So, the fact that 0x41 and 0x42 disappear into thin air means 0x02 is never sent so those two values are always rejected... Very, very, simple stuff, so the fact that it consistently is unable to ONLY NOT read 0x41 and 0x42 while clearly displaying all other sent HEX values is causing me unlimited headaches and conniptions... Programming... YAY! -_-</p> <p>So, anyone... please, do you know what's going on? The signal is 100% being generated, and my code, below, is setup to display all incoming bytes, but it acts like 0x41 and 0x42 do not exist at all! Nothing. Nada. Zilch. WTF? It literally handles everything I can throw at it... except 0x41 and 0x42!!! FUUUUUUUUUUUU!!! So mad...</p> <p><strong>HERE IS THE ICT RS232 PROTOCL FOR MY BILL ACCEPTOR - <a href="http://tdmegalit.ru/upload/iblock/401/ict_protocol.pdf" rel="nofollow noreferrer">http://tdmegalit.ru/upload/iblock/401/ict_protocol.pdf</a></strong></p> <p><strong>ALSO, I HAVE ALL DIP SWITCHES CORRECTLY SET, POWER SUPPLY IS PERFECT, ALL WIRES ARE TESTED AND PERFECT, RS232 TO TTL CONVERTERS ARE PERFECT. I GUESS IT IS SOFTWARE SERIAL, OR THE TTGO</strong></p> <p>So with all that said, <strong>below is my code</strong>. It is a part of a much great whole of a program, so to remove the possibilities of the rest of the code causing the error, I reduced it to what you see below, but the problem persist... bruh</p> <p>Also, I have included the <strong>Serial Monitor LOG</strong>. The LOG below shows startup, and then a 1, 5, 10, and 20 dollar bill being inserted...</p> <p><strong>SERIAL MONITOR LOG:</strong></p> <pre><code>PLZ NOTE, I ADDED SPACES TO SHOW WHATS GOING ON... ==================================================================== ... Received: 0x80 //IDLE SIGNALS (BA POWERED ON BEFORE &quot;SETUP&quot; SENT) ... Received: 0x8F ... Received: 0x80 ... Received: 0x8F ... Received: 0x80 ... Received: 0x8F SETUP - ...Sent: STX //SETUP TO INITALIZE BA SETUP - ...Sent: DLE SETUP - ...Sent: ETX ======================= //INSERTED $1 (0x40) SUCCESS!!! ... Received: 0x40 $1 accepted ... Sent: 0x02 ... Received: 0x10 //INSERTED $5 and 5 seconds later 0x29&gt;&gt;0x29&gt;&gt;0x2F = Rejection ... Received: 0x29 Bill rejected ... Received: 0x29 Bill rejected ... Received: 0x2F //INSERTED $10 and 5 seconds later 0x29&gt;&gt;0x29&gt;&gt;0x2F = Rejection ... Received: 0x29 Bill rejected ... Received: 0x29 Bill rejected ... Received: 0x2F //INSERTED $20 (0x43) SUCCESS!!! ... Received: 0x43 $20 accepted ... Sent: 0x02 ... Received: 0x10 </code></pre> <p><strong>BILL ACCEPTOR CODE:</strong></p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial BA(32, 33); // RX, TX int billCounter = 0; void setup() { Serial.begin(9600); BA.begin(9600); delay(3000); //WAIT BC TRESH BA.write(0x02); // Send the initialization command (STX) Serial.println(&quot;SETUP - ...Sent: STX&quot;); BA.write(0x10); // Send the command to enable the bill acceptor Serial.println(&quot;SETUP - ...Sent: DLE&quot;); BA.write(0x03); // Send the end of text character (ETX) Serial.println(&quot;SETUP - ...Sent: ETX&quot;); Serial.println(&quot;=======================&quot;); } void loop() { if (BA.available()) { byte receivedByte = BA.read(); Serial.print(&quot;... Received: 0x&quot;); Serial.println(receivedByte, HEX); if (receivedByte == 0x29) { delay(200); Serial.println(&quot;Bill rejected&quot;); // Handle bill rejection here (e.g., display message or perform necessary actions) } else if (receivedByte == 0x40) { delay(200); Serial.println(&quot;$1 accepted&quot;); BA.write(0x02); // Send the HEX value 0x02 to accept the bill Serial.println(&quot;... Sent: 0x02&quot;); // Increment the counter by $1 billCounter += 1; } else if (receivedByte == 0x41) { delay(200); Serial.println(&quot;$5 accepted&quot;); BA.write(0x02); // Send the HEX value 0x02 to accept the bill Serial.println(&quot;... Sent: 0x02&quot;); // Increment the counter by $5 billCounter += 5; } else if (receivedByte == 0x42) { delay(200); Serial.println(&quot;$10 accepted&quot;); BA.write(0x02); // Send the HEX value 0x02 to accept the bill Serial.println(&quot;... Sent: 0x02&quot;); // Increment the counter by $10 billCounter += 10; } else if (receivedByte == 0x43) { delay(200); Serial.println(&quot;$20 accepted&quot;); BA.write(0x02); // Send the HEX value 0x02 to accept the bill Serial.println(&quot;... Sent: 0x02&quot;); // Increment the counter by $20 billCounter += 20; } else if (receivedByte == 0x44) { delay(200); Serial.println(&quot;$50 accepted&quot;); BA.write(0x02); // Send the HEX value 0x02 to accept the bill Serial.println(&quot;... Sent: 0x02&quot;); // Increment the counter by $50 billCounter += 50; } else if (receivedByte == 0x45) { delay(200); Serial.println(&quot;$100 accepted&quot;); BA.write(0x02); // Send the HEX value 0x02 to accept the bill Serial.println(&quot;... Sent: 0x02&quot;); // Increment the counter by $100 billCounter += 100; } } } </code></pre>
<blockquote> <p>The default for Arduino Serial is 8 data bits, no parity, one stop bit. The first page of your linked documents says: Start bit 1, Data bit 8, Parity bit Even, Stop bit 1. The mismatched parity parameter could explain a partial failure of this communication. The documentation for the Serial begin() method describes the various configuration options.</p> <p>However, see also this thread: <a href="https://forum.arduino.cc/t/altsoftserial-how-to-change-parity-solved/668535" rel="nofollow noreferrer">https://forum.arduino.cc/t/altsoftserial-how-to-change-parity-solved/668535</a> It appears that the various software serial libraries do not support EVEN parity settings. Use a hardware serial port on your TTGO Arduino instead. This may mean using SoftwareSerial for the debug printing (maybe with a USB/UART adapter) and dedicating the hardware serial port to your bank note reader.</p> </blockquote> <p>Thank you 6v6gt! Using HardwareSerial was the answer and setting the parity bit to EVEN was the answer too :D Here is what I did to fix it if anyone ever needs to see this answer in the future...</p> <p><strong>Also note, here is the logic:</strong></p> <p>The default for hardware serial is SERIAL_8N1, but I needed to use SERIAL_8E1 for the even parity because:</p> <p>SERIAL_8N1 means &quot;8&quot; bits, &quot;N&quot;o parity, and &quot;1&quot; stop bit (hence 8N1)</p> <p>SERIAL_8E1 means &quot;8&quot; bits, &quot;E&quot;ven parity, and &quot;1&quot; stop bit (hence 8E1)</p> <p><strong>Here is the chart I used to get the protocol format I needed:</strong></p> <pre><code>/* Baud-rates available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200, 256000, 512000, 962100 * * Protocols available: * SERIAL_5N1 5-bit No parity 1 stop bit * SERIAL_6N1 6-bit No parity 1 stop bit * SERIAL_7N1 7-bit No parity 1 stop bit * SERIAL_8N1 (the default) 8-bit No parity 1 stop bit * SERIAL_5N2 5-bit No parity 2 stop bits * SERIAL_6N2 6-bit No parity 2 stop bits * SERIAL_7N2 7-bit No parity 2 stop bits * SERIAL_8N2 8-bit No parity 2 stop bits * SERIAL_5E1 5-bit Even parity 1 stop bit * SERIAL_6E1 6-bit Even parity 1 stop bit * SERIAL_7E1 7-bit Even parity 1 stop bit * SERIAL_8E1 8-bit Even parity 1 stop bit * SERIAL_5E2 5-bit Even parity 2 stop bit * SERIAL_6E2 6-bit Even parity 2 stop bit * SERIAL_7E2 7-bit Even parity 2 stop bit * SERIAL_8E2 8-bit Even parity 2 stop bit * SERIAL_5O1 5-bit Odd parity 1 stop bit * SERIAL_6O1 6-bit Odd parity 1 stop bit * SERIAL_7O1 7-bit Odd parity 1 stop bit * SERIAL_8O1 8-bit Odd parity 1 stop bit * SERIAL_5O2 5-bit Odd parity 2 stop bit * SERIAL_6O2 6-bit Odd parity 2 stop bit * SERIAL_7O2 7-bit Odd parity 2 stop bit * SERIAL_ </code></pre> <p><strong>CODE SOLUTION:</strong></p> <pre><code>#include &lt;HardwareSerial.h&gt; HardwareSerial BA(1); // Use Hardware Serial on TTGO void setup() { Serial.begin(9600); BA.begin(9600, SERIAL_8E1, 32, 33); // (Baud rate, Protocol, RX, TX) ... //rest of my code </code></pre>
93431
|programming|arduino-leonardo|
Improving moving mouse loop to optimize speed
2023-06-14T02:23:32.750
<p>Code:</p> <pre><code>#include &lt;Mouse.h&gt; #include &lt;hiduniversal.h&gt; #include &quot;hidmouserptparser.h&quot; #include &lt;USBController.h&gt; USBController controller; USB Usb; HIDUniversal Hid(&amp;Usb); HIDMouseReportParser Mou(nullptr); String x; String y; boolean isX; int recv; void setup() { Mouse.begin(); Usb.Init(); delay(200); if (!Hid.SetReportParser(0, &amp;Mou)) ErrorMessage&lt;uint8_t &gt; (PSTR(&quot;SetReportParser&quot;), 1); } void loop() { Usb.Task(); recv = controller.read(); if ((recv-48)==29){ // recv = M // , : -4 // /n : -38 x=&quot;&quot;; y=&quot;&quot;; isX = true; while (true){ recv = controller.read(); if (recv!=0 &amp;&amp; recv!=2){ // filter out 0 and 2 if ((recv-48)==-38){ // -38 is a line break break; } else if ((recv-48)==-4){ // switch to y value after comma isX = false; continue; } if (isX){ x+=String(recv-48); } else{ y+=String(recv-48); } } } Mouse.move(x.toInt(),y.toInt()); } } void onButtonDown(uint16_t buttonId) { Mouse.press(buttonId); } void onButtonUp(uint16_t buttonId) { Mouse.release(buttonId); } void onMouseMove(int8_t xMovement, int8_t yMovement, int8_t scrollValue) { Mouse.move(xMovement, yMovement, scrollValue); } </code></pre> <p>I'm using an Arduino leonardo with a usb host shield. My goal is to move my cursor to a specific location based on the data read in. Format of the data read in is &quot;MX,Y&quot; and a line break.</p> <p>In the main loop,</p> <ul> <li>I read the data and subtract 48 because that's the real number.</li> <li>Then I check if the first character is M because that is where the beginning of my data starts.</li> <li>Then I filter out 0 and 2 because those values are useless to me and randomly appear.</li> <li>I loop to add the integer values as strings to x then switch to y after the comma appears.</li> <li>Then I convert the <code>string</code> values to <code>int</code> and <code>mouse.move</code>.</li> </ul> <p>The problem is the mouse movement is slow and jittery and I think it's because the <code>toInt</code> and <code>String()</code> methods are slowing it down. How could I improve my algorithm?</p>
<p>This:</p> <blockquote> <pre class="lang-cpp prettyprint-override"><code>while (true){ recv = controller.read(); // ... } </code></pre> </blockquote> <p>is a <em>blocking</em> loop. This means that, while executing this part of the code, the Arduino is stuck for an indeterminate amount of time, and can do nothing else. Specifically, it cannot run <code>Usb.Task()</code>, which could well be the cause of the jittery behavior you are experiencing.</p> <p>I would recommend reading the incoming data in a <em>non blocking</em> fashion: each time there is a byte to be read, read it and move on. Do not wait for the subsequent bytes. Only when you find an end of line would you handle the data you received. For example:</p> <pre class="lang-cpp prettyprint-override"><code>// Parse and execute a command received through USB. executeCommand(String &amp;command) { // Implementation left as an exercise to the reader. } // Whether we are presently receiving characters from a command. bool receivingCommand = false; // Received command, may be incomplete. String command; void loop() { Usb.Task(); if (controller.available()) { char c = controller.read(); if (!receivingCommand &amp;&amp; c == 'M') { // start of command receivingCommand = true; } else if (receivingCommand &amp;&amp; c == '\n') { // end of command executeCommand(command); command = &quot;&quot;; receivingCommand = false; } else if (receivingCommand) { // body of command command += c; // buffer the received character } } } </code></pre> <p>A better approach would be to avoid the <code>String</code> class, which is not friendly to your Arduino's memory, and use a plain C string, as explained in <a href="https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27" rel="nofollow noreferrer">Reading Serial on the Arduino</a>. This, however, is likely unrelated to your jitter issue.</p>
93449
|c++|esp32|python|websocket|
ESP32 SocketIO Client is not connecting to Flask-SocketIO Server
2023-06-15T16:51:09.943
<p>I'm trying to connect a ESP32 client using <code>SocketIO</code> with a <code>Flask-SocketIO</code> server and it's not getting connected. The server uses SSL. The local server address is <code>https://192.168.1.137:3000</code>.Is the <code>https</code> causing issue here?</p> <p>The following is the output from the ESP32 in the serial monitor. Note that esp32 successfully connects to the wifi.</p> <pre><code>&gt; [&quot;myEvent&quot;,{&quot;now&quot;:95506}] &gt; [IOc] Disconnected! &gt; [IOc] Disconnected! &gt; [IOc] Disconnected! &gt; ... </code></pre> <p>Esp32 code:</p> <pre><code>/* * WebSocketClientSocketIOack.ino */ #include &lt;Arduino.h&gt; #include &lt;WiFi.h&gt; #include &lt;WiFiMulti.h&gt; #include &lt;WiFiClientSecure.h&gt; #include &lt;ArduinoJson.h&gt; #include &lt;WebSocketsClient.h&gt; #include &lt;SocketIOclient.h&gt; WiFiMulti WiFiMulti; SocketIOclient socketIO; #define USE_SERIAL Serial void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) { switch(type) { case sIOtype_DISCONNECT: USE_SERIAL.printf(&quot;[IOc] Disconnected!\n&quot;); break; case sIOtype_CONNECT: USE_SERIAL.printf(&quot;[IOc] Connected to url: %s\n&quot;, payload); // join default namespace (no auto join in Socket.IO V3) socketIO.send(sIOtype_CONNECT, &quot;/&quot;); break; case sIOtype_EVENT: { char * sptr = NULL; int id = strtol((char *)payload, &amp;sptr, 10); USE_SERIAL.printf(&quot;[IOc] get event: %s id: %d\n&quot;, payload, id); if(id) { payload = (uint8_t *)sptr; } DynamicJsonDocument doc(1024); DeserializationError error = deserializeJson(doc, payload, length); if(error) { USE_SERIAL.print(F(&quot;deserializeJson() failed: &quot;)); USE_SERIAL.println(error.c_str()); return; } String eventName = doc[0]; USE_SERIAL.printf(&quot;[IOc] event name: %s\n&quot;, eventName.c_str()); // Message Includes a ID for a ACK (callback) if(id) { // creat JSON message for Socket.IO (ack) DynamicJsonDocument docOut(1024); JsonArray array = docOut.to&lt;JsonArray&gt;(); // add payload (parameters) for the ack (callback function) JsonObject param1 = array.createNestedObject(); param1[&quot;now&quot;] = millis(); // JSON to String (serializion) String output; output += id; serializeJson(docOut, output); // Send event socketIO.send(sIOtype_ACK, output); } } break; case sIOtype_ACK: USE_SERIAL.printf(&quot;[IOc] get ack: %u\n&quot;, length); break; case sIOtype_ERROR: USE_SERIAL.printf(&quot;[IOc] get error: %u\n&quot;, length); break; case sIOtype_BINARY_EVENT: USE_SERIAL.printf(&quot;[IOc] get binary: %u\n&quot;, length); break; case sIOtype_BINARY_ACK: USE_SERIAL.printf(&quot;[IOc] get binary ack: %u\n&quot;, length); break; } } void setup() { //USE_SERIAL.begin(921600); USE_SERIAL.begin(115200); //Serial.setDebugOutput(true); USE_SERIAL.setDebugOutput(true); // USE_SERIAL.println(); // USE_SERIAL.println(); // USE_SERIAL.println(); // for(uint8_t t = 4; t &gt; 0; t--) { // USE_SERIAL.printf(&quot;[SETUP] BOOT WAIT %d...\n&quot;, t); // USE_SERIAL.flush(); // delay(1000); // } WiFiMulti.addAP(&quot;ssid&quot;, &quot;mypass&quot;); //WiFi.disconnect(); while(WiFiMulti.run() != WL_CONNECTED) { delay(100); } String ip = WiFi.localIP().toString(); USE_SERIAL.printf(&quot;[SETUP] WiFi Connected %s\n&quot;, ip.c_str()); // server address, port and URL socketIO.begin(&quot;192.168.1.137&quot;, 3000, &quot;/socket.io/?EIO=4&quot;); // event handler socketIO.onEvent(socketIOEvent); } unsigned long messageTimestamp = 0; void loop() { socketIO.loop(); uint64_t now = millis(); if(now - messageTimestamp &gt; 2000) { messageTimestamp = now; // creat JSON message for Socket.IO (event) DynamicJsonDocument doc(1024); JsonArray array = doc.to&lt;JsonArray&gt;(); // add event name // Hint: socket.on('event_name', .... array.add(&quot;myEvent&quot;); // add payload (parameters) for the event JsonObject param1 = array.createNestedObject(); param1[&quot;now&quot;] = (uint32_t) now; // JSON to String (serializion) String output; serializeJson(doc, output); // Send event socketIO.sendEVENT(output); // Print JSON for debugging USE_SERIAL.println(output); } } </code></pre> <p>Server code (Removed unrelated parts):</p> <pre><code>from flask import Flask, render_template, Blueprint, current_app, request, session, url_for, render_template from flask_socketio import SocketIO, emit from threading import Thread from queue import Queue import logging loggerPath = baseUrl + &quot;logs/appLog.log&quot; os.makedirs(os.path.dirname(loggerPath), exist_ok=True) with open(loggerPath, &quot;a&quot;) as f: logging.basicConfig( level=logging.INFO, # format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', format='%(levelname)s - %(message)s', filename=loggerPath ) bp = Blueprint('audio', __name__, static_folder='static', template_folder='templates') app = Flask(__name__) async_mode = &quot;threading&quot; socketio = SocketIO(app, cors_allowed_origins=&quot;*&quot;, async_mode=async_mode) @socketio.on('myEvent') def test_connect(data): logging.info(&quot;receiving&quot;) def runApp(): try: certificatePath = os.getenv('BASE_URL')+&quot;SSL/&quot; key = certificatePath+&quot;localhost.key&quot; certificate = certificatePath+&quot;localhost.crt&quot; context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(certificate, key) ip = socket.gethostbyname(socket.gethostname()) socketio.run(app, host=ip, port=3000,ssl_context=context) except Exception as e: logging.error(&quot;Exception occurred in: &quot;+__file__, exc_info=True) q = Queue() t = Thread(target=wrapper, args=(q, runApp), daemon=True) t.start() </code></pre>
<p>This is version Socketio issue,I have successfully connected . This installed version Werkzeug 2.0.0 Flask 2.3.3 Flask-SocketIO 4.3.1 python-engineio 3.13.2 python-socketio 4.6.0</p>
93460
|arduino-uno|dht22|
Reading from DHT22 with Arduino, powered by external source
2023-06-16T14:41:02.237
<p>I have the following situation. When I power my DHT22 with the 3.3V from the Arduino UNO (and Ground it there), then I can read the data perfectly fine using the DHT library from Adafruit.</p> <p>However, when I connect the DHT22 to my own external power supply (and respective ground), it fails. The reason for using this external power supply is so I can hook it up to a ESP8266 later.</p> <p>The power supply I build uses a 5V adapter, then an LD33V converter and (just for experimentation) an 100nF capacitor to reduce any noise on the line. I measured this external power supply and it indeed gives off 3.3V after the LD33V. I check the datasheet of the LD33V and it should be able to 'give' 5mA, whereas the DHT22 needs less than 1mA for operation.</p> <p>I don't know where to look at this moment. Can someone point me in the right direction? Much appreciated :)</p> <p>Cheers</p>
<p>Have you connected the external power supply ground to the Arduino's ground? If not, one is &quot;floating&quot; with respect to the other. But they need to have the same reference - the ground sides of their power supplies.</p>
93465
|avr|assembly|platformio|
Arduino Uno R3 assembly code to push a button and turn on a LED
2023-06-16T17:46:31.100
<p>I've been trying this for days without success...</p> <p>I need to turn on a LED on portb when a button in portd is pushed. Cabling works, I've tested it with Arduino IDE and it works like a charm.</p> <p>This is what I got so far:</p> <pre><code>.global main .equ LED, PB5 .equ BUTTON, PD3 main: ldi r22,0xff ;all bits in portb are output out _SFR_IO_ADDR(DDRB),r22 ldi r21,0x00 ;all bits in portd are input out _SFR_IO_ADDR(DDRD),r21 ldi r19, 0b00000000 ;unpushed button ldi r18, 0b00100000 ;pushed button eor r16, r16 loop: out BUTTON, r16 ;read button to r16 cp r16, r18 ;compare r16 with r19 (button on) cbi _SFR_IO_ADDR(PORTB),LED breq loop ;go back to loop sbi _SFR_IO_ADDR(PORTB),LED ;if z=1, turn led on turn led on rjmp loop ;back to loop </code></pre> <p>It is much easier with <code>sbis</code>, if I got it right...</p> <pre><code>#include &lt;avr/io.h&gt; .equ LED, PB5 .global main ldi r16,0xff out _SFR_IO_ADDR(DDRB),r16 ldi r16,0x00 out _SFR_IO_ADDR(DDRD),r16 main: sbis portd, 3 rjmp ledoff ldi r16,0xff sbi _SFR_IO_ADDR(PORTB),LED ; turn on led rjmp main ledoff: ldi r16,0x00 cbi _SFR_IO_ADDR(PORTB),LED ; turn off led rjmp main </code></pre> <p>But I got this error compiling:</p> <pre><code>.pio\build\uno\src\main.o: In function `main': (.text+0x8): undefined reference to `portd' collect2.exe: error: ld returned 1 exit status *** [.pio\build\uno\firmware.elf] Error 1 </code></pre>
<p>This line:</p> <blockquote> <pre class="lang-lisp prettyprint-override"><code> ldi r18, 0b00100000 ;pushed button </code></pre> </blockquote> <p>does not match the definition of <code>BUTTON</code>. You are setting bit 5 of the register, whereas the button is on bit 3. In order to avoid this kind of error, I would rather write</p> <pre class="lang-lisp prettyprint-override"><code> ldi r18, _BV(BUTTON) ;pushed button </code></pre> <p>Then, here:</p> <blockquote> <pre class="lang-lisp prettyprint-override"><code> out BUTTON, r16 ;read button to r16 </code></pre> </blockquote> <p>you are not reading anything: you are writing somewhere. I guess you mean:</p> <pre class="lang-lisp prettyprint-override"><code> in r16, _SFR_IO_ADDR(PIND) ;read button to r16 </code></pre> <p>Note that this reads the whole port at once. If you are only interested in one bit, you should then</p> <pre class="lang-lisp prettyprint-override"><code> andi r16, _BV(BUTTON) ;keep only the relevant bit </code></pre> <p>before the comparison.</p> <p>One last thing: you may want to read about the <code>sbis</code> and <code>sbic</code> instructions: they could simplify the code you have here.</p> <hr /> <p><strong>Edit</strong>: answering the updated question.</p> <blockquote> <p>undefined reference to `portd'</p> </blockquote> <p>This is because there is no such thing as “portd”. You mean <code>_SFR_IO_ADDR(PORTD)</code>. Well, no, you should actually use <code>_SFR_IO_ADDR(PIND)</code>, as this is the port <em>input</em> register, whereas <code>PORTD</code> is the <em>output</em> register.</p> <p>A couple of extra notes:</p> <ul> <li>Do not put code before <code>main</code>: it will not be executed, as the C runtime jumps to <code>main</code> after its initialization.</li> <li>The instructions <code>ldi r16, …</code> within the main loop serve no purpose: you are not using this register after the program initialization.</li> </ul>
93468
|library|keyboard|
With reference to Arduino Keyboard library, it does not have a keymap for UK keyboard, has anyone created a KeyboardLayout_en_UK.cpp file for this?
2023-06-17T09:34:43.117
<p>With reference to the Arduino Keyboard library, it does not have a keymap for the UK keyboard. I have tried to find a keyboard map that shows the hex value for the UK keyboard but I didn't have any luck.</p> <p>If you look in the Arduino Keyboard library: <code>Arduino\libraries\Keyboard\scr\KeyboardLayout_en_US.cpp</code> it has some other languages but no keyboard layout for a UK keyboard.</p> <p>It does say somewhere I think on GitHub that a keyboard layout file can be added, but where can I get that file or how can I create that file? Has anyone already created a KeyboardLayout_en_UK.cpp file I could use, please?</p>
<p>As an example of what you might do ...</p> <p>First copy the file KeyboardLayout_en_US.cpp and rename it as KeyboardLayout_en_UK.cpp.</p> <p>Most of the entries will be the same. Now looking at the layout in <a href="https://github.com/arduino-libraries/Keyboard/blob/1.0.4/src/KeyboardLayout.h" rel="nofollow noreferrer">https://github.com/arduino-libraries/Keyboard/blob/1.0.4/src/KeyboardLayout.h</a> we see this:</p> <pre class="lang-none prettyprint-override"><code> +---+---+---+---+---+---+---+---+---+---+---+---+---+-------+ |35 |1e |1f |20 |21 |22 |23 |24 |25 |26 |27 |2d |2e |BackSp | +---+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-----+ | Tab |14 |1a |08 |15 |17 |1c |18 |0c |12 |13 |2f |30 | Ret | +-----++--++--++--++--++--++--++--++--++--++--++--++--++ | |CapsL |04 |16 |07 |09 |0a |0b |0d |0e |0f |33 |34 |31 | | +----+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+---+----+ |Shi.|32 |1d |1b |06 |19 |05 |11 |10 |36 |37 |38 | Shift | +----+---++--+-+-+---+---+---+---+---+--++---+---++----+----+ |Ctrl|Win |Alt | |AlGr|Win |Menu|Ctrl| +----+----+----+------------------------+----+----+----+----+ </code></pre> <p>The third key along the top row of my (US) keyboard (below the function keys) has <code>@</code> on top and <code>2</code> on the bottom. It has the code <code>1f</code> in the chart.</p> <p>In the US layout file we see, in part:</p> <pre class="lang-none prettyprint-override"><code>0x2c, // ' ' 0x20 0x1e|SHIFT, // ! 0x21 0x34|SHIFT, // &quot; 0x22 0x20|SHIFT, // # 0x23 0x21|SHIFT, // $ 0x24 0x22|SHIFT, // % 0x25 0x24|SHIFT, // &amp; 0x26 0x34, // ' 0x27 0x26|SHIFT, // ( 0x28 0x27|SHIFT, // ) 0x29 0x25|SHIFT, // * 0x2a 0x2e|SHIFT, // + 0x2b 0x36, // , 0x2c 0x2d, // - 0x2d 0x37, // . 0x2e 0x38, // / 0x2f 0x27, // 0 0x30 0x1e, // 1 0x31 0x1f, // 2 0x32 0x20, // 3 0x33 0x21, // 4 0x34 0x22, // 5 0x35 0x23, // 6 0x36 0x24, // 7 0x37 0x25, // 8 0x38 0x26, // 9 0x39 0x33|SHIFT, // : 0x3a 0x33, // ; 0x3b 0x36|SHIFT, // &lt; 0x3c 0x2e, // = 0x3d 0x37|SHIFT, // &gt; 0x3e 0x38|SHIFT, // ? 0x3f 0x1f|SHIFT, // @ 0x40 </code></pre> <p>I've put the <em>positions</em> of each entry on the right (the offset from the start of the array).</p> <p>So looking at that table, when the scan code <code>1f</code> arrives, and SHIFT is pressed, we get <code>0x40</code> which is indeed <code>@</code> in the ASCII table.</p> <p>Similarly, <code>1f</code> without SHIFT gives us <code>0x32</code> which is <code>2</code> in the ASCII table.</p> <p>Now in your case I believe that key gives <code>&quot;</code> when SHIFT is pressed, so the <em>third</em> line from the top in my example changes from:</p> <pre class="lang-none prettyprint-override"><code>0x34|SHIFT, // &quot; 0x22 </code></pre> <p>to:</p> <pre class="lang-none prettyprint-override"><code>0x1f|SHIFT, // &quot; 0x22 </code></pre> <p>And likewise for the other keys. So, the <code>@</code> symbol moves to where the quote is in the US keyboard. So change the <em>last</em> line in my example from:</p> <pre class="lang-none prettyprint-override"><code>0x1f|SHIFT, // @ 0x40 </code></pre> <p>to:</p> <pre class="lang-none prettyprint-override"><code>0x34|SHIFT, // &quot; 0x40 </code></pre> <p>Those two changes &quot;swap&quot; the locations of the <code>&quot;</code> and the <code>@</code> symbols.</p> <hr /> <p>As noted in the comments, keys marked ¬ and £ do not have a 7-bit ASCII representation so you will not be able to put them in the table (there is no entry for them).</p>
93481
|arduino-mega|library|analogread|
Why does analogRead(A0) deliver different Values when called in a library file vs calling it in the sketch directly
2023-06-18T14:09:33.207
<p>I wanted to write a library representing a sensor to later on have an array of sensors. I generated a file MoistureSensor.h:</p> <pre><code>#ifndef MoistureSensor_h #define MoistureSensor_h #include &lt;Arduino.h&gt; class MoistureSensor { private: uint8_t sensPin; int sensValue; int sensId; public: MoistureSensor(uint8_t pin,int id); int getValue(); int getId(); }; #endif </code></pre> <p>and MoistureSensor.cpp:</p> <pre><code> // MoistureSensor.cpp #include &quot;MoistureSensor.h&quot; MoistureSensor::MoistureSensor(uint8_t pin, int id) { sensPin = pin; sensId = id; } int MoistureSensor::getValue() { sensValue = analogRead(sensPin); return sensValue; } int MoistureSensor::getId() { return sensId; } </code></pre> <p>this is the main sketch running on a Arduino Mega:</p> <pre><code>#include &quot;MoistureSensor.h&quot; MoistureSensor sens1(&quot;A0&quot;, 1); void setup() { Serial.begin(9600); } void loop() { Serial.println(&quot;Value from analogread:&quot;); Serial.println(analogRead(A1)); Serial.println(&quot;Value from library:&quot;); Serial.println(sens1.getValue()); Serial.println(&quot;End&quot;); delay(1000); } </code></pre> <p>So when I run this the serial monitor shows:</p> <pre><code>Value from analogread: 600 Value from library: 496 End </code></pre> <p>Why doesn't this print the same value? Does the .cpp file interpret the data from <code>analogRead()</code> different than the sketch?</p> <p>Also both values where moving up and down depending on the response of the sensor.</p> <p>Thanks in advance.</p>
<p>Trying to compile your sketch, I get the following compiler warning:</p> <pre><code>warning: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}' MoistureSensor sens1(&quot;A0&quot;, 1); ^ note: initializing argument 1 of 'MoistureSensor::MoistureSensor(uint8_t, int)' </code></pre> <p>This means that, whereas the <code>MoistureSensor()</code> constructor expected its first argument to be of type <code>uint8_t</code>, you provided a <code>const char*</code> instead. Indeed, a string literal like <code>&quot;A0&quot;</code> decays to a <code>const char*</code> pointer when you pass it as a function argument.</p> <p>The fix is to pass the actual pin number to your constructor:</p> <pre class="lang-cpp prettyprint-override"><code>MoistureSensor sens1(A0, 1); </code></pre> <p>But then, there is a second issue. In your test sketch, you have your <code>MoistureSensor</code> object read <code>A0</code>, whereas the direct <code>analogRead()</code> reads pin <code>A1</code>. If you want to get the same value, you should read the same pin.</p> <p><strong>Side note</strong>: the change from <code>uint8_t</code> to <code>byte</code> has absolutely nothing to do with your issue. These two types are synonyms.</p>
93493
|serial|esp32|usb|uploading|uart|
Unable to upload sketch to Lolin S3 Pro (ESP32-S3)
2023-06-19T13:49:25.097
<p>I'm trying to upload a simple sketch to the new Wemos Lolin S3 Pro but unfortunately I can't seem to get it to work. I get the following error message:</p> <pre><code> Connecting...................................... A fatal error occurred: Failed to connect to ESP32-S3: No serial data received. For troubleshooting steps visit: https://docs.espressif.com/projects/esptool/en/latest/troubleshooting.html Failed uploading: uploading error: exit status 2 </code></pre> <p>The following board is causing problems: <a href="https://www.wemos.cc/en/latest/s3/s3_pro.html" rel="nofollow noreferrer">https://www.wemos.cc/en/latest/s3/s3_pro.html</a></p> <p>It seems that there is no USB to UART chip and also no boot button. As board I selected the &quot;LOLIN S3 Pro&quot; in the Arduino IDE and under Platformio I had selected the &quot;lolin_s3&quot;. I have also tried it under platformio with the following build flags but unfortunately without success:</p> <pre><code>build_flags = -DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT=1 </code></pre> <p>I am really perplexed what could be the cause?</p> <p>Btw: I bought 3 of these boards and all 3 have the same issue.</p>
<p>OK I managed to solve it although I find its a little bit annoying it seems that you need to always set this board in download mode manually. (Press and hold boot and click reset button once).</p> <p>If you are using Arduino IDE use the following options:</p> <ul> <li>USB CDC On Boot -&gt; Enabled</li> <li>Upload Mode -&gt; Hardware CDC / UART0</li> </ul> <p>If you are using PlatformIO use the following build flags:</p> <pre><code>build_flags = '-DARDUINO_USB_MODE=1' '-DARDUINO_USB_CDC_ON_BOOT=1' </code></pre> <p>Also a good source: <a href="https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/tutorials/cdc_dfu_flash.html" rel="nofollow noreferrer">https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/tutorials/cdc_dfu_flash.html</a></p>
93494
|arduino-ide|bluetooth|buffer|
Arduino IDE equivalent to DataView?
2023-06-19T15:08:11.103
<p>I am working on a project with Bluetooth commands between various devices. I would like to try and convert a string to a DataView Object on Arduino, so I can send it over BLE, much like this function written in Javascript:</p> <pre><code>function str2DV(str) { var buf = new ArrayBuffer(str.length); var bufView = new Uint8Array(buf); for (var i=0, strLen=str.length; i&lt;strLen; i++) { bufView[i] = str.charCodeAt(i); } var DV = new DataView(buf); return DV; } </code></pre> <p>Is this possible with Arduino? I have yet to find a solution....</p>
<p>There is no use for a DataView in the Arduino environment. In the JavaScript language, a string and an array of bytes are two very different things. That's why you need something like this <code>str2DV()</code> function to convert between them. In C++, they are one and the same thing: no need to convert. Sometimes the type <code>uint8_t</code> (also named <code>byte</code>) is used in preference of <code>char</code> for storing binary data, but you can just typecast between these types. The typecast typically compiles to zero machine instructions, as the underlying data representation is the same.</p> <p>For example:</p> <pre class="lang-cpp prettyprint-override"><code>extern some_lib_function(const uint8_t *buffer, int buffer_length); const char *my_message = &quot;Hello, World!\n&quot;; some_lib_function((uint8_t *) my_message, strlen(my_message)); </code></pre> <p>If your string is in the form of a <code>String</code> object, rather than a plain C-string, then use the <code>c_str()</code> method to get the plain string back:</p> <pre class="lang-cpp prettyprint-override"><code>String my_message = &quot;Hello, World!\n&quot;; some_lib_function((uint8_t *) my_message.c_str(), my_message.length()); </code></pre>
93522
|esp32|wifi|array|http|memory|
stream a "big" array of measures to a server through wifi
2023-06-21T09:24:34.100
<p>I'm measuring accelerations at &quot;high frequency&quot; (4kHz) from an accelerometer (ADXL355/ADXL357) to an esp32. It's crucial that no sample is lost while performing a measure which last say 2 seconds, thus I first record all the samples and then send the complete array of measures to a server over wifi knowing the IP and the port of the server.</p> <p>The measures array is an int array of size 3bytes * 3axis * 4000Hz * 2seconds = 72000 bytes.</p> <p>I tried to make an http server and send the measures array from the microcontroller to the server with a POST request and serializing the payload with json (ArduinoJSON library), but this is very costy in terms of memory, because I need to duplicate the array of measures and convert it to an array of strings.</p> <p>Is there a better way to send this array over wifi to the server (some sort of stream?) optimizing the memory usage on the microcontroller? which arduino libraries may help in the task? could you link an example with code of a similar situation?</p>
<p>JSON is a format trivial to write: you do not need a library for this. For example, an array of numbers could be serialized like this:</p> <pre class="lang-cpp prettyprint-override"><code>void serialize_array(Print &amp;client, int *data, int count) { client.print('['); for (int i = 0; i &lt; count; i++) { client.print(data[i]); client.print(i==count-1 ? ']' : ','); } } </code></pre> <p>This would effectively stream the data without storing the JSON representation in memory.</p>
93547
|arduino-mega|hardware|atmega2560|
ATMEGA2560 died inside a arcade game circuit
2023-06-22T21:59:55.187
<p>I am building arcade game with 10 player buttons (5 for each player) and one start button. All buttons have build in LED inside. Player buttons has LED for 12V and start button has led for 5V. I am using ATMEGA2560 pro boar. I have also 4 TM1637 displays (two for each player) showing time and score. I am using 12V adapter. This is my schematic:</p> <p><a href="https://i.stack.imgur.com/ocdaM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ocdaM.png" alt="schematics" /></a></p> <p>This is test code which I had:</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;TM1637Display.h&gt; #define BTN_A1_PIN 16 #define BTN_A2_PIN 18 #define BTN_A3_PIN 28 #define BTN_A4_PIN 26 #define BTN_A5_PIN 47 #define BTN_B1_PIN 44 #define BTN_B2_PIN 36 #define BTN_B3_PIN 39 #define BTN_B4_PIN 46 #define BTN_B5_PIN 37 #define LED_A1_PIN 13 #define LED_A2_PIN 17 #define LED_A3_PIN 11 #define LED_A4_PIN 15 #define LED_A5_PIN 19 #define LED_B1_PIN 25 #define LED_B2_PIN 27 #define LED_B3_PIN 23 #define LED_B4_PIN 21 #define LED_B5_PIN 29 #define BTN_START_PIN 32 #define LED_START_PIN 35 #define DISPLAY_A_SCORE_CLK 20 #define DISPLAY_A_SCORE_DIO 10 #define DISPLAY_A_TIME_CLK 40 #define DISPLAY_A_TIME_DIO 43 #define DISPLAY_B_SCORE_CLK 42 #define DISPLAY_B_SCORE_DIO 33 #define DISPLAY_B_TIME_CLK 34 #define DISPLAY_B_TIME_DIO 38 typedef struct { uint8_t btnIn; uint8_t ledOut; } btn_t; btn_t btn[] = { { .btnIn = BTN_A1_PIN, .ledOut = LED_A1_PIN, }, { .btnIn = BTN_A2_PIN, .ledOut = LED_A2_PIN, }, { .btnIn = BTN_A3_PIN, .ledOut = LED_A3_PIN, }, { .btnIn = BTN_A4_PIN, .ledOut = LED_A4_PIN, }, { .btnIn = BTN_A5_PIN, .ledOut = LED_A5_PIN, }, { .btnIn = BTN_B1_PIN, .ledOut = LED_B1_PIN, }, { .btnIn = BTN_B2_PIN, .ledOut = LED_B2_PIN, }, { .btnIn = BTN_B3_PIN, .ledOut = LED_B3_PIN, }, { .btnIn = BTN_B4_PIN, .ledOut = LED_B4_PIN, }, { .btnIn = BTN_B5_PIN, .ledOut = LED_B5_PIN, }, { .btnIn = BTN_START_PIN, .ledOut = LED_START_PIN, }, }; TM1637Display displayAScore(DISPLAY_A_SCORE_CLK, DISPLAY_A_SCORE_DIO); TM1637Display displayATime(DISPLAY_A_TIME_CLK, DISPLAY_A_TIME_DIO); TM1637Display displayBScore(DISPLAY_B_SCORE_CLK, DISPLAY_B_SCORE_DIO); TM1637Display displayBTime(DISPLAY_B_TIME_CLK, DISPLAY_B_TIME_DIO); void setup() { for (int i = 0; i &lt; 11; i++) { pinMode(btn[i].btnIn, INPUT_PULLUP); pinMode(btn[i].ledOut, OUTPUT); } displayAScore.setBrightness(0x0f); displayATime.setBrightness(0x0f); displayBScore.setBrightness(0x0f); displayBTime.setBrightness(0x0f); displayAScore.showNumberDec(1111, false); displayATime.showNumberDec(2222, false); displayBScore.showNumberDec(3333, false); displayBTime.showNumberDec(4444, false); } void loop() { for (size_t i = 0; i &lt; 11; i++) { if(0 == digitalRead(btn[i].btnIn)) { digitalWrite(btn[i].ledOut, HIGH); } else { digitalWrite(btn[i].ledOut, LOW); } } } </code></pre> <p>And this is what it looks like inside:</p> <p><a href="https://i.stack.imgur.com/Q5RMw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q5RMw.jpg" alt="arcade box inside" /></a></p> <p><a href="https://i.stack.imgur.com/ikW0B.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ikW0B.jpg" alt="arcade box front" /></a></p> <p>The problem is <strong>ATMEGA2560</strong> just burned. I was testing it firstly without TM1637 (they were connected to power but I did not use lib for them at that time) and it was working okay (buttons were lighting up upon pressing).</p> <p>Then I added lib for TM1637 to code and for 2 seconds I saw &quot;1111&quot; &quot;2222&quot; ... so on as it is in code, so there is no bad connection. But after 2 seconds it started buzzing (probably linear regulator temp protection was kicking in) and ATMEGA just burned.</p> <p>Now when I plug 12V in it MCU gets hot pretty fast. I can measure 5V on the linear regulator so it is not shorted. I had always connected only 12V and no power from USB. I know my wires are not the shortest but I would not expect that MCU dies. Could you help please? I don't want to plug the next 20€ chip just to see another expensive smoke.</p>
<p>You fried it because you broke rule #1: &quot;A Power Supply the Arduino is NOT!&quot;. Your displays can pull 320 Ma in themselves. That is over 2 watts of power before anything else. When you get a new one purchase a buck converter and power the LEDs with the 5V output of that, use the 12V to feed it. As I understand it The suggested maximum power dissipation for the Mega regulator is 1 Watt. So with 12V into the regulator the max current is about 140 mA (1W / (12V - 5V)), This does not count your LEDs.</p>
93549
|arduino-ide|arduino-nano|
How can I get the Arduino IDE v0021 running on Windows XP to communicate with the latest Nano v3.0
2023-06-23T10:30:57.170
<p>After reading another post <a href="https://arduino.stackexchange.com/questions/51729/ch340-nano-avrdude-stk500-getsync-not-in-sync-resp-0xa4">CH340 Nano avrdude: stk500_getsync() not in sync resp=0xa4</a> I have discovered that the bootloader on current Nano v3.0 has been upgraded. However, the advice given to overcome this problem is based around a more modern version of the Arduino IDE communicating with an old bootloader. I have the reverse problem. I damaged my Arduino Nano that was working with a laptop running Windows XP and bought a replacement. It obviously has the latest bootloader installed so my version of the Arduino IDE v0021 (recommended to run on Windows XP) can no longer upload sketches to the board.</p> <p>I have uploaded GRBL v1.1h to the Nano board from an Arduino IDE v1.8.19 installation on a Windows 7 computer but the older version of GRBL Control v0.8.1 running on Windows XP has compatibility issues with GRBL 1.1h. I need to upload an earlier version of GRBL that is compatible with GRBL Control v0.8.1 but the bootloader on the new Arduino Nano v3.0 runs at 115200 and the Arduino IDE v0021 expects a baud rate of 57600 so I get these errors</p> <blockquote> <p>stk500_getsync():not in sync: resp=0x09</p> <p>stk500_disable(): protocol error, expect=0x14, resp=0x51</p> </blockquote> <p>Can I upload an older bootloader to a newer Arduino Nano so I can then flash an older version of GRBL that is compatible with GRBL Control v0.8.1 to run on Windows XP?</p>
<p>I agree with Juraj that any bootloader can be uploaded to the newer version of the Nano. However, the process of doing so is not simple. With Windows XP SP3 installed on my laptop I was running Arduino IDE v0021. The process involves connecting an Arduino UNO R3 to the Arduino Nano v3.0 but first you have to communicate with both boards through the Arduino IDE v0021. This requires two different USB drivers. For Device Manager to recognise the UNO R3 I had to copy the &quot;Drivers&quot; folder from my Arduino IDE v1.8.19 installation on my Windows 7 computer to my Arduino IDE v0021 installation folder on my laptop. Inside that drivers folder is a file called &quot;Old_Arduino_Drivers.zip&quot;. You need to expand that into the &quot;Drivers&quot; folder. In Device Manager with the Arduino UNO R3 plugged in you can now update the driver for the &quot;Unknown USB&quot; device by searching in the &quot;Drivers&quot; folder. On my computer it installed it as Arduino UNO R3 on COM7. It may be a different COM port on your computer. <em><strong>NOTE: FTDI and CH340 drivers will NOT work on Windows XP with the Arduino UNO R3.</strong></em></p> <p>Now disconnect the Arduino UNO R3 and connect the Arduino Nano v3.0. Once again Device Manager should not recognise it. Search the &quot;Drivers&quot; folder once again and it should find a driver. However, this time it will use an FTDI driver to install the Nano. It showed up in Device Manager as USB Serial Port on COM5.</p> <p>After both these drivers were successfully installed my Arduino IDE v0021 could communicate with both Arduino boards and it could upload sketches to the Arduino UNO R3 but not the Nano...yet. I connected the Arduino UNO R3 and uploaded, &quot;ArduinoISP&quot; from the menu File &gt;&gt; Examples.</p> <p>I then unplugged the USB cable from the Arduino UNO R3 and physically connected wires between the UNO and the Nano (see the connection diagram <a href="https://support.arduino.cc/hc/en-us/articles/4841602539164-Burn-the-bootloader-on-UNO-Mega-and-classic-Nano-using-another-Arduino" rel="nofollow noreferrer">here</a>).</p> <p>With both boards wired correctly, plug the USB cable back into the Arduino UNO R3. You should see LEDs light up on both boards. Open the Arduino IDE v0021 and from the Tools menu select &quot;Arduino Duemilanove or Nano w/ ATmega328&quot; as the board. <em><strong>NOTE: Do NOT select &quot;Arduino Uno&quot; even though it is the board connected to your computer. You are about to burn a new bootloader to the Nano not the Uno.</strong></em> Next select whatever serial port has been allocated to the device. In my case COM7 was allocated to the UNO. Now from the &quot;Tools&quot; menu select &quot;Burn Bootloader &gt;&gt; w/ Arduino as ISP&quot;. This worked for me and I was finally able to upload sketches to the Arduino Nano v3.0 using the old version 0021 of the Arduino IDE on Windows XP.</p>
93559
|bootloader|atmega32u4|
Arduino AVR Program with default ATMEGA32U4 bootloader instead
2023-06-24T01:36:02.427
<p>I’m working an Arduino program that uses the FastLED library and is all coded in the Arduino IDE (not my choice, just a result of this OOS library).</p> <p>However, I don’t want to run this on an “Arduino” board. Instead, I want to flash this to a factory fresh ATMEGA32U4 as an MCU for the project. However, the ATMEGA32U4 doesn’t come with the Arduino boot loader, but instead, DFU. I have flashing procedures designed for the DFU boot loader already and I don’t want to go swapping bootloaders.</p> <p>Would the Arduino program work fine without swapping to the Arduino bootloader? My understanding is <em>yes</em> since the bootloader only controls the boot sequence, and has nothing to do with runtime.</p>
<blockquote> <p>Would the Arduino program work fine without swapping to the Arduino bootloader?</p> </blockquote> <p>Yes, the bootloader is only there for conveniently changing program memory via serial instructions.</p> <p>Whatever method you use to put the &quot;main&quot; code there, it will be the same code and will operate the same.</p>
93561
|arduino-uno|interrupt|spi|nrf24l01+|
Changing SPI ports on an Arduino
2023-06-24T06:08:06.353
<p>My end goal is to read information from an nRF24l01 module connected to my Arduino UNO R3, and generate an interrupt whenever a message is sent to the Arduino.</p> <p>Now, I have read that for Hardware interrupts, only pins D2 and D3 can be used to generate interrupts. However, while connecting the MISO line, I saw that <a href="https://docs.arduino.cc/built-in-examples/arduino-isp/ArduinoISP" rel="nofollow noreferrer">here</a> it was mentioned that</p> <blockquote> <p>On some Arduino boards (see table above), pins MOSI, MISO and SCK are the same pins as digital pin 11, 12 and 13, respectively. That is why many tutorials instruct you to hook up the target to these pins.</p> </blockquote> <p>On every website I have searched, MISO is always connected to 12. <b>Is there any way to change the MISO line from 12 to 3, or will I have to resort to using Pin change interrupts?</b> Another way I can think of to bypass this is to connect D12 to D3, but I'm afraid this may cause complications in the circuit.</p>
<h1>My second answer ...</h1> <p>Your question, in bold, is a good example of an XY Problem. You asked:</p> <blockquote> <p>Is there any way to change the MISO line from 12 to 3, or will I have to resort to using Pin change interrupts?</p> </blockquote> <p>This is the X question. However the Y question is your goal:</p> <blockquote> <p>My end goal is to read information from an nRF24l01 module connected to my Arduino UNO ...</p> </blockquote> <p>I answered, in another answer, first about changing the MISO line from pin 12, and also pointed out that SPI transactions can generate interrupts.</p> <p>However, as Juraj pointed out in a comment, the Arduino in this case is the <strong>master</strong> and the nRF24l01 is the <strong>slave</strong> (from the SPI point of view).</p> <p>There is no way that a slave can burst into life and generate a message, and hence cause an interrupt. That is the master's job.</p> <p>As I read on <a href="https://lastminuteengineers.com/nrf24l01-arduino-wireless-communication/" rel="nofollow noreferrer">this page about the module</a> it has an IRQ pin described thus:</p> <blockquote> <p>IRQ is an interrupt pin that can notify the master when there is new data to process.</p> </blockquote> <p>So, your job is simplified, really. You don't need to detect when an SPI transaction starts (the Arduino will start the transaction), you need to connect the IRQ pin to an Arduino pin and detect that data is ready. Simple! Then you can easily use pin 2 or pin 3 if you want to use the &quot;hardware&quot; interrupts rather than the pin-change interrupts. (The pin-change interrupts are hardware interrupts too, though).</p>
93565
|arduino-uno|programming|keypad|
Problem when coding 4x4 keypad's key detection (without library)
2023-06-24T20:19:46.647
<p>Part of my current assignment involves reading the input from a 4x4 keypad connected to an Arduino UNO. While this may be done easily using &lt;Keypad.h&gt;, the project is being done with Tinkercad's online simulator, meaning I don't have access to that library. I have to do it the manual way.</p> <p>This is the code I've got so far:</p> <pre><code>#include &lt;Wire.h&gt; #define DIMENSIONS 4 const unsigned long period = 50; unsigned long prevMillis = 0; byte modo = 0; const byte rowsPins[DIMENSIONS] = {11, 10, 9, 8}; const byte columnsPins[DIMENSIONS] = {7, 6, 5, 4}; char keys[DIMENSIONS][DIMENSIONS] = { {'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} }; void setup() { Serial.begin(9600);// debug for(byte i = 0; i &lt; DIMENSIONS; i++){ pinMode(columnsPins[i], INPUT); digitalWrite(columnsPins[i], HIGH); pinMode(rowsPins[i], INPUT_PULLUP); } Wire.begin(); } void loop() { switch(modo){ case 0: Serial.print(&quot;Master (2) boot up\n&quot;); modo++; break; case 1: if(millis() &gt;= 1000){ modo++; } break; case 2: if (millis() - prevMillis &gt; period){ prevMillis = millis(); for(byte c = 0; c &lt; DIMENSIONS; c++){ pinMode(columnsPins[c], OUTPUT); digitalWrite(columnsPins[c], LOW); for(byte r = 0; r &lt; DIMENSIONS; r++){ if(digitalRead(columnsPins[r]) == LOW){ Serial.println(keys[r][c]); } } digitalWrite(columnsPins[c], HIGH); pinMode(columnsPins[c], INPUT); } } break; default: break; } } </code></pre> <p>(the &quot;modes&quot; and Wire.h are a different part of the assignment and not related to my issue)</p> <p>This code should, in theory, read the input from the connected 4x4 keypad and then print on the serial monitor which key was pressed. I've done a fair bit of searching, and other solutions for detecting key presses without the Keypad library aren't super different from what I've done here. However, for some reason, what I wrote is not working properly for me.</p> <p>On starting the simulation, the serial monitor prints 1, 5, 9, D continuously and repeatedly on a loop. Pressing the keys does sometimes print the appropriate character, but it does not stop the flood of 1s, 5s, 9s and Ds.</p> <p>I know for a fact that it's not a matter of the pins being misconnected, I've checked for that at least a dozen times by now. It's most certainly a matter of code... but I can't figure out where the problem lies.</p>
<p>In case 2:</p> <pre><code>digitalWrite(columnsPins[c], LOW); for(byte r = 0; r &lt; DIMENSIONS; r++){ if(digitalRead(columnsPins[r]) == LOW){ Serial.println(keys[r][c]); } } </code></pre> <p>Since you just wrote one of the column pins low, you can guarantee that one is going to read low. Did you mean to read the row pins?</p>
93566
|arduino-uno|
Instructables "Omnibot" -- using the "real" Uno R3 board
2023-06-24T20:34:28.883
<p>Step 4 of this instructable uses what seems to be a &quot;knock-off&quot; development version of the Uno R3 board, where an RF receiver is soldered to pads that don't exist on the R3 or R3 SMD boards:</p> <p><a href="https://www.instructables.com/OmniBot-Easy-Arduino-RC-Robots/" rel="nofollow noreferrer">https://www.instructables.com/OmniBot-Easy-Arduino-RC-Robots/</a></p> <blockquote> <p>...</p> <ol start="4"> <li>Locate available Gnd, Vcc, and Rx holes on your Arduino. (if using the recommended Arduino they can be found all near each other just below the ICSP pins.)</li> <li>Insert the tinned wires through their respective holes and solder on the back side. White to RX, red to 5V, black to GND.</li> </ol> <p>...</p> </blockquote> <p>I am completely new to Arduino, so I'm a little puzzled by the lack of VCC. Sounds like this is just power. Is there any reason I can't hook the RF receiver to the D0 (RX) pin, 5v out, and GND headers?</p>
<p>Yes, the holes they are showing it connected to are physically connected to the pins you mention. Connecting directly to those pins would be equivalent.</p>
93577
|usb|joystick|hid|raspberrypi-pico|
Expose two HID Joystick devices with single RP2040 board (Waveshare Pi Pico Zero)
2023-06-25T15:55:18.330
<p>I want to use a Waveshare Pi Pico Zero to connect two standard NES controllers to a computer over a single USB port.</p> <p>I'm using the <code>Waveshare RP2040 Zero</code> board definition from <a href="https://github.com/earlephilhower/arduino-pico" rel="nofollow noreferrer">https://github.com/earlephilhower/arduino-pico</a> which seems to provide a <code>Joystick</code> HID library that was compatible with this Teensy targeted <a href="https://github.com/GadgetReboot/Arduino/tree/master/Teensy/NES_To_USB" rel="nofollow noreferrer">NES_to_USB</a> sketch. However, that only works for a single NES controller.</p> <p>I found <a href="https://github.com/mcgurk/Arduino-USB-HID-RetroJoystickAdapter/blob/master/README.md" rel="nofollow noreferrer">Arduino-USB-HID-RetroJoystickAdapter</a> that supports two joysticks or NES controllers using a single board using the <a href="https://github.com/MHeironimus/ArduinoJoystickLibrary/tree/version-1.0" rel="nofollow noreferrer">MHeironimus ArduinoJoystickLibrary</a>. Unfortunately it seems that particular Joystick library only supports ATmega32u4 based Arduino boards (e.g. Leonardo, Pro Micro).</p> <h2>Ask</h2> <p>A solution for exposing two USB HID Joystick devices on a single Pi Pico Zero board. First prize is a drop-in library like <a href="https://github.com/MHeironimus/ArduinoJoystickLibrary/tree/version-1.0" rel="nofollow noreferrer">MHeironimus ArduinoJoystickLibrary</a> that is compatible with <a href="https://github.com/earlephilhower/arduino-pico%27s" rel="nofollow noreferrer">https://github.com/earlephilhower/arduino-pico's</a> RP2040 core. Happy to hear of more DIY solutions too, not sure if I'll be able to follow though :)</p>
<p>By selecting the Adafruit TinyUSB USB stack option (Tools-&gt;USB Stack-&gt;Adafruit TinyUSB) of the <code>arduino-pico</code> core instead of the default (Pico SDK) the USB HID descriptors can be configured directly to expose two HID gamepads.</p> <p>The disadvantage of this approach is that the easy to use preconfigured devices (e.g. <code>Joystick</code>, <code>Mouse</code> and <code>Keyboard</code>) are not configured, but this gives you the option to use the full flexibility of TinyUSB to configure USB devices. While I've used it with my Waveshare Pi Pico Zero board it should work with any Arduino board that <a href="https://github.com/adafruit/Adafruit_TinyUSB_Arduino/tree/master" rel="nofollow noreferrer">Adafruit TinyUSB</a> supports.</p> <p>Here is a test sketch that sets up a HID device with two gamepads similar to the &quot;Hey how about two players?&quot; example in <a href="https://eleccelerator.com/tutorial-about-usb-hid-report-descriptors/" rel="nofollow noreferrer">https://eleccelerator.com/tutorial-about-usb-hid-report-descriptors/</a>. I modified the <a href="https://github.com/adafruit/Adafruit_TinyUSB_Arduino/blob/ffaa85e9e7cff1b5cc87451082f8fa0a829dae7b/examples/HID/hid_gamepad/hid_gamepad.ino" rel="nofollow noreferrer">Adafruit TinyUSB hid_gamepad.ino example</a> by adding a second Gamepad report and shortening the &quot;demo&quot; loop to save space:</p> <pre class="lang-c prettyprint-override"><code>/********************************************************************* Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! MIT license, check LICENSE for more information Copyright (c) 2021 NeKuNeKo for Adafruit Industries All text above, and the splash screen below must be included in any redistribution *********************************************************************/ #include &quot;Adafruit_TinyUSB.h&quot; // NB NB!!! Select &quot;Adafruit TinyUSB&quot; for USB stack // HID report descriptor using TinyUSB's template uint8_t const desc_hid_report[] = { TUD_HID_REPORT_DESC_GAMEPAD(HID_REPORT_ID(1)), // First gamepad report-id 1 TUD_HID_REPORT_DESC_GAMEPAD(HID_REPORT_ID(2)) // Second gamepad report-id 2 }; // USB HID object. For ESP32 these values cannot be changed after this declaration // desc report, desc len, protocol, interval, use out endpoint Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROTOCOL_NONE, 2, false); // Report payload defined in src/class/hid/hid.h // - For Gamepad Button Bit Mask see hid_gamepad_button_bm_t // - For Gamepad Hat Bit Mask see hid_gamepad_hat_t hid_gamepad_report_t gp[2]; // Two gamepad descriptors void setup() { #if defined(ARDUINO_ARCH_MBED) &amp;&amp; defined(ARDUINO_ARCH_RP2040) // Manual begin() is required on core without built-in support for TinyUSB such as mbed rp2040 TinyUSB_Device_Init(0); #endif Serial.begin(115200); usb_hid.begin(); // wait until device mounted while( !TinyUSBDevice.mounted() ) delay(1); Serial.println(&quot;Adafruit TinyUSB HID multi-gamepad example&quot;); } uint8_t gp_i = 0; void loop() { if ( !usb_hid.ready() ) return; Serial.print(&quot;Testing gamepad nr: &quot;); Serial.println(gp_i); // Reset buttons Serial.println(&quot;No pressing buttons&quot;); gp[gp_i].x = 0; gp[gp_i].y = 0; gp[gp_i].z = 0; gp[gp_i].rz = 0; gp[gp_i].rx = 0; gp[gp_i].ry = 0; gp[gp_i].hat = 0; gp[gp_i].buttons = 0; // gp_i + 1 is the HID report-id, i.e. 1 for first gamepad and 2 for the // second, as defined in desc_hid_report[] above. usb_hid.sendReport(gp_i + 1, &amp;gp[gp_i], sizeof(gp[gp_i])); delay(2000); // Random touch Serial.println(&quot;Random touch&quot;); gp[gp_i].x = random(-127, 128); gp[gp_i].y = random(-127, 128); gp[gp_i].z = random(-127, 128); gp[gp_i].rz = random(-127, 128); gp[gp_i].rx = random(-127, 128); gp[gp_i].ry = random(-127, 128); gp[gp_i].hat = random(0, 9); gp[gp_i].buttons = random(0, 0xffff); usb_hid.sendReport(gp_i + 1, &amp;gp[gp_i], sizeof(gp[gp_i])); delay(2000); // select the other gamepad gp_i = (gp_i + 1) % 2; } </code></pre> <h2>Linux HID Malarkey</h2> <p>For some reason the Linux kernel by default ignores multiple reports of the same type of HID device. I.e. a device with a mouse, keyboard and joystick device reports are no problem, but if a device has multiple of the same HID reports, say, two gamepads, Linux will only see the first instance. To enable multiple instances the <code>HID_QUIRK_MULTI_INPUT</code> setting must be enabled for the specific USB device.</p> <p>These instructions worked on Ubuntu 22.04, you may need to adjust them for your distro.</p> <p>After programming the example sketch I could see the ID of my Pi Pico USB device with `lsusb:</p> <pre><code>$ lsusb ... Bus 001 Device 011: ID 239a:cafe Adafruit RP2040 Zero ... </code></pre> <p>Note down the USB device identifier (<code>239a:cafe</code>) and create a file in <code>/etc/modprobe.d</code> to configure the <code>usbhid</code> module:</p> <pre><code>$ echo &quot;options usbhid quirks=0x239a:0xcafe:0x040&quot; | sudo tee /etc/modprobe.d/adafruit_hid_quirk.conf $ sudo update-initramfs -u # Requires a reboot to take effect, e.g.: $ sudo shutdown -r now </code></pre> <p>The <code>0x239a:0xcafe</code> is from the <code>lsusb</code> output and <code>0x040</code> is the magic number to enable <code>HID_QUIRK_MULTI_INPUT</code> mode. We need <code>update-initramfs</code> since <code>usbhid</code> is usually loaded too early in the boot process for the settings from <code>/etc/modprobe.d</code> to take effect without it being in the <code>initrd</code>.</p> <p>Once you have rebooted you can check if the <code>usbhid</code> setting took effect:</p> <pre><code>$ cat /sys/module/usbhid/parameters/quirks 0x239a:0xcafe:0x040,(null),(null),(null) </code></pre> <p>and you should see two joystick devices after programming the sketch:</p> <pre><code>ls /dev/input/js* /dev/input/js0 /dev/input/js1 </code></pre> <h2>Testing</h2> <p>An easy way to test is to navigate to <a href="https://gamepad-tester.com/" rel="nofollow noreferrer">https://gamepad-tester.com/</a>. After a short period you should see something like:</p> <p><a href="https://i.stack.imgur.com/hBuG2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hBuG2.png" alt="Player 1 and Player 2 Gamepads" /></a></p> <p>You should see Player1's values toggle and then Player2's values until you unplug your pico.</p>
93582
|arduino-mega|arduino-cli|
Can't install to arduino mega 2560 using arduino-cli, but can using IDE
2023-06-26T11:44:48.197
<p>I have a MKS GEN L v1.0 3dprinter board that works fine uploading using the IDE. But I need to install to it using the arduino-cli.</p> <p>For some reason, the command <code>arduino-cli board list</code> says that the board has an unknown FQBN. Which is fine, I guess. I guess I don't know how to compile &amp; upload without the FQBN.</p> <p>The options I need selected (which work in the IDE) are:</p> <ul> <li>Board: Arduino/Genuino Mega or Mega 2560</li> <li>Processor: ATmega2560</li> <li>Programmer: AVRISP mkII</li> </ul> <p>I don't understand why these options aren't clearly available in the arduino-cli.</p> <p>I ran these commands: <code>arduino-cli core install arduino:avr and arduino-cli core install arduino:megaavr</code></p> <p>I ran <code> arduino-cli board list</code>. It says /dev/ttyUSB0, serial, Serial Port (USB), &quot;Unknown&quot; for FQBN....</p> <p>I run <code>arduino-cli compile Marlin</code>. It says &quot;unknown FQBN&quot;.</p> <p>So how do I install using the same parameters in the IDE?</p>
<p>I would guess, that the arduino-cli doesn't recognize your boards FQBN, since it is not a genuine Arduino board. My Arduino Nano clones (with the CH340 USB-Serial-chip) aren't recognized as Arduino Nanos either. For me that's the same with the Arduino IDE.</p> <p>Though, since you already know what board you have, you can find the FQBN yourself by looking through the list in the output of</p> <pre><code>arduino-cli board listall </code></pre> <p>or if you want to narrow the list down a bit:</p> <pre><code>arduino-cli board listall avr </code></pre> <p>There you will find the line with the Megas FQBN:</p> <pre><code>Arduino Mega or Mega 2560 arduino:avr:mega </code></pre> <p>Then you need to know, which Serial interface/COM port your Arduino has. This is done analog to the Arduino IDE: Check the list of connected boards via</p> <pre><code>arduino-cli board list </code></pre> <p>If you cannot identify it directly from the list, you might want to disconnect and connect it again, to see, what entry in this list reappears again.</p> <p>Then compile and upload can be done like this (be sure to input your own COM port/Serial interface, if it differs from this):</p> <pre><code>arduino-cli compile --fqbn arduino:avr:mega arduino-cli upload --fqbn arduino:avr:mega --port /dev/ttyUSB0 </code></pre> <p>while being in the sketch folder.</p>
93595
|isr|
How to get around passing a variable into an ISR
2023-06-27T17:59:45.650
<p>Okay so you aren't able to pass a variable into in ISR. This is causing problems for me. I'm using a rotary encoder, and I need it to be connected to an interrupt pin and running a ISR. When using this method, no pulses are ever skipped and the knob works great.</p> <p>Currently I have the ISR setup like this:</p> <pre><code>void vhISR() { // this checks the PINE register for a 1 or 0 on the 5th bit (or 6th) // I'm bit shifting the result so that variable is either true or false for comparison, not 16/0 or 32/0 rotCurrentA = (PINE &amp; B00010000) &gt;&gt; 4; rotB = (PINE &amp; B00100000) &gt;&gt; 5; if (rotCurrentA != rotLastA) { if (rotCurrentA != rotB) // cw { voltageHigh += knobResolution; rotLastA = rotCurrentA; } else // ccw { voltageHigh -= knobResolution; rotLastA = rotCurrentA; } } } </code></pre> <p>The code simply varies voltageHigh by 0.1V increments. The problem is this: I need to do this same 0.1 variations on several other variables, depending on which one I select. I need to increase/decrease a voltageLow, a timer, and a resistance, all that need +/- 0.1 increments (but on different ranges. For instance, voltLow is somewhere between 0.1 &amp; 5, and VH is somewhere between 6 &amp; 10). Normally what I would do is just pass the variable I needed by reference into the function and have the function increment/decrement that variable....but an ISR is not a normal function and you cannot pass a variable into it.</p> <p>How do I get around this? I'm not sure if that's enough information to go off of let me know.</p>
<blockquote> <p>Okay so you aren't able to pass a variable into in ISR ...</p> </blockquote> <p>Not as such, because the ISR is triggered by hardware, and therefore you don't pass arguments to it.</p> <p>However there is nothing stopping you having a global variable which the ISR can access (preferably declared <code>volatile</code>) so the ISR can change its behaviour depending on what the global variable holds.</p>
93606
|arduino-ide|esp32|wifi|wireless|esp32-cam|
Does ESP32 can support WIFIDirect
2023-06-28T07:22:33.720
<p>I would like to establish a simple P2P connection between an ESP32 and an Android device without the use of an access point. I should be able to send and receive data from the ESP32 through the established connection. Is this possible, and if not, are there any alternative solutions?</p>
<p>From my research i for to know that we can't use wifi direct for esp32 i found an alternative for my problem!!!!</p>
93608
|arduino-uno|serial|python|serial-data|
How to ignore garbage values in serial communication between arduino and python
2023-06-28T09:47:55.133
<p>I have <code>arduino uno</code>. I am trying to send and receive serial data from arduino to python. I have <a href="https://i.ebayimg.com/images/g/49wAAOSw%7EXhZlUdj/s-l1200.jpg" rel="nofollow noreferrer">usb to uart converter</a>. I have connected its <code>tx</code> to <code>rx</code> of Arduino and <code>rx</code> to <code>tx</code> of Arduino and <code>gnd</code> is connected to <code>gnd</code>. I have connected this usb to my laptop where I have written below python script:</p> <pre><code>import serial ser = serial.Serial(port='COM6') res = ser.read(10) print(bytes.hex(res)) data = b&quot;\x7E\x7E\xAA\x03\xAB\x77&quot; ser.write(data) ser.close() </code></pre> <p>In above code, I am first reading the serial data, once the data is received, I sent out some hex packets. Below is the Arduino code:</p> <pre><code>void setup() { Serial.begin(9600); } void loop() { const byte message[] = {0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03 }; Serial.write(message, sizeof message); Serial.println(&quot;data sent&quot;); delay(1000); char buffer[6]; if (Serial.available() &gt; 0) { int size = Serial.readBytesUntil('\x77', buffer, 6); for (int i = 0 ; i &lt; size ; i++) { Serial.println(buffer[i], HEX); } } } </code></pre> <p>In above code, I am first sending out the hex packets (which is received fine on python side) and then it waits for serial data. Once serial data is available to read, it reads it unitll <code>\x77</code> and prints out all data. This is received on serial console of Arduino:</p> <p><a href="https://i.stack.imgur.com/AxAlE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AxAlE.jpg" alt="enter image description here" /></a></p> <p>You will notice that it has received the data but there are some extra <code>FF</code> being received. Why have we recived these <code>FF</code>. Also in the python code, we know we are sending data of length 6 so accordingly we have defined <code>char buffer[6]</code> in arduino but what if we have to receive data which we do not what length it will be. Please help. Thanks</p>
<p>The effect that you see is <a href="https://en.wikipedia.org/wiki/Type_conversion#Type_promotion" rel="nofollow noreferrer">type promotion</a>, in the C++ standard called &quot;integral promotion&quot;, which happens implicitly. Values of type <code>char</code> are cast to <code>int</code>. Commonly, and in your case too, the <code>char</code> is by default signed.</p> <p>The values <code>0xAA</code> and <code>0xAB</code> have a set most significant bit, which commonly designates a <em>negative</em> value in <a href="https://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow noreferrer">two's complement</a>. This holds true for your case. And so these negative values are cast to the same negative values, but in full width of an <code>int</code>. In your case, an <code>int</code> has 32 bits.</p> <p>Hex <code>0xAA</code> as (by default signed) <code>char</code> is <code>-86</code> decimal. And <code>-86</code> decimal as (by definition signed) <code>int</code> is <code>0xFFFFFFAA</code> hex.</p> <p>Printed as hex, all bits are shown. So you see all these <code>FF</code>.</p> <p>The solution is to mask only the interesting lower 8 bits:</p> <pre class="lang-cpp prettyprint-override"><code> { Serial.println(buffer[i] &amp; 0xFF, HEX); } </code></pre>
93614
|arduino-nano|hardware|
arduino nano fried (TWICE!!)
2023-06-29T05:13:44.100
<p>Having the skill to be stupid has managed to fry not one but 2 Arduino nano boards in the same place (I think it is because this part that smoke came out from of has a lump on it that was not there before). I have heard that Arduino boards are open source, but I have not found anything explaining which part I have fried. Therefore, I don't know the function, so I cannot replace it. It would be greatly appreciated if anyone could point out the part name or a link to a shop with it in stock so I could purchase it or give me a copy of the PCB schematics to make my own Arduino. I think the part is called the &quot;usb diode&quot;<a href="https://i.stack.imgur.com/0J06h.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0J06h.jpg" alt="arduino nano" /></a> Thanks</p>
<p>From the several Arduino Nano schematics I've found, the &quot;fried&quot; part you identify as the USB diode, might be a MBR0520 Schottky diode or a similar diode with a low forward voltage drop. These parts are polarized and should be replaced in the same orientation as the original part.</p> <p>There is no guarantee that this is the only damaged component on your Nano.</p>
93619
|arduino-uno|lcd|gps|speed|
Speedometer for car
2023-06-29T09:02:11.310
<p>I want to build a speedometer for a car using Arduino UNO. For the display, I'm using an LCD screen that will be located behind the steering wheel. For context, I'm building the speedometer for a Tesla, which does not have a speedometer behind the steering wheel. Because this speedometer is for a car, and for driving purposes, I need the speedometer to be very accurate. I am planning to calculate the current speed of the car using a GPS module, but not sure <strong>which GPS module would have the best accuracy but is not too expensive?</strong> I am also open to other methods that may be available to measure current speed.</p>
<p>I built a GPS speedometer for an old Corvette using the TinyGPSPlus library with a GY-NEO6MV2 NEO-6M with an Arduino Uno. <a href="http://www.carols62.com/speedo" rel="nofollow noreferrer">http://www.carols62.com/speedo</a> Speed readings were very accurate.</p>
93626
|programming|esp32|wireless|networking|espressif|
How do I set the DHCP pool for an ESP-WIFI-MESH?
2023-06-30T01:57:37.237
<p>I'm building a mesh with ESP32 dev kits (ESP32-DevKitC V4) using the ESP-IDF VS Code extension and the ip_internal_network example project. The code for the <a href="https://github.com/espressif/esp-idf/tree/master/examples/mesh/ip_internal_network" rel="nofollow noreferrer">example</a>, <a href="https://github.com/espressif/esp-idf/tree/master/examples/common_components" rel="nofollow noreferrer">common project components</a>, and the <a href="https://github.com/espressif/esp-idf/tree/master/components" rel="nofollow noreferrer">API</a> is linked. When the mesh nodes power on and build the network, they use the 10.0.0.0 network. How do I change the internal mesh network?</p> <p>My operating assumptions:</p> <ul> <li>The root node receives an external IP address from an external DHCP server.</li> <li>The root node acts as an internal DHCP server to the mesh nodes.</li> <li>The root node performs network address translation.</li> <li>Its DHCPv4 server runs on the lwIP TCP/IP stack.</li> <li>Internal IP addresses are leased from a pool governed by the root node (but it's possible that nodes request a particular address from this network and the server provides the next available; I'm unsure).</li> <li>The network address is 10.0.0.0/8 (I inferred the subnet mask; it could be anything).</li> </ul> <p>Obviously, the first thing I tried was searching for this network address in files. There was nothing in the project workspace and too many hits in the repo to be useful. I tried decimal and hex with no luck.</p> <p>I also tried tracing the function that prints the IP address to the serial terminal to find the IP var, and working backwards to locate the statement that initializes this variable. I'm still reading event handler API documentation so I haven't made quick progress here either.</p> <p>The programming interface is split among ESP-IDF component header files, build systems (CMake and Ninja?), KConfig options and host tools (idf.py?). C, FreeRTOS and build systems are all new to me so I would appreciate if someone with more experience could weigh in. Thank you.</p>
<p>I figured it out; it's in mesh_netif.c:43. I'm not sure why I passed over this file initially but it caused a lot of unnecessary headache. The relevant struct is this:</p> <pre><code>const esp_netif_ip_info_t g_mesh_netif_subnet_ip = { .ip = { .addr = ESP_IP4TOADDR( 192, 168, 0, 1) }, .gw = { .addr = ESP_IP4TOADDR( 192, 168, 0, 1) }, .netmask = { .addr = ESP_IP4TOADDR( 255, 255, 255, 0) }, }; </code></pre> <p>I changed the 10.0.0.0/16 network to 192.168.0.0/24. The root node assumes the address in <code>.ip</code>. I assume child nodes check the ARP table and increment until an address is available, then send the DHCPREQUEST for that address to root. I say &quot;assume&quot; because although root runs lwIP, I am not sure child nodes run lwIP (they may just communicate in layer 2 ESP-WIFI-MESH frames).</p> <p>Make sure your DHCP server publishes an IPv4 DNS address or <code>ESP_ERROR_CHECK(esp_netif_set_dns_info(netif, ESP_NETIF_DNS_MAIN, &amp;dns))</code> (mesh_netif.c:70) will fail and cause the board to power cycle. A way around this is to enable <code>Use global DNS IP</code> in menuconfig. The global DNS field is in hex format, so 10.32.64.128 is written 0x0A204080.</p> <p>Mesh-internal IP messages are published with MQTT so the name/address <code>.broker.address.uri</code> in mqtt_app.c:74 must be accessible from the router.</p>