Wednesday, 4 December 2019

c - Interfacing switch and LED


I am trying to write a program in which I am interfacing a switch and a LED. I want a program so that when I press the switch the LED turns on and when I press again that led turns off. Right now I have made a program in which when I press the switch the LED turns on and then goes off.


void main()
{
DDRA=0x01; // Interfacing LED at PORTA.0
DDRB=0xFE; // Interfacing Switch at PORTB.0
PORTB=0xFF;


while(1)
{
if(PINB==0xFE)
{
PORTA=0x01;
}
else
{
PORTA=0x00;
}

}
}

Answer



I guess, you are dealing with a push button and not a switch. So Pin0 on PORTB (PB0) stays LOW as long as you are pushing the button, the if statement is fulfilled and your LED will be turned on. But once you release the button, PB0 will go back HIGH and the else branch will be executed, thus your LED will be turned off immediately.


You need an additional variable, which changes only on button pushes and remains unchanged on button releases. Then you can control the LED with this variable.


Example:


void main()
{
DDRA |= (1< DDRB &= ~(1<

uint8_t status = 0;

while(1)
{
if(!(PINB & (1< {
status = !status;
}


if(status)
{
PORTA |= (1< }
else
{
PORTA &= ~(1< }
}
}


In addition have a look at this question about bit operations. Very useful when you want to change only one bit on a PORT and let the rest unchanged.


A simpler soultion is to toggle the LED controller pin itself on button pushes. To do so, the XOR operator: ^ could be used as follows PORTA ^= (1<. This means that we XOR 1(HIGH) with the current value of the PIN.



  • If the LED is on, the current value of the PIN is 1 (HIGH), which we XOR with another 1. The result will be 1 XOR 1 = 0 so the LED will be turned off.

  • Now, when the LED is off, the current value of the PIN is 0 (LOW), which we XOR with 1 again. The result will be 0 XOR 1 = 1 so the LED will be turned on.


Example:


void main()
{

DDRA |= (1< DDRB &= ~(1<
while(1)
{
if(!(PINB & (1< {
PORTA ^= (1< }
}

}

Tuesday, 3 December 2019

How to make a 7 to 3 priority encoder?



I'm trying to make a 7 to 3 priority encoder for a circuit diagram for a class. The problem is that we have to take in a 7 bit number and output a 3 bit answer representing the maximum number of consecutive ones in the input.


Example:


0011100 = 011 (3)
1111111 = 111 (7)
0000000 = 000 (0)

The issue at the moment is that regardless of the input, it is always outputting 111 (7).


I have circuits for handling every possible combination of consecutive ones in the input, and am then piping that into a 7 to 3 priority encoder, but for some reason the encoder is not working the way it should. What am I doing wrong? Or is there a better way that I should be doing this?


Original Circuit diagram:


circuit



Attempt 2:


another try




pcb design - Encoding version or configuration on PCB


I need to encode information about either version or configuration on the board/electrically, so the firmware can detect which board layout is used.


What options are possible and what are their pro/cons?



Answer



Off the top of my head, two easy solutions come to mind.



  1. Have n lines attached to the GPIO of your microcontroller. Tie these high or low depending on your board version. This would give you \$2^n\$ board configuration options. This would use n pins on your microcontroller. Static current draw would be negligible.

  2. Have an input to the microcontroller's ADC and use a voltage divider with different values depending on the board configuration. This would only use a single microcontroller pin. This has the disadvantage that there will be static current draw through the divider. It would also be prone to BOM errors, while the first suggestion is hard wired to the board.



Both of these suggestions do have a weakness in that the end user could easily alter them, say to open up "locked" features. This may not be a concern for you, but something to bear in mind.


stm32 - TIM2 DMA configuration for stm32h7


My problem: I can't configure DMA to working properly on Input Capture event. Data doesn't transfered and error occurs.


static void my_TIM2_initInputCaptureTimer(void) {

// enable clock source for timer
RCC->APB1LENR |= (0x1 << 0);

// set prescaler to 200
TIM2->PSC = 200 - 1;

// choose TIM2_CH1 input
TIM2->TISEL |= (0x0 << 0);
// set channel 1 as input mapped on TI1
TIM2->CCMR1 |= (0x1 << 0);
// digital filter length (0)
TIM2->CCMR1 |= (0x0 << 4);
// rising & falling edge

TIM2->CCER |= (0x1 << 1);
TIM2->CCER |= (0x1 << 3);
// prescaler to (0)
TIM2->CCMR1 |= (0x0 << 2);
// enable DMA interrupt & Capture/Compare interrupt
TIM2->DIER |= (0x1 << 9) | (0x1 << 1);
// capture enabled
TIM2->CCER |= (0x1 << 0);
// reset registers WARNING: need for preloading PSC
TIM2->EGR |= (0x1 << 0);


// enable TIM3 timer
TIM2->CR1 |= TIM_CR1_CEN;
// enable interrupt request
NVIC_EnableIRQ(TIM2_IRQn);
// set priority
NVIC_SetPriority(TIM2_IRQn, 1);

}


DMA configuration:


static void my_DMA_init(void) {
// enable DMA1 clocking
RCC->AHB1ENR |= (0x1 << 0);
// clear EN bit to 0
DMA1_Stream0->CR &= ~(0x1 << 0);
// safeguard EN bit reset
while (DMA1_Stream0->CR & 0x1);
// check LISR HISR registers
if ((DMA1->HISR == 0) && (DMA1->LISR == 0))

printf("status registers is clear\r\n");
else
printf("status register is not clear -- DMA wont start\r\n");
// set peripheral addres
DMA1_Stream0->PAR = TIM2_CCR1_Address;
// set memory addres
DMA1_Stream0->M0AR = (unsigned int)buffer;
// set total number of data items
DMA1_Stream0->NDTR = 10;


// NOTE: configurate TIM2_CH1 interrupt route
// set DMAMUX to route request (TIM2_CH1)
DMAMUX1_Channel0->CCR |= 18U;

// set DMA priority (very high)
DMA1_Stream0->CR |= (0x3 << 16);
// set memory data size (32)
DMA1_Stream0->CR |= (0x2 << 13);
// set peripheral data size (32)
DMA1_Stream0->CR |= (0x2 << 11);

// set memory addres increment (enable)
DMA1_Stream0->CR |= (0x1 << 10);
// set peripheral addres increment (disable)
DMA1_Stream0->CR |= (0x0 << 9);
// set circular buffer mode (enable)
DMA1_Stream0->CR |= (0x1 << 8);
// set data transfer direction (peripheral to memory)
DMA1_Stream0->CR |= (0x0 << 6);
// set transfer complete interrupt
DMA1_Stream0->CR |= (0x1 << 4);

// set transfer error interrupt
DMA1_Stream0->CR |= (0x1 << 2);
// enable DMA1
DMA1_Stream0->CR |= (0x1 << 0);
// enable IRQ
NVIC_EnableIRQ(DMA1_Stream0_IRQn);
printf("DMA1_Stream0 %u \r\n", (DMA1_Stream0->CR & 0x1));
}

Interrupt routines:



void TIM2_IRQHandler(void) {

InCapTick = TIM2->CCR1;
// reset interrupt flag
TIM2->SR = 0;

tick = systick_ms;
flag++;
}


void DMA1_Stream0_IRQHandler(void) {

printf("within\r\n");
printf("LISR: %u \r\n", DMA1->LISR);
// clear interrupt flag
DMA1->LIFCR |= (0x1 << 3) | (0x1 << 5);

}

Full compiled project (gcc-arm\make) for thoose who interested: https://drive.google.com/open?id=1fwns5fKexGWJl64UDeYfDyFmSFA9BURZ



(stm32h743zi-nucleo board) expected behaviour: (when you press user button (the blue one) ->PG0 pin get SET (1) state -> so input capture pin (PA5, they should be connected via jumper) get low-high transition and capture first value (output it via com-port) when you free button, input capture pin get high-low transition and capture another value(output it via com-port), but none of this events do not kick start DMA request.


Data will be outputted via com port with 115200 speed.



Answer



DMA was initialized correctly. The problem was: buffer array wasn't initialized into any SRAM memory area, so when DMA trying to reach that memory via AHB (it's not possible) DMA crash with error and set TEI_flag (transfer error interrupt).


The easises way to make this work (and obviously it isn't correct way but for acquaintance purposes it works)


#define Destination_Address ((unsigned int)0x30000000)
DMA1_Stream0->M0AR = Destination_Address;

0x30000000 -> is boundary of SRAM1 memory


and you need first enable SRAM1\2\3:



static void my_SRAM_init(void) {
// activate SRAM1\2\3
RCC->AHB2ENR |= (0x7 << 29);
}

you can reach that area with:


  uint32_t *Ptr_Dest = (uint32_t *)Destination_Address;
printf("buffer: %lu %lu \r\n", *Ptr_Dest, *(Ptr_Dest + 1));

For those this won't work or some UB happens (corrupt data, strange placing) possible reasons:




  1. Cache (enabled cache could corrupt data)

  2. Your addresses should be aligned with PSIZE and MSIZE


Example: if your MSIZE and PSIZE is 32bit address must end on 0x4


I hope this will help someone, because this was huge pain in my ass for straight 3 days, I hate it.


serial - Problem connecting UART Wifi Module to PC


As refereed to my old question ( Connect UART WiFi module to PC ) which has been solved that days, I have a UART Wifi module ( this one ) and unfortunately I have problem again ! The point is, this time I can't remember what's the last configuration of this module.


What I did this time:


1. Connect Power Source: Connect modules VCC and GND to 3.3V external power source.



2. Connect USB to Serial ( with TTL Logic ): Connect module's RX to my converter's TX and TX to RX. (in 3.3V mode, you can see the image of my converter in the end of this question and also Before I connect it, I tested it and it works pretty well with my other circuits. ). I didn't connect converter's ground to module's ground


3. Install terminal program: Install Download and Install Eltima Software's Advanced Serial Port Terminal which I tested this module with it before and it works well.


4. Power up the module and send 3 pluses "+++" after 2 seconds: I power up the module and send +++ with all possible baud rates as a string (or text file) with Eltima, but I don't get the "+OK" as response from the module.



1- I tried connecting converter's and module's grounds together and tried again with all possible baud rates but nothing happened.


2- I tried 5v mode of my converter but no luck !


3- I tried connecting nReset and nCTS/MODE/GPIO pins to ground for a while and some other blind attempts but no wish...


BTW, when I start my module one of the lights is blinking and the other is just not blinking but is on.


I think I missed something funny here but I don't know what it is. Please help me find a solution to get this module work. I really messed up with it again!


What can I do to get "+OK" from my module after sending "+++" after 2 seconds as a text file ?



schematic


simulate this circuit – Schematic created using CircuitLab


This is my USB-TTL converter This is my WiFi module




pcb design - How to go from a development board to a production board?


Ok, I am a software guy and new to electronics. My product needs a small computer and currently I have developed everything on development boards like raspberry pi and such. As the development board does not have all the hardware that I need, I have added the missing hardware through USB and GPIO's but obviously the production board can not be like that.


So my question is how do I go to the next step to come up with the production version of my hardware? In other words, what would a hardware specialist do to turn its development board into a production ready product? These are what comes to my mind


1> Get the schematic of current development boards like the pi (or any publicy available schematic that is close to my basic hardware requirement like the cpu type and such) and try to find some one to add the missing pieces to it and re-organize the position of the ports (like usb port and such) to your desire and make it the production product. This is possible because CAD software like Eagle are very powerful and adding a couple of more hardware chips (say like a temperature sensor) and changing the locations of ports is fast to do.


2> Are you stupid? The design of such board is very complex, specially a computer like pi and you have to hire a board design consulting company (or whatever they are called) to design this production ready board for you. If so, how should I talk to? US or China?


3> If your are building a production level hardware, you need to have the design team in-house and you need to hire the right ppl with such expertise to do so. This is not something that you want to contract out. you must have it internally as practice has shown. If it was a simple board you could have done yourself, but a computer needs a lot of work (although there are many commonality among them) and you have to start from scratch as there are so many details involved.



Oh, my production size is not big. I need 5,000 units every 6 month. The main thing is the a good reliable final board design with my requirements to get it to a PCB manufacturer.


As you see, I am sort of lost in this hardware manufacturing space and your insight and personal experience will be very valuable to me.


Many Thanks!



Answer



Development to 50,000 units every six months? I wish all my projects went like that :) If you don't have the experience there's no reason you can't hire a consulting company to make the board for you. It won't be cheap but they'll get the job done. It's a little riskier too if you don't know the guys you're hiring enough to trust them with the design.


50,000 units is not a small run so if you're really going to do that you should have no trouble finding a manufacturer here in the US or over seas who would work with you. Keep in mind you'll need the cash to buy your parts, and order your boards upfront.


So I'll go through each approach for you:


1.) Do it yourself


Making a Schematic


Start with the reference schematics you have, then find yourself a tool you like. I'm an Orcad guy, I've used Mentor and many others. Just pick one you're comfortable with and you can afford (Eagle is cheap I understand). If you're lucky you can get your reference board schematics in a format that you can modify. If not you'll have to create parts in your schematic tool. Creating parts basically involves looking up each parts datasheet to get it's pin out and then creating a symbol with pin names and numbers to match. Then you can use those symbols in your schematic and connect them up the way they need to be. That's the simple version, oh and double and triple check that your schematic symbols match the pins on the datasheet.



Here's some links to schematic tools



Layout Your PCB


Now you have a schematic that's a big step, from here you could give that schematic to a contractor and ask him to do the layout for you (that's the drawing of the actual traces on the board). You could also opt to do it yourself, it's both easier and harder than the schematics. Drawing connections and placing parts isn't too hard, but knowing where to put things, how many layers, how to route traces correctly for things like cross talk and emissions, and especially how to do the decoupling correctly takes a little know how. If you're committed to it and you review the reference schematics for each of your pieces you can make it through. Oh and you'll spend a lot of time looking at datasheets, and drawing footprints if the standard ones don't work. If you ever took a CAD class in school it's pretty much like that. Ask questions here if you go this route.


Here's some links to layout tools, there are certainly others



Decoupling, SI, and power design


Decoupling, Signal integrity and power design are huge areas and too detailed for this post. However if you're going to get into pcb design you should know them. I could write posts on top of posts about it :) I'd at least check out these two guys and get their books, or at least browse around their websites:



Both of them are pretty nice guys and will answers questions if you ask them, you can also join the SI-List over at http://www.freelists.org/archive/si-list It's a great place to ask questions.



That may be more than you're ready to do so there levels of how involved you can get and how involved you need to be on this front. For your design I'd suggest following the app notes and reference design and keeping all your caps as close as possible.


From ok to better here's some ways you can handle signal/power integrity:



  • Ignore it (NO!!! :)

  • Just use a bunch of the highest value smallest size caps you can get and keep them close to your chips Design your own decoupling cap system in pspice, and then wing it on the placement of them in layout

  • Use an excel calculator like the one Altera provides for it's tools http://www.altera.com/literature/ug/pdn_tool_stxiv.zip (pretty useful if you have no other tools)

  • Design your cap system in spice, and then use a full simulator


I've done all of those depending on where I was and what I can afford. When I can get it I love to use Sigrity to do both SI and PI analysis http://www.sigrity.com/ They're actually owned by Cadence now. No affiliation here I just really like their tools.


You can also hire guys to do it for you, I've only ever used http://www.teraspeed.com/ for that but I know there are others. It's not cheap though!



Generating Files To Send To Board House


Once you finish your layout you'll need to quadruple check it because you're about to pay actual money for bare boards. At this point you can generate cad files, either Gerbers or ODB++ files. You send these files to a board house to get a quote. Pricing is based on complexity and how impatient you are. You should probably order a small number, ask them for say 10 or best value that should give a good place to start. ( I should point out that there are some board houses that offer their own free software tools if you want to go that route, it restricts you to them but hey it's free).


You should review these gerber files too not just generate them I've always used the free GC-Prevue from http://www.graphicode.com/GC-Prevue. There's also a nice commercial tool out there that some of my cad guys love called Blueprint http://www.downstreamtech.com/support-viewers.php. There's others too but I always like to look at the final design on a projector and pick out problems. I'll also print the top and bottom layers out in hi-res on a laser printer and make sure the parts fit the footprints I made. If I'm feeling particularly obsessive I might print all the layers on transparencies and look them over. Really, really obsessive I might send the top and bottom layers out as a two layer board just to see how things fit together.


Order Your Proto Parts


At this point you should be ordering parts for your proto-run so they arrive when your boards do. If you don't think you can handle soldering yourself you'll need to pick an assembly house to do you run for you. I can think of a few that handle small runs and they should be easy to find. You'll need to send them your gerbers ahead of time so they can make a solder stencil for you board. Then send them the parts kit, and ship them the bare boards when they come in.


Bare PCB Production


There are a lot of good board houses out there: Cheaper ones like PCB Express ( the guys with the free software) http://www.pcbexpress.com/ I also use Advanced Circuits in Colarado a lot for my hobby projects, and some fast proto types as well http://www.4pcb.com/ They have an assembly service too that I've never used.


For my US production PCBs I use DDI http://www.ddiglobal.com/ now via systems http://www.viasystems.com/ or Vermont Circuits http://www.vtcircuits.com/


PCB Assembly Services


For small to medium US assembly services I use IMS in NH http://www.imscorp-us.com/ They'll do 10 boards for me or 10,000 and their quality is great. I've used them for years. For crazy big runs I'd use a Flextronics or someone like that but that's a whole different league, and not what you're looking for. There are plenty of others, probably even near you. There's a family owned place by me called Edmond Marks that does good work. http://www.edmondmarks.com/ and Advanced who I mentioned before likes to call me and tell me about their assembly options as well.



Over Seas


So most of my China production experience is with million unit plus volumes so that's not as helpful to you, but let me tell you it's a whole different experience :) I do know that people like IMS can help you take something over there if you get a little bit of volume so that's what I'd suggest. My advice to you would be pick a US partner who has the ability to outsource to a Mexico or China plant if you need it. You may not find as much of a cost advantage as you might think for your board though. Especially if you don't have a lot of hand operations.


Done!


If all that goes ok you'll have protos back that you can play with, and you'll have a good time finding all the things you did wrong that you need to fix for your next proto run.


Compliance and Testing


I should mention also that no matter what you do if you're going to sell these you'll also need to do FCC compliance testing (or other countries if you're selling internationally). In addition there are environmental regs like RoHS and REACH that apply both here and internationally. Don't sell 50,000 units with doing compliance testing, fines are a b*.


Here's some links just to the wiki pages for those:



Typically I pick a compliance lab that's near me. Now that happens to be NTS http://www.nts.com/, but I've also use TUV http://www.tuv.com/global/en/index.html, met labs http://www.metlabs.com/ and even UL http://www.ul.com/ themselves once or twice. I've also used small independent places. They can all help you but I like to pick someplace close by so I can sneak in when I need to.


You may also want to do UL safety testing to ensure your product is safe, in which case any UL lab mentioned above can help you. My guess is you'd be under UL 60950 which is for telecom products.



2.) Use Consultants


Listen everyone here started out at one point with no idea how do to a schematic or layout a board. If we can learn you can to. That said if you can afford it there's nothing wrong with have a consultant do it for you. Just remember that no one loves your product like you do so stay on top of them. I don't consider the PI boards to be very complex but it's not exactly a beginner board. Personally I would stick to the US or Canada for my first attempt. However if you really are going to order 20,000-50,000 I know there are small China (prob US too) manufacturer who would take your design, do the work and then manf for you just to get the business. I've worked with guys like that before, but just keep in mind it's not that hard for them to copy your design... :) Happens all the time.


Also distance, time shift, and language barrier can be difficult but not impossible to over come. One nice thing about this is if you have a day job you can work at night on your project with your guys overseas. (I've certainly never done that before...)


These are the only guys I've ever done a product with, there are countless others but here are some examples who did well by me:



3.) Build Your Own Team


Well listen if you can do it hire the right people, I've done pretty well walking into small places that are a mess on the hardware side and fixing lots of issues. Having the right people with the right knowledge (maybe the right tools if you're lucky). That's really invaluable. But that shouldn't scare you into riding out into the unknown by yourself. This would definitely be the safest route, but hey if we all took the safe route what fun would that be.


You could also consider outsourcing and building your team in another country. I find that this is full of pitfalls though. You really need to know what you're doing yourself in order to manage this, it's hard to outsource effectively if you don't have the expertise in house to know what's going on.


Finishing up


Some last words of advice from a guy who's made a lot of products :P If you really have a channel to move 50,000 units then great. If that's just speculation though don't stick your neck out buying a big order to keep your prices down. Find a way to make it work where you're only making say a 100 and you can still sell them without losing money.



Lastly if your pi project is epic enough to sell 50k units consider doing a kickstarter (www.kickstarter.com) project and seeing if you can pre-sell any. They have a new requirement that you have a working proto and demonstrate what you would do with the money, but many a cool project have been given life there.


Good Luck, and ask us questions as you go.


What are some insights from looking at Bode plots


After studying this in school, the entire concept of a Bode plot still seems to be as a bit of a let down for me given how much emphasis is placed upon it, how often this tool is rumored to be used in the workplace and how little it actually seems to offer. Much ado is placed on how to analytically draw the Bode plot, but very little is said about its interpretation. How does this thing relate back to real life?


Most Bode plots look like this: enter image description here



I honestly have to say I am not in the least impressed by this plot. All that the Bode plot is telling me is that as frequency go up, at frequency of 1 Hz, there is a peak in system response, then it goes down afterwards (surprise surprise). The phase is a bit more enigmatic, it seems to tell me that the signal experiences a larger delay as frequency goes up.


What are some conclusions that an experienced engineer is able to see from looking at these Bode plots. Are there things that are not obvious that is blocking me from seeing the utility of these bodes plots?


Since I have not done much real life engineering work with Bode plot, can someone please show me an example of a bode plot of a real system that actually provides some more interesting insights?



Answer



One of the main innovations Bode proposed with Bode Stability plots was how the plot asymptotes behave for stable systems. A knowledge of these rules allows compensation just by manipulating the asymptotes. Much simpler than mathematical techniques like pole placement.


Some main ones spring to mind (but it's not an exhaustive list):




  1. When the magnitude crosses from >0dB to <0dB at a lower frequency than the Phase=180degrees then the system is stable.





  2. At this crossover frequency your Phase Margin is your "insurance policy" against unmodelled delay. It's only 20 degrees to instability for your system.




  3. Falling magnitude and rising phase implies a non-minimum phase system (RHP zeros).




  4. A 1-slope (-20dB/dec) at crossover is stable and is equivalent to -90 degrees. (In fact the magnitude is the integral of the phase by Bode's Theorem).





  5. A 2nd order system that falls at 2-slope (magnitude) can be adequately compensated by crossing at a 1-slope in the vicinity of the crossover.




arduino - Can I use TI&#39;s cc2541 BLE as micro controller to perform operations/ processing instead of ATmega328P AU to save cost?

I am using arduino pro mini (which contains Atmega328p AU ) along with cc2541(HM-10) to process and transfer data over BLE to smartphone. I...